股票走势及K线绘制练习代码笔记(无注释)
import tushare as ts
df=ts.get_k_data('000002',start='2000-01-01',end='2022-01-01')
df.head()
import tushare
print(tushare.__version__)
df.set_index('date',inplace=True)
df['close'].plot()
import matplotlib.pyplot as plt
from datetime import datetime
import tushare as ts
df=ts.get_k_data('000002',start='2000-01-01',end='2022-01-01')
df['date']=df['date'].apply(lambda x:datetime.strptime(x, '%Y-%m-%d'))
plt.figure(dpi=300,figsize=(12,6))
plt.plot(df['date'],df['close'])
plt.show()
type(df)
import tushare as ts
import matplotlib.pyplot as plt
import mpl_finance as mpf
import seaborn as sns
df=ts.get_k_data('000002','2019-06-01','2019-09-30')
from matplotlib.pylab import date2num
import datetime
def date_to_num(dates):
num_time=[]
for date in dates:
date_time=datetime.datetime.strptime(date,'%Y-%m-%d')
num_date=date2num(date_time)
num_time.append(num_date)
return num_time
df_arr=df.values
df_arr[:,0]=date_to_num(df_arr[:,0])
df_arr[:5]
fig,ax=plt.subplots(figsize=(15,6))
mpf.candlestick_ochl(ax,df_arr,width=0.6,colorup='r',colordown='g',alpha=1.0)
plt.grid(True)
ax.xaxis_date()
df['MA5']=df['close'].rolling(5).mean()
df['MA10']=df['close'].rolling(10).mean()
df.head(15)
plt.rcParams['font.sans-serif']='SimHei'
fig,axes=plt.subplots(2,1,sharex=True,figsize=(15,8))
ax1,ax2=axes.flatten()
mpf.candlestick_ochl(ax1,df_arr,width=0.6,colorup='r',colordown='g',alpha=1.0)
ax1.plot(df_arr[:,0],df['MA5'],label='5日均线')
ax1.plot(df_arr[:,0],df['MA10'],label='10日均线')
ax1.grid(True)
ax1.set_title('万科A')
ax1.set_xlabel('日期',x=1,y=-0.1)
ax1.set_ylabel('价格',x=-0.1,y=1)
ax1.legend()
ax.xaxis_date()
ax2.bar(df_arr[:,0],df_arr[:,5])
ax2.set_xlabel('日期',x=1,y=-0.1)
ax2.set_ylabel('成交量',x=-0.1,y=1)
ax2.grid()
ax2.xaxis_date()
结果1:
结果2: