烛台图也叫K线图,通常用作交易工具,用来显示和分析证券、衍生工具、外汇货币、股票、债券等商品随着时间的价格变动。
由于不是专业的金融从业者,这里只是简单的进行分享,更多用法可参考baostock 数据平台[1]、mplfinance文档[2]以及Candlestick charts in Python - Plotly[3]
获取股票数据
# 获取股票数据
import baostock as bs
import pandas as pd
lg = bs.login()
rs = bs.query_history_k_data_plus("sh.600000",
"date,open,high,low,close",
start_date='2022-01-01', end_date='2022-03-31',
frequency="d", adjustflag="2")
data_list = []
while (rs.error_code == '0') & rs.next():
data_list.append(rs.get_row_data())
result = pd.DataFrame(data_list, columns=rs.fields)
# 将date转为索引
result['date'] = pd.to_datetime(result['date'])
result.set_index('date', inplace=True)
# 更换字段类型
for col in ['open', 'high', 'low', 'close']:
result[col] = result[col].astype(float)
bs.logout()
基于mplfinance
import mplfinance as mpf
moving_averages = [5,10,15] # 需要绘制的均线
mpf.plot(result,
type='candle',
mav=moving_averages)
基于plotly
import plotly.graph_objects as go
result['moving3'] = result['close'].rolling(3).mean()
result['moving8'] = result['close'].rolling(8).mean()
fig = go.Figure(data=[go.Candlestick(
x = result.index, # 日期索引
open = result['open'],
high = result['high'],
low = result['low'],
close = result['close'],
# bar颜色
increasing_line_color = 'purple',
decreasing_line_color = 'orange',
showlegend=False
),
# 均线
go.Scatter(x=result['moving3'].index,
y=result['moving3'],
line=dict(color='gray',
width=1,
shape='spline'), # smooth the line
name='MA3'),
go.Scatter(x=result['moving8'].index,
y=result['moving8'],
line=dict(color='black',
width=1,
shape='spline'), # smooth the line
name='MA8')
])
# 屏蔽默认滑块
fig.update_layout(xaxis_rangeslider_visible=False,
autosize=False,
width=700,
height=500,
legend=dict(
x=0.82,
y=0.98,
font=dict(size=12)
))
以上基于baostock获取股票数据,并利用mplfinance和plotly快速绘制烛台图。
共勉~
[1] baostock 数据平台: http://www.baostock.com/
[2] mplfinance文档: https://pypi.org/project/mplfinance/
[3] Candlestick charts in Python - Plotly: https://plotly.com/python/candlestick-charts/