pyfolio工具结合backtrader分析量化策略组合,附源码+问题分析

pyfolio可以分析backtrader的策略,并生成一系列好看的图表,但是由于pyfolio直接install的稳定版有缺陷,开发版也存在诸多问题,使用的依赖版本都偏低,试用了一下之后还是更推荐quantstats。

1、安装依赖

pip install pyfolio
# 直接install是稳定版会报各式各样的错误,要用git拉开发版
pip install git+https://github.com/quantopian/pyfolio

但是git拉也可能报各种http代理等问题,可以使用如下方法解决:

  1. 克隆 GitHub 仓库: 打开命令行或终端,然后使用以下命令将 pyfolio 仓库克隆到本地:

    bashCopy code

    如果git clone https://github.com/quantopian/pyfolio.git报错,可以用下面格式
    git clone git@github.com:quantopian/pyfolio.git

    这将在当前目录下创建一个名为 “pyfolio” 的文件夹,并将仓库的所有代码下载到其中。

  2. 切换到仓库目录: 使用以下命令进入 pyfolio 文件夹:

    bashCopy code

    cd pyfolio

  3. 安装: 在 pyfolio 文件夹中执行以下命令,安装开发版本的代码:

    bashCopy code

    pip install -e .

    -e 选项表示以 “editable” 模式安装,这意味着你对代码的修改会立即反映在安装的库中。这对于开发和测试非常有用。

