翼度科技»论坛 编程开发 python 查看内容

Python量化因子测算与绘图超详细流程代码

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
量化因子的测算通常都是模拟交易,计算各种指标,其中:

  • 测算需要用到的第三方库:numpy,pandas,talib
  • 绘图需要用到的第三方库:matplotlib,seaborn
其他库随策略的需要额外添加

因子测算框架

这里博主分享自己测算时常使用的流程,希望与大家共同进步!
测算时从因子到收益的整个流程如下:策略(因子组合) -> 买卖信号 -> 买点与卖点 -> 收益
因此我们在测算时,针对每一个个股:

1. 预处理股票数据

首先这里是常用的一个工具导入,包括测算用的库与绘图用的库(含图片中文显示空白解决方案)
  1. # 测算用
  2. import numpy as np
  3. import pandas as pd
  4. from copy import deepcopy
  5. from tqdm import tqdm
  6. from datetime import datetime
  7. import talib
  8. # 绘图用
  9. import matplotlib as mpl
  10. import matplotlib.pyplot as plt
  11. import seaborn as sns
  12. %matplotlib inline
  13. # 绘图现实中文
  14. sns.set()
  15. plt.rcParams["figure.figsize"] = (20,10)
  16. plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']  # 当前字体支持中文
  17. plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题
  18. # 其他
  19. import warnings
  20. warnings.filterwarnings("ignore")
复制代码
然后是循环读取股票的代码:
  1. import os
  2. def readfile(path, limit=None):
  3.     files = os.listdir(path)
  4.     file_list = []
  5.     for file in files:  # 遍历文件夹
  6.         if not os.path.isdir(file):
  7.             file_list.append(path + '/' + file)
  8.     if limit:
  9.         return file_list[:limit]
  10.     return file_list
  11. stock_dict = {}
  12. for _file in tqdm(readfile("../data/stock_data")):
  13.     if not _file.endswith(".pkl"):
  14.         continue
  15.     # TODO 这里可以添加筛选,是否需要将当前的股票添加到测算的股票池中
  16.     file_df = pd.read_pickle(_file)
  17.     file_df.set_index(["日期"], inplace=True)
  18.     file_df.index.name = ""
  19.     file_df.index = pd.to_datetime(file_df.index)
  20.     file_df.rename(columns={'开盘':'open',"收盘":"close","最高":"high","最低":"low","成交量":"volume"},inplace=True)
  21.     stock_code = _file.split("/")[-1].replace(".pkl", '')
  22.     # TODO 这里可以添加日期,用来截取一部分数据
  23.     stock_dict[stock_code] = file_df
复制代码
上面一部分是处理股票数据,处理后的数据都会保存在 stock_dict 这个变量中,键是股票的代码,值是股票数据

2. 指标测算

测算指标时,我们以一只股票为例:
  1. for _index,_stock_df in tqdm(stock_dict.items()):
  2.     measure_df = deepcopy(_stock_df)
复制代码
代码中的:

  • 这里的measure_df即要测算的dataframe数据
  • 使用deepcopy是防止测算的过程影响到原始数据
然后我们就可以循环这一个股票的每一行(代表每一天),测算的交易规则如下:

  • 买入规则:买入信号发出&当前没有持仓,则买入
  • 卖出规则:卖出信号发出&当前有持仓,则卖出
  1. # 开始测算
  2. trade_record_list = []
  3. this_trade:dict = None
  4. for _mea_i, _mea_series in measure_df.iterrows(): # 循环每一天
  5.     if 发出买入信号:
  6.         if this_trade is None:  # 当前没有持仓,则买入
  7.             this_trade = {
  8.                 "buy_date": _mea_i,
  9.                 "close_record": [_mea_series['close']],
  10.             }
  11.     elif 发出卖出信号:
  12.         if this_trade is not None:  # 要执行卖出
  13.             this_trade['sell_date'] = _mea_i
  14.             this_trade['close_record'].append(_mea_series['close'])
  15.             trade_record_list.append(this_trade)
  16.             this_trade = None
  17.     else:
  18.         if this_trade is not None:  # 当前有持仓
  19.             this_trade['close_record'].append(_mea_series['close'])
复制代码
上述代码中,我们将每一个完整的交易(买->持有->卖),都保存在了trade_record_list变量中,每一个完整的交易都会记录:
  1. {
  2.     'buy_date': Timestamp('2015-08-31 00:00:00'), # 买入时间
  3.     'close_record': [41.1,42.0,40.15,40.65,36.6,32.97], # 收盘价的记录
  4.     'sell_date': Timestamp('2015-10-12 00:00:00')} # 卖出时间
  5.     # TODO 也可以添加自定义记录的指标
  6. }
复制代码
3. 测算结果整理

直接使用 pd.DataFrame(trade_record_list),就可以看到总的交易结果:

整理的过程也相对简单且独立,就是循环这个交易,然后计算想要的指标,比如单次交易的年化收益可以使用:
  1. trade_record_df = pd.DataFrame(trade_record_list)
  2. for _,_trade_series in trade_record_df.iterrows():
  3.     trade_record_df.loc[_i,'年化收益率'] = (_trade_series['close_record'][-1] - _trade_series['close_record'][0])/_trade_series['close_record'][0]/(_trade_series['sell_date'] - _trade_series['buy_date']).days * 365 # 年化收益
  4.     # TODO 这里根据自己想要的结果添加更多的测算指标
复制代码
4. 结果绘图

绘图的代码通常比较固定,比如胜率图:
  1. # 清理绘图缓存
  2. plt.cla()
  3. plt.clf()
  4. # 开始绘图
  5. plt.figure(figsize=(10, 14), dpi=100)
  6. # 使用seaborn绘制胜率图
  7. fig = sns.heatmap(pd.DataFrame(total_measure_record).T.round(2), annot=True, cmap="RdBu_r",center=0.5)
  8. plt.title("胜率图")
  9. scatter_fig = fig.get_figure()
  10. # 保存到本地
  11. scatter_fig.savefig("胜率图")
  12. scatter_fig.show() # 最后显示
复制代码

到此这篇关于Python量化因子测算与绘图超详细流程代码的文章就介绍到这了,更多相关Python量化因子测算内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/article/276306.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具