Backtesting.py 恒生指数

  • 简介
    • 载入packages
    • 读取数据
    • 策略遍历,选择夏普率最高的阈值和周期
    • 看看最大值是什么参数
    • 将参数套路策略,并查看回测图表
    • 查看逐次交易记录
    • 对先前得到的SR table计算9格mean和std
    • 计算SR of SR

简介

主要是使用backtesting.py做了个回测,对象是恒生指数,数据源是yahoo finance,策略是基于夏普率的Z-score 配合给定阈值,然后目标是计算9格平均夏普率的夏普率

载入packages

import numpy as np
import pandas as pd
from datetime import datetime%matplotlib inline
import matplotlib
import matplotlib.pyplot as pltfrom backtesting import Backtest, Strategy
from backtesting.lib import SignalStrategy
from backtesting.lib import crossover, compute_stats
from backtesting.test import SMA from yahoo_fin.stock_info import get_data

读取数据

data = get_data("^HSI", index_as_date = True, interval = "1d")
df = data.dropna()df = df[['open', 'high', 'low', 'close']]
df.columns = ['Open','High','Low','Close']

策略遍历,选择夏普率最高的阈值和周期

SR = []
SR1= []
period = (list(np.arange(5,1000,5))) #4年
threshhold_list = np.arange(0.25,2.75,0.25) #阈值为0.25~2.5,0.25为一跳
for i in threshhold_list:for j in period:class Strategy(SignalStrategy):   threshold = in = jdef init(self):super().init()   # Precompute the two moving averagesDR = pd.Series(self.data.Close).pct_change()*100MA = DR.rolling(window=self.n).mean()MAstd = DR.rolling(window=self.n).std(ddof= 1)Z = (DR - MA)/MAstd# Precompute signalsignal_long = (Z > self.threshold) & (Z.shift() < self.threshold)signal_short = (Z < -self.threshold) & (Z.shift() > -self.threshold)# combine signalsignal = signal_longsignal[signal_short] = -1# add signalentry_size = signal * 0.9999999 #这里如果=1的话每次只买一股,所以我要怎么完全all in 呢self.set_signal(entry_size = entry_size)bt = Backtest(df, Strategy,exclusive_orders = True,cash=10000000)result1 = bt.run()SR.append(pd.DataFrame(result1).loc["Sharpe Ratio"].tolist()[0])SR1.append(SR)SR = []
SR_table = pd.DataFrame(SR1, columns=period,index = threshhold_list)
SR_table

看看最大值是什么参数

param = SR_table.stack().idxmax()
print(param)

将参数套路策略,并查看回测图表

class Strategy(SignalStrategy):   threshold = param[0]n = param[1]def init(self):super().init()   # Precompute the two moving averagesDR = pd.Series(self.data.Close).pct_change()*100MA = DR.rolling(window=self.n).mean()MAstd = DR.rolling(window=self.n).std(ddof= 1)Z = (DR - MA)/MAstd# Precompute signalsignal_long = (Z > self.threshold) & (Z.shift() < self.threshold)signal_short = (Z < -self.threshold) & (Z.shift() > -self.threshold)# combine signalsignal = signal_longsignal[signal_short] = -1# add signalentry_size = signal * 0.9999999self.set_signal(entry_size = entry_size)bt = Backtest(df, Strategy,exclusive_orders = True,cash=10000000)
result1 = bt.run()
bt.plot()
print(result1)

查看逐次交易记录

去博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片.

result1._trades

对先前得到的SR table计算9格mean和std

这里主要是这样,比如

1 2 3
4 5 6
7 8 9

我们计算其平均值为(1+2+3+4+5+6+7+8+9)/9 = 5
那如果是

1 2 3 4
4 5 6 7
7 8 9 0
1 2 3 4

这样的我们就以4*4矩阵的中心4个数(5689)取各自的9格均数,计算为

5 4.89
5 4.89

这样

SR1_table = SR_table.copy().fillna(0)
mean_list_row = []
mean_list_col= []
mean_period = (list(np.arange(10,995,5)))
mean_threshhold_list = np.arange(0.5,2.5,0.25)
row = range(2,len(SR1_table))
col = range(2,len(SR1_table.columns))
for i in row:for j in col:ta = SR1_table.iloc[i-2:i+1,j-2:j+1]#print(ta)mean_list_row.append(ta.mean().mean())        mean_list_col.append(mean_list_row)mean_list_row = []mean_table = pd.DataFrame(mean_list_col,columns=mean_period,index = mean_threshhold_list)
mean_table

这里是计算std,同上

std_list_row = []
std_list_col= []row = range(2,len(SR1_table))
col = range(2,len(SR1_table.columns))
for i in row:for j in col:ta = SR1_table.iloc[i-2:i+1,j-2:j+1]std_list_row.append(ta.values.std(ddof = 1))        std_list_col.append(std_list_row)std_list_row = []std_table = pd.DataFrame(std_list_col,columns=mean_period,index = mean_threshhold_list)
std_table

计算SR of SR

SR_of_SR = mean_table/std_table
SR_of_SR

