Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo Candlestick chart (nến) với Bokeh trong Python


Bokeh là package Python trực quan hóa dữ liệu, mã nguồn mở. Bokeh render bằng HTML/JavaScript → phù hợp dashboard web.

Bokeh tương thích NumPy, Pandas. Tạo biểu đồ tương tác, dashboard.

Dependencies: NumPy, Pillow, Jinja2, Packaging, PyYAML, Six, Tornado, python-dateutil.

Cài đặt Windows: pip3 install bokeh | Anaconda: conda install bokeh

Ví dụ

from math import pi
import pandas as pd
from bokeh.plotting import figure, output_file, show
from bokeh.sampledata.stocks import MSFT

my_df = pd.DataFrame(MSFT)[:35]
my_df["date"] = pd.to_datetime(my_df["date"])

inc = my_df.close > my_df.open
dec = my_df.open > my_df.close
w = 12*60*60*1000  # half day in ms

TOOLS = "pan,wheel_zoom,box_zoom,reset,save"

p = figure(x_axis_type="datetime", tools=TOOLS, plot_width=1000, title="Candlestick using MSFT data")
p.xaxis.major_label_orientation = pi/4
p.grid.grid_line_alpha = 0.3

p.segment(my_df.date, my_df.high, my_df.date, my_df.low, color="black")
p.vbar(my_df.date[inc], w, my_df.open[inc], my_df.close[inc], fill_color="#D5E1DD", line_color="black")
p.vbar(my_df.date[dec], w, my_df.open[dec], my_df.close[dec], fill_color="#F2583E", line_color="black")

output_file("candlestick.html", title="candlestick plot")
show(p)

Lưu ý: Cần bokeh.sampledata.download() để tải sample dataset.

Đầu ra

Tạo Candlestick chart (nến) với Bokeh trong Python

Giải thích

  • Import package, alias.
  • Dữ liệu MSFT có sẵn trong Bokeh, chuyển DataFrame.
  • Gọi figure() với x_axis_type datetime, tools, width, title.
  • output_file() chỉ định file HTML output.
  • Định nghĩa TOOLS tương tác.
  • segment() vẽ影 (high-low), vbar() vẽ thân nến (tăng/xanh, giảm/đỏ).
  • show() hiển thị biểu đồ.