下面是代码,需要在python3环境下使用,但需要注意:
1、自己去加载库;
2、在线数据库来源baostock,感谢!
3、按 filepath = r'c:\DataCenter\Stock\\' 的要求先建立磁盘目录。
4、我是新手,不太会用,所以格式可能会不对,若需要源文件可以Q我,18518244。
5,最重要的是它只是一个工具,能不能很好的使用还需要有心得体会。
#YJ_DATA_CENTER
import baostock as bs
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import datetime
# 定义数据文件存储和读取目录
filepath = r'c:\DataCenter\Stock\\'
# 定义数据库获取数据的开始时间,暂定今日往前400天,目的是为了计算60日均线留余量,可调整
startdate = (datetime.date.today() - datetime.timedelta(days=400)).strftime("%Y-%m-%d")
# 核心!定义加权计算重要参数,会直接影响到后续图形和判断交叉点
b5 = np.array([2,3,4,4,5])
w5 = b5 / sum(b5)
wv5 = 1/5
b15 = np.array([6,7,7,8,8,8,9,9,9,10,11,13,13,14,15])
w15 = b15 / sum(b15)
w60 = 1/60
# while 语名的目的,是为了重复循环,便利多次检索
while True:
print('Please imput data code. Format = xx.xxxxxx, example = sh.000001 or sz.000001')
filename = input()
# name_join和newS两个变量的引入,是为了对filename进行重写。这是MySQL带“.”文件名不能读取造成的,这个版本的APP不带连接MySQL,懒得改了。
name_join = list(filename)
name_join[2] = ''
newS = ''.join(name_join)
# 登陆数据库,并获取数据
# 共16项列名参数"date,code,open,high,low,close,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",目前使用"date,close,volume"三项,主要是因为目前计算图形只需要“日期、收盘价、成交量”三个数据来进行计算,其余参数的使用待开发。
lg = bs.login()
rs = bs.query_history_k_data_plus(filename,"date,close,volume",start_date = startdate, end_date = "",frequency = "d", adjustflag = "3")
data_list = []
while (rs.error_code == '0') & rs.next():
data_list.append(rs.get_row_data())
bs.logout()
result = pd.DataFrame(data_list, columns = rs.fields)
result.to_csv(filepath + newS + '.txt', index = False)
result = pd.read_csv(filepath + newS+'.txt')
result.index = result.iloc[:,0]
result.index = pd.to_datetime(result.index,format = '%Y-%m-%d')
result = result.iloc[:,1:] # iloc[:,:]参数和startdate可以综合使用,看需要多少的数据量保存到本地,及多少数据量来进行分析决定
# 通过权重参数的计算,获取绘图数据
close=result.close
volume=result.volume
expma5 = pd.Series(0.0,index=close.index)
expma15 = pd.Series(0.0,index=close.index)
expma60 = pd.Series(0.0,index=close.index)
expmavolume5 = pd.Series(0.0,index=volume.index)
expmavolume60 = pd.Series(0.0,index=volume.index)
for i in range(4,len(close)):
expma5[i]=sum(w5*close[(i-4):(i+1)])
expmavolume5[i]=sum(wv5 *volume[(i-4):(i+1)])
for i in range(14,len(close)):
expma15[i]=sum(w15*close[(i-14):(i+1)])
for i in range(59,len(close)):
expma60[i]=sum(w60*close[(i-59):(i+1)])
expmavolume60[i]=sum(w60*volume[(i-59):(i+1)])
# 绘制两个子图,一个是收盘价子图,一个是成交量子图
plt.figure(figsize=(32,18))
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.subplot(2,1,1)
plt.plot(close[0:],label = "当日收盘价", color = 'b')
plt.plot(expma5[4:],label = "5日加权均线",color = 'r',linestyle = 'dashed')
plt.plot(expma15[14:],label = "15日加权均线",color = 'g',linestyle = 'dashed')
plt.plot(expma60[59:],label = "60日移动均线",color = 'y',linestyle = 'dashed')
plt.ylabel('close')
plt.title(newS + ' Date-Close-Volume')
plt.legend()
plt.subplot(2,1,2)
plt.plot(volume[0:],label = "当日成交量", color = 'b')
plt.plot(expmavolume5[4:],label = "5日成交均量",color = 'r',linestyle = 'dashed')
plt.plot(expmavolume60[59:],label = "60日成交均量",color = 'y',linestyle = 'dashed')
plt.xlabel('date')
plt.ylabel('volume')
plt.legend()
# 可以保存到本地png文件,也可以直接打开,个人喜好,自己选择,我更喜欢保存本地,这样线型显示更清楚,但缺点是点数据不能反映。
plt.savefig(filepath+newS+'.png')
# plt.show()