任务完成

https://colab.research.google.com/drive/1USLxSGoSEgR4QQL3kboY910WstfkqeA5#scrollTo=UOfThq6OqtXg

2021-09-30 Backtesting.py 恒生指数相关推荐

  1. 橘子CPS联盟操作手册2021.09

    橘子CPS联盟操作手册2021.09 目录 橘子CPS联盟操作手册2021.09 橘子CPS联盟是干嘛的 橘子CPS基本操作流程 PC端操作 1.注册 2.登陆 3.渠道管理 4.分享网站 5.分享网 ...

  2. JZOJ 7036. 2021.03.30【2021省赛模拟】凌乱平衡树(平衡树单旋+权值线段树)

    JZOJ 7036. 2021.03.30[2021省赛模拟]凌乱平衡树 题目大意 给出两棵Treap,大小分别为 n , m n,m n,m,每个点的 p r i o r i t y priorit ...

  3. 2021.09.27 MySQL笔记

    2021.09.27 MySQL笔记 文章目录 2021.09.27 MySQL笔记 一.展示当前存在的所有数据库 二.使用(选中)一个数据库 三.创建一个数据表 四.查询并展示该数据库内的所有数据表 ...

  4. 实习日志 (2021.09.13)

    2021.09.13星期一 今天把之前的算法题终于给弄明白了,并能够按照自己的思路去把他给完成,总结这个题目并不是很难,最重要的是要把链表给弄懂,一开始由于我对链表不是很熟悉,导致我在写该题目的时候花 ...

  5. 2021数学基础30讲扫描版 网盘(里面直接是文档,免费)

    2021数学基础30讲扫描版 网盘(里面直接是文档,无需付费) 考研数学基础(数一二三通用) https://pan.baidu.com/s/1tq_GzdapBpiPxjtu7entEw 提取码:s ...

  6. 2021/10/30的1+X大数据Java答案

    2021/10/30 步骤二 public Member() { }public Member(String name,String pwd,float score,int rank) {this.n ...

  7. 2021.1.30课程摘要(逻辑教育-王劲胜)

    2021.1.30课程摘要 逻辑教育-13期-Python基础班-王劲胜 一.集合 二.函数(上) 三.作业讲解 逻辑教育-13期-Python基础班-王劲胜 一.集合 1.集合简介 • 集合表现形式 ...

  8. 2021.09青少年软件编程(Python)等级考试试卷(三级)

    2021.09青少年软件编程(Python)等级考试试卷(三级) 一.单选题(共25题,每题2分,共50分) 1.使用map函数可以实现列表数据元素类型的转换,而无需通过循环.则将列表L=['1',' ...

  9. 2021.03.30【2021省赛】模拟 比赛总结

    2021.03.30[2021省赛]模拟 比赛总结 地址: https://gmoj.net/senior/#contest/home/3350 T1: 神奇纸牌(uno) T2: 凌乱平衡树 (tr ...

最新文章

  1. 程序员哀叹:专科都是ji's万的年薪,互联网的泡沫要破了
  2. 像我这种背景的人跑到微软来干什么?
  3. 学习dubbo(二): 第1个例子
  4. 多协程实例讲解(python 三)
  5. 初学Java Web——Servlet(一)
  6. FPGA(7)--有限状态机--交通灯
  7. Apache Shiro<=1.2.4反序列化RCE漏洞
  8. getHibernateTemplate 抛出NullPointer 异常 其中一个容易被忽略的原因
  9. pycharm创建scrapy项目
  10. 快速判断二叉树先序遍历 后序遍历
  11. 苦等8个月!华为最令人期待的手机终于要来了:最快月底开卖
  12. jsp页面引用相关js,css文件路径问题
  13. JZOJ 1035. 【SCOI2009】粉刷匠
  14. 中断按键c语言程序设计,C语言程序设计:INT0及INT1中断计数
  15. backgroundWorker控件使用笔记
  16. uniapp开发微信公众号(支付宝支付)
  17. 【汇编】2、从汇编源码逐步分析函数调用过程
  18. Svchost.exe病毒的简单处理
  19. 包装严重的 IT 圈,作为面试官,是如何甄别应聘者呢?
  20. 中移物联网联合上研院推出快速定位服务,助力智慧物联网发展

热门文章

  1. org.junit.runners.model.InvalidTestClassError: Invalid test class ‘com.zhj.esdemo.MysqlTests‘: 1.
  2. 未雨绸缪,迎接运维新时代—— Tech Neo第十六期技术沙龙
  3. IP和MAC地址绑定的好处和作用
  4. React造轮子(reacthook实现一套自己的组件库)轮子公开课——第五课【Radio、RadioButton、RadioGroup】组件
  5. 采用UWB定位技术开发的室内定位系统源码
  6. 《嵌入式 - 嵌入式大杂烩》详解常见的二极管
  7. 数据结构——二路归并排序和基数排序
  8. sql server小型案例-自动生成销售单号的触发器
  9. go 调用faiss服务
  10. 恶搞英语大厅的原理(准确来说应该是恶搞IE)