highstock比matplotlib方便的是提供交互
def candlestick_processor(df_options):
# df_options:为df转化后的数据
# 蜡烛图
# 生成ohlc:从series中读取OHLC数据(前四列)合并
ohlc_series = {}
sma_series={}
other_series = []
series = df_options['series']
for s in series:
if s['name'] in {'open', 'high', 'low', 'close'}:
ohlc_series[s['name']] = s
elif s['name'] in {'sma_10'}:
sma_series[s['name']]=s
else:
other_series.append(s)
if len(ohlc_series) != 4:
print('【错误】蜡烛图,没有找到open, high, low, close数据,请确保输入的数据有这四列')
return None
ohlc_data = []
for i in range(0, len(ohlc_series['open']['data'])):
row = [ohlc_series['open']['data'][i][0]]
for j in ['open', 'high', 'low', 'close']:
row.append(ohlc_series[j]['data'][i][1])
ohlc_data.append(row)
sma_data=[]
for i in range(0,len(sma_series['sma_10']['data'])):
xrow = [sma_series['sma_10']['data'][i][0]]
for j in ['sma_10']:
xrow.append(sma_series[j]['data'][i][1])
sma_data.append(xrow)
df_options['series'] = [{'data': ohlc_data, 'name': 'OHLC', 'yAxis': 0, 'type': 'candlestick',},
{'data':sma_data,'name':'sma_10','yAxis':0,'type':'spline',}] + other_series
if other_series:
# 设置其他数据使用第二个y轴
for s in other_series:
s.update({'yAxis':1, 'type': 'column'})
y_axis = [
{
'labels': {'align': 'right', 'x': -3},
'title': {'text': 'OHLC'},
'height': '60%', 'lineWidth': 2
},
{
'labels': {'align': 'right', 'x': -3},
'top': '65%', 'height': '35%', 'offset': 0, 'lineWidth': 2,
}
]
df_options = T.deep_update(df_options, {'yAxis': y_axis})
return df_options
data = D.history_data(['000001.SHA'], start_date='2017-01-01', end_date='2017-06-30',
fields=['close','high','open','low','volume'])
data=data.set_index('date')
del data['instrument']
data['sma_10'] = talib.SMA(np.array(data['close'].astype('double')), 10)
T.plot(data, options=candlestick_processor, title='股票数据分析', stock=True)