python:mpf 画股票K线图+ MA10 + SAR

kline_sar.py

# coding: utf-8
import os, sys
import datetime
import matplotlib.pyplot as plt
from matplotlib.pylab import date2num
#import matplotlib.finance as mpf
import mpl_finance as mpf
import pandas as pd
import tushare as ts
import talib

if len(sys.argv) ==2:
    code = sys.argv[1]
else:
    print('usage: python kline_sar.py stockcode ')
    sys.exit(1)

if len(code) !=6:
    print('stock code length: 6')
    sys.exit(2)
    
# help(ts.get_k_data) 了解参数
df = ts.get_k_data(code)
df = df[ df['date'] >'2020-01-01']
if len(df) <10:
    print(" len(df) <10 ")
    sys.exit(2)

# SAR,Stop and Reverse,是 Welles Wilder发明的,SAR是一个基于价格/时间的指标.
sar = talib.SAR(df.high, df.low)
print(sar[-5:])

# 对tushare获取到的数据转换成 candlestick_ohlc()方法可读取的格式
alist = []
tlist = []
for idx,row in df.iterrows():
    date,open,close,high,low,volume = row[0:6]
    # 将日期转换为数字
    date1 = datetime.datetime.strptime(date,'%Y-%m-%d')
    t = date2num(date1)
    data = (t,open,high,low,close)
    alist.append(data)
    tlist.append(t)

# 加这个两句 可以显示中文
plt.rcParams['font.sans-serif'] = [u'SimHei'] 
plt.rcParams['axes.unicode_minus'] = False

# 创建子图
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
# 设置X轴刻度为日期时间
ax.xaxis_date()
ax.autoscale_view()
#plt.setp(plt.gca().get_xticklabels(), rotation=45)
plt.xticks(rotation=45)
plt.yticks()
plt.title("股票 {0}:K线图".format(code))
plt.xlabel("date")
plt.ylabel("price")
mpf.candlestick_ohlc(ax,alist,colorup='red',colordown='green')
#  画 10日均线 , SAR 散点图
df['ma10'] = df['close'].rolling(window=10).mean()
plt.plot(tlist, df['ma10'].values, 'blue', label='ma10')
plt.plot(tlist, sar, '.', c='black', label='sar')
plt.legend(loc='best', shadow=True)
plt.grid()
plt.show()

运行 python kline_sar.py 000063

python:mpf 画股票K线图+ MA10 + SAR_第1张图片

你可能感兴趣的:(python)