python使用pandas进行量化回测
作者:神出鬼没,指的就是我! 时间:2021-10-12 12:37:29
下面文章描述可能比excel
高级一点,距离backtrader
这些框架又差一点。做最基础的测试可以,如果后期加入加仓功能,或者是止盈止损等功能,很不合适。只能做最简单的技术指标测试。
导包,常用包导入:
import os
import akshare as ak
import requests
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import talib as ta
%matplotlib inline
plt.style.use("ggplot")
获取数据,本文使用akshare中债券数据为对象分析:
bond_zh_hs_daily_df = ak.bond_zh_hs_daily(symbol="sh010107")
添加指标:
def backtest_trend_strategy(ohlc: pd.DataFrame,
fast_period: int = 50,
slow_period: int = 200,
threshold: float = 1.0) -> pd.DataFrame:
"""封装向量化回测的逻辑"""
# 计算指标
ohlc["fast_ema"] = talib.EMA(ohlc.close, fast_period)
ohlc["slow_ema"] = talib.EMA(ohlc.close, slow_period)
ohlc["pct_diff"] = (ohlc["fast_ema"] / ohlc["slow_ema"] - 1) * 100
# 生成信号,1表示做多,-1表示做空,0表示空仓
ohlc["signal"] = np.where(ohlc["pct_diff"] > threshold, 1, 0)
ohlc["signal"] = np.where(ohlc["pct_diff"] < -threshold, -1, ohlc["signal"])
# 计算策略收益率
ohlc["returns"] = np.log(ohlc["close"] / ohlc["close"].shift(1))
ohlc["strategy"] = ohlc["signal"].shift(1) * ohlc["returns"]
ohlc["strategy_returns"] = ohlc["strategy"].cumsum()
return ohlc
运行策略,并绘制图片:
data = strategy1(data)
fig, ax = plt.subplots(nrows=3, ncols=1, figsize=(12, 15), sharex=True)
ax[0].plot(data.index, data["close"])
ax[0].plot(data.index, data["fast_ema"])
ax[0].plot(data.index, data["slow_ema"])
ax[0].set_title("Price and Indicators")
ax[1].plot(data.index, data["signal"])
ax[1].set_title("Strategy Position")
data[["returns", "strategy"]].cumsum().plot(ax=ax[2], title="Strategy Return")
参数优化:
# 选择核心参数和扫描区间,其它参数保持不变
fast_period_rng = np.arange(5, 101, 5)
total_return = []
for fast_period in fast_period_rng:
ohlc = data.filter(["open", "high", "low", "close"])
res = backtest_trend_strategy(ohlc, fast_period, 200, 1.0)
total_return.append(res["strategy_returns"].iloc[-1])
# 散点图:策略收益率 vs 快速均线回溯期
fig, ax = plt.subplots(figsize=(12, 7))
ax.plot(fast_period_rng, total_return, "r-o", markersize=10)
ax.set_title("Strategy Return vs Fast period")
ax.set_xlabel("fast_period")
ax.set_ylabel("return(%)")
来源:https://blog.csdn.net/qq_26742269/article/details/123697226
标签:python,pandas,量化回测
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Python中的Dict(下篇)
2021-11-10 17:16:14
![](https://img.aspxhome.com/file/2023/0/90920_0s.png)
golang中值类型/指针类型的变量区别总结
2023-09-02 15:07:11
python数组和矩阵的用法解读
2023-07-13 07:38:18
![](https://img.aspxhome.com/file/2023/7/110557_0s.png)
Python学习之基础语法介绍
2022-03-22 22:08:54
![](https://img.aspxhome.com/file/2023/3/99703_0s.jpg)
Python 中制作偶数列表的方法
2022-08-20 20:15:56
![](https://img.aspxhome.com/file/2023/8/63928_0s.webp)
学习CSS布局心得
2007-05-11 16:50:00
Python中namedtuple 命名元祖的使用
2023-02-20 15:06:00
Python实现的数据结构与算法之基本搜索详解
2021-07-25 03:47:44
![](https://img.aspxhome.com/file/2023/4/67934_0s.png)
python 使用csv模块读写csv格式文件的示例
2021-04-24 15:58:28
Laravel框架实现定时发布任务的方法
2023-11-22 23:54:57
asp怎么实现中文字符串按声母检索
2010-05-16 21:19:00
50个常用sql语句 网上流行的学生选课表的例子
2012-07-11 16:02:01
Python绘图之柱形图绘制详解
2023-08-16 16:16:49
![](https://img.aspxhome.com/file/2023/3/97333_0s.jpg)
Python实现字典的key和values的交换
2021-08-18 03:45:49
sqlserver 2000中创建用户的图文方法
2012-03-26 18:26:39
Dreamweaver制作技巧四则
2008-01-04 09:42:00
通过pycharm使用git的步骤(图文详解)
2023-07-24 14:43:21
![](https://img.aspxhome.com/file/2023/3/104823_0s.png)
python任务调度实例分析
2021-06-30 12:42:57
用ASP和XMLHTTP分析远程XML文件
2007-12-12 12:48:00
python+selenium 实现扫码免密登录示例代码
2021-02-03 06:41:57