课程参考:网易云课堂 基于Python的量化指数基金投资
量化用到的数据源来自baostock,可以通过www.baostock.com网址进行访问,它是一个免费、开源的证券数据平台(无需注册),提供大量准确、完整的证券历史行情数据、上市公司财务数据等。
可以通过提供的python API获取证券数据信息,满足量化交易投资、金融数据分析、计量经济数据需求。
返回的数据格式为pandas DataFrame类型,以便于用pandas/NumPy/Matplotlib进行数据分析和可视化。 同时支持通过BaoStock的数据存储功能,将数据全部保存到本地后进行分析。目前版本BaoStock.com只支持Python3.5及以上,暂不支持python 2.x。
安装方式pip install baostock
也可以使用国内源安装:
pip install baostock -i https://pypi.tuna.tsinghua.edu.cn/simple/--trusted-host pypi.tuna.tsinghua.edu.cn
baostock提供了完备的API进行数据获取
例如获取历史A股K线数据:query_history_k_data_plus()
import baostock as bs
import pandas as pd
#### 登陆系统####
lg = bs.login()
# 显示登陆返回信息
print('login responderror_code:'+lg.error_code)
print('login respond error_msg:'+lg.error_msg)
#### 获取沪深A股历史K线数据####
# 详细指标参数,参见“历史行情指标参数”章节;“分钟线”参数与“日线”参数不同。“分钟线”不包含指数。
# 分钟线指标:date,time,code,open,high,low,close,volume,amount,adjustflag
# 周月线指标:date,code,open,high,low,close,volume,amount,adjustflag,turn,pctChg
rs =bs.query_history_k_data_plus("sh.600000",
"date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST",
start_date='2010-07-01', end_date='2021-02-19',
frequency="d", adjustflag="3")
print('query_history_k_data_plus responderror_code:'+rs.error_code)
print('query_history_k_data_plusrespond error_msg:'+rs.error_msg)
#### 打印结果集####
data_list = []
while (rs.error_code == '0') &rs.next():
#获取一条记录,将记录合并在一起
data_list.append(rs.get_row_data())
result = pd.DataFrame(data_list,columns=rs.fields)
#### 结果集输出到csv文件####
result.to_csv("D:\\history_A_stock_k_data.csv",index=False)
print(result)
#### 登出系统####
bs.logout()
程序运行完后会返回相应的数据,并按照你指定的文件路径存储为csv文件。
然后可以通过
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import math as math
stock_info = pd.read_csv("D:\\history_A_stock_k_data.csv")
size_title = 28
size_label = 23
size_text = 35
size_line = 3
size_rotation = 20
size_marker = 23
list_tmp = list(stock_info['close'])
index_max = list_tmp.index(max(list_tmp))
plt_gap = 8
plt.figure(0)
plt.rcParams["axes.grid"] = True
plt.rcParams['font.sans-serif'] =['SimHei']
plt.rcParams["grid.linestyle"] =(3, 5)
plt.plot(stock_info['close'],'tomato',linewidth=size_line)
font = {'size': 30, 'color': 'tomato','weight': 'black'}
plt.text(index_max+30, list_tmp[index_max],str("{:.2f}".format(list_tmp[index_max])), fontdict=font)
plt.plot(index_max, list_tmp[index_max],color='cornflowerblue', marker='o', ms=size_marker)
plt.text(1+30, list_tmp[0]+1,str("{:.2f}".format(list_tmp[0])), fontdict=font)
plt.plot(1, list_tmp[0],color='cornflowerblue', marker='o', ms=size_marker)
plt.text(len(list_tmp)+30, list_tmp[-1]+1,str("{:.2f}".format(list_tmp[-1])), fontdict=font)
plt.plot(len(list_tmp)+30, list_tmp[-1],color='cornflowerblue', marker='o', ms=size_marker)
plt_xticks =stock_info['date'].values[1:len(stock_info['date']):1].tolist()
plt.xticks(range(len(plt_xticks),0,-math.floor(len(plt_xticks)/plt_gap)),plt_xticks[len(plt_xticks):0:-math.floor(len(plt_xticks)/plt_gap)],rotation=size_rotation)
plt.tick_params(labelsize=size_label)
plt.title('股价走势',size=size_title)
plt.figure(1)
plt.rcParams["axes.grid"] = True
plt.rcParams['font.sans-serif'] =['SimHei']
plt.rcParams["grid.linestyle"] =(3, 5)
plt.gca()
# plt.grid(True)
plt.subplot(321)
plt.plot(stock_info['close'],'tomato')
plt_xticks =stock_info['date'].values[1:len(stock_info['date']):1].tolist()
plt.xticks(range(len(plt_xticks),0,-math.floor(len(plt_xticks)/plt_gap)),plt_xticks[len(plt_xticks):0:-math.floor(len(plt_xticks)/plt_gap)],rotation=0)
plt.title('价格')
plt.subplot(322)
plt.plot(stock_info['pbMRQ'] /stock_info['peTTM'],'tomato')
plt.xticks(range(len(plt_xticks),0,-math.floor(len(plt_xticks)/plt_gap)),plt_xticks[len(plt_xticks):0:-math.floor(len(plt_xticks)/plt_gap)],rotation=0)
plt.title('ROE')
plt.subplot(323)
plt.plot(stock_info['pbMRQ'],'tomato')
plt.xticks(range(len(plt_xticks),0,-math.floor(len(plt_xticks)/plt_gap)),plt_xticks[len(plt_xticks):0:-math.floor(len(plt_xticks)/plt_gap)],rotation=0)
data_calc = stock_info['pbMRQ']
xx = np.where(data_calc < data_calc.values[-1])
data_percentage =str("{:.2f}".format(100 * len(xx[0]) / data_calc.shape[0])) + '%'
plt.plot([len(data_calc),0],[data_calc.values[-1],data_calc.values[-1]],color='cornflowerblue',linewidth=1)
plt.title('市净率|' +data_percentage)
plt.subplot(324)
plt.plot(stock_info['peTTM'],'tomato')
plt.xticks(range(len(plt_xticks),0,-math.floor(len(plt_xticks)/plt_gap)),plt_xticks[len(plt_xticks):0:-math.floor(len(plt_xticks)/plt_gap)],rotation=0)
data_calc = stock_info['peTTM']
xx = np.where(data_calc < data_calc.values[-1])
data_percentage =str("{:.2f}".format(100 * len(xx[0]) / data_calc.shape[0])) + '%'
plt.plot([len(data_calc),0],[data_calc.values[-1],data_calc.values[-1]],color='cornflowerblue',linewidth=1)
plt.title('市盈率|' +data_percentage)
运行后可以画出相应的数据图
Baostock提供了非常丰富的数据,大家可以自行查阅相关接口和对应的数据关系。后续和大家分享的基于Python的量化指数基金投资方法都是采用的baostock数据。
网友评论