pyfolio策略源码

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Author:Airyv
@Project:test 
@File:quantstats_demo.py
@Date:2024/1/1 21:45 
@desc:
'''from datetime import datetimeimport backtrader as bt  # 升级到最新版
import matplotlib.pyplot as plt  # 由于 Backtrader 的问题,此处要求 pip install matplotlib==3.2.2
import akshare as ak  # 升级到最新版
import pandas as pd
import quantstats as qs
import pyfolio as pfplt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False# 利用 AKShare 获取股票的后复权数据,这里只获取前 6 列
stock_hfq_df = ak.stock_zh_a_hist(symbol="600028", adjust="hfq").iloc[:, :6]
# 处理字段命名,以符合 Backtrader 的要求
stock_hfq_df.columns = ['date','open','close','high','low','volume',
]
# 把 date 作为日期索引,以符合 Backtrader 的要求
stock_hfq_df.index = pd.to_datetime(stock_hfq_df['date'])class MyStrategy(bt.Strategy):"""主策略程序"""params = (("maperiod", 5),)  # 全局设定交易策略的参数def __init__(self):"""初始化函数"""self.data_close = self.datas[0].close  # 指定价格序列# 初始化交易指令、买卖价格和手续费self.order = Noneself.buy_price = Noneself.buy_comm = None# 添加移动均线指标self.sma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.maperiod)def next(self):"""执行逻辑"""if self.order:  # 检查是否有指令等待执行,return# 检查是否持仓if not self.position:  # 没有持仓if self.data_close[0] > self.sma[0]:  # 执行买入条件判断:收盘价格上涨突破20日均线self.order = self.buy(size=100)  # 执行买入else:if self.data_close[0] < self.sma[0]:  # 执行卖出条件判断:收盘价格跌破20日均线self.order = self.sell(size=100)  # 执行卖出# 更新指令状态if self.order:self.buy_price = self.data_close[0]self.buy_comm = self.broker.getcommissioninfo(self.data).getcommission(self.buy_price, 100)self.order = None  # 在这里将订单设置为None,表示没有正在执行的订单else:self.buy_price = Noneself.buy_comm = Nonecerebro = bt.Cerebro()  # 初始化回测系统
start_date = datetime(2010, 1, 3)  # 回测开始时间
end_date = datetime(2023, 6, 16)  # 回测结束时间
data = bt.feeds.PandasData(dataname=stock_hfq_df, fromdate=start_date, todate=end_date)  # 加载数据
# data=bt.feeds.PandasData(dataname=df,fromdate=start_date,todate=end_date)#加银数据
cerebro.adddata(data)  # 将数据传入回测系统
cerebro.addstrategy(MyStrategy)  # 将交易策略加载到回测系统中
# 加入pyfolio分析者
cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio')
start_cash = 1000000
cerebro.broker.setcash(start_cash)  # 设置初始资本为 100000
cerebro.broker.setcommission(commission=0.002)  # 设置交易手续费为 0.2%
result = cerebro.run()  # 运行回测系统port_value = cerebro.broker.getvalue()  # 获取回测结束后的总资金
pnl = port_value - start_cash  # 盈亏统计print(f"初始资金: {start_cash}\n回测期间:{start_date.strftime('%Y%m%d')}:{end_date.strftime('%Y%m%d')}")
print(f"总资金: {round(port_value, 2)}")
print(f"净收益: {round(pnl, 2)}")# cerebro.plot(style='candlestick')  # 画图cerebro.broker.getvalue()strat = result[0]
pyfoliozer = strat.analyzers.getbyname('pyfolio')returns, positions, transactions, gross_lev = pyfoliozer.get_pf_items()
%matplotlib inline
pf.create_full_tear_sheet(returns,positions=positions,transactions=transactions,live_start_date='2023-01-03')# returns, positions, transactions, gross_lev = pyfoliozer.get_pf_items()
# returns
# positions
# transactions
# gross_lev# pf.create_full_tear_sheet(returns)
# pf.create_full_tear_sheet(
#     returns,
#     positions=positions,
#     transactions=transactions,
#     live_start_date='2010-01-03',
#     round_trips=True)
# pf.create_full_tear_sheet(returns,live_start_date='2010-01-03')
# cerebro.plot()

错误解决

解决后可能报错:

  1. AttributeError: 'Series' object has no attribute 'iteritems'
    solution:

    For anyone else who has the same error pls edit the plotting.py file in ur site packages folder from iteritems() to items()

    意思是进入plotting.py文件(可以用everything搜索)中全局搜索iteritems(),替换为items()即可

  2. AttributeError: module 'pandas' has no attribute 'Float64Index'

    原因是pandas版本太高了(2.0.1),安装低版本:

pip uninstall pandas
pip install pandas==1.5.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
  1. File "...\pyfolio\timeseries.py", line 896, in get_max_drawdown_underwater

    将timeseries.py893行改为:

# valley = np.argmin(underwater)  # end of the period
valley = underwater.idxmin()
  1. File "\pyfolio\round_trips.py", line 133, in _groupby_consecutive grouped_price = (t.groupby(('block_dir',KeyError: ('block_dir', 'block_time')

    修改round_trips.py第133行

        # grouped_price = (t.groupby(('block_dir',#                            'block_time'))#                   .apply(vwap))grouped_price = (t.groupby(['block_dir','block_time']).apply(vwap))grouped_price.name = 'price'grouped_rest = t.groupby(['block_dir', 'block_time']).agg({'amount': 'sum','symbol': 'first','dt': 'first'})
  1. File "...\pyfolio\round_trips.py", line 77, in agg_all_long_short stats_all = (round_trips pandas.errors.SpecificationError: nested renamer is not supported

    改round_trips.py第77行

    stats_all = (round_trips.assign(ones=1).groupby('ones')[col].agg(list(stats_dict.items())).T.rename(columns={1.0: 'All trades'}))stats_long_short = (round_trips.groupby('long')[col].agg(list(stats_dict.items())).T.rename(columns={False: 'Short trades',True: 'Long trades'}))
  1. File "...\pyfolio\round_trips.py", line 393, in gen_round_trip_stats round_trips.groupby('symbol')['returns'].agg(RETURN_STATS).T pandas.errors.SpecificationError: nested renamer is not supported

    393行修改:

    stats['symbols'] = \round_trips.groupby('symbol')['returns'].agg(list(RETURN_STATS.items())).T
  1. ValueError: The number of FixedLocator locations (16), usually from a call to set_ticks, does not match the number of labels (3).

    注释掉tears.py文件的871行

画图运行

在Jupter notebook中运行,不建议直接console中运行,结果如图:


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/329079.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++学习笔记——友元及重载运算符

目录 一、友元 1.1声明友元函数 1.2声明友元类 二、运算符重载 2.1重载加号运算符 2.2重载流插入运算符 三、一个简单的银行管理系统 四、 详细的介绍 一、友元 在 C 中&#xff0c;友元是一个函数或类&#xff0c;它可以访问另一个类的私有成员或保护成员。通常情况下…

浅析观察者模式在Java中的应用

观察者模式&#xff08;Observer Design Pattern&#xff09;,也叫做发布订阅模式&#xff08;Publish-Subscribe Design Pattern&#xff09;、模型-视图&#xff08;Model-View&#xff09;模式、源-监听器&#xff08;Source-Listener&#xff09;模式、从属者&#xff08;D…

Docker部署 SRS rtmp/flv流媒体服务器

一、介绍 SRS&#xff08;Simple Realtime Server&#xff09;是一款开源的流媒体服务器&#xff0c;具有高性能、高可靠性、高灵活性的特点&#xff0c;能够支持直播、点播、转码等多种流媒体应用场景。SRS 不仅提供了流媒体服务器&#xff0c;还提供了适用于多种平台的客户端…

Springboot进行多环境配置的2种方式

本文来说下Springboot使用Spring Profile和Maven Profile进行多环境配置 文章目录 概述Spring Profile多环境主配置文件与不同环境的配置文件 Maven ProfileProfile配置资源过滤 Spring Profile与Maven Profile具体使用 概述 原因 在实际的项目上&#xff0c;一般会分三种环境d…

端云协同,Akamai 与快手联合落地 QUIC 提升海外用户视频体验

10月10日&#xff0c;负责支持和保护数字化体验且深受全球企业信赖的解决方案提供商阿卡迈技术公司( Akamai Technologies, Inc.&#xff0c;以下简称&#xff1a;Akamai )( NASDAQ&#xff1a;AKAM )携手全球领先的短视频记录和分享平台快手(HK&#xff1a;1024)通过全面落地 …

静态网页设计——环保网(HTML+CSS+JavaScript)(dw、sublime Text、webstorm、HBuilder X)

前言 声明&#xff1a;该文章只是做技术分享&#xff0c;若侵权请联系我删除。&#xff01;&#xff01; 感谢大佬的视频&#xff1a; https://www.bilibili.com/video/BV1BC4y1v7ZY/?vd_source5f425e0074a7f92921f53ab87712357b 使用技术&#xff1a;HTMLCSSJS&#xff08;…

我与nano实验室交流群

感兴趣的同学、朋友可以加入群聊共同学习聊天哦。 主要是工训赛、电赛、光电、集成电路等等&#xff0c;会分享一些开源代码&#xff0c;博主自己做的项目&#xff0c;自己画的PCB等等&#xff0c;包含但不限于STM32、K210、V831、机器视觉&#xff0c;机械臂&#xff0c;ROS&a…

Python爬虫获取百度的图片

一. 爬虫的方式&#xff1a; 主要有2种方式: ①ScrapyXpath (API 静态 爬取-直接post get) ②seleniumXpath (点击 动态 爬取-模拟) ScrapyXpath XPath 是 Scrapy 中常用的一种解析器&#xff0c;可以帮助爬虫定位和提取 HTML 或 XML 文档中的数据。 Scrapy 中使用 …

09.简单工厂模式与工厂方法模式

道生一&#xff0c;一生二&#xff0c;二生三&#xff0c;三生万物。——《道德经》 最近小米新车亮相的消息可以说引起了不小的轰动&#xff0c;我们在感慨SU7充满土豪气息的保时捷设计的同时&#xff0c;也深深的被本土品牌的野心和干劲所鼓舞。 今天我们就接着这个背景&…

广义零样本学习综述的笔记

1 Title A Review of Generalized Zero-Shot Learning Methods&#xff08;Farhad Pourpanah; Moloud Abdar; Yuxuan Luo; Xinlei Zhou; Ran Wang; Chee Peng Lim&#xff09;【IEEE Transactions on Pattern Analysis and Machine Intelligence 2022】 2 conclusion Generali…

STM32F407ZGT6时钟源配置

1、26M外部时钟源 1、25M外部时钟源

Open3D 读写并显示PLY文件 (2)

Open3D 读写并显示PLY文件 &#xff08;2&#xff09; 一、算法介绍二、算法实现1.代码2.注意 一、算法介绍 读取PLY文件中的点云坐标&#xff0c;写出到新的文件中&#xff0c;并显示在屏幕上。 二、算法实现 1.代码 import open3d as o3dprint("读取点云") pl…