结论:移动平均线是不能和pd.to_datetime()一起的。
原因:stock_nums.close.rolling(5).mean().plot(label=‘ma5’,color=‘y’) 的下标stock_nums.index必须是dtype=‘object’,不能是dtype='datetime64[ns],pd.to_datetime(stock.index)就把下标变为日期型,导致两者不兼容。除非新增stock_nums.index = x,把下标换成数字,就没事了。
import talib
from mpl_finance import candlestick_ochl
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.pylab import date2num
stock = pd.read_csv('../stock_day.csv')
stock.sort_index(inplace=True)
# stock.index = pd.to_datetime(stock.index)
# stock['date'] = date2num(stock.index)
index = [i for i in range(stock.shape[0])]
stock['index'] = index
stock_k = stock[['index',"open","close","high","low"]]
nums = 200
stock_nums = stock_k[:nums]
arr = stock_nums.values
x = [i for i in range(nums)]
# stock_nums.index = x
stock_nums.index
dif,dea,bar = talib.MACD(stock_nums['close'].values,fastperiod=12,slowperiod=26,signalperiod=9)
fig,ax = plt.subplots(nrows=1,ncols=1,figsize=(18,8),dpi=100)
# ax.xaxis_date()
# bar[np.isnan(bar)] = 0
# plt.plot(x,dif,color='B',label='差离值 DIF')
# plt.plot(x,dea,color='m',label='讯号线 DEA')
# red_hist = np.where(bar>=0,bar,0)
# green_hist = np.where(bar<0,bar,0)
# plt.bar(x,red_hist,color='r',label='红色MACD值')
# plt.bar(x,green_hist,color='g',label='绿色MACD值')
candlestick_ochl(ax,arr,colorup='g',colordown='r')
stock_nums.close.rolling(5).mean().plot(label='ma5',color='y')
stock_nums.close.rolling(10).mean().plot(label='ma10',color='k')
plt.legend()
plt.show()