传统媒体网站建设,永久一级传奇网站,网站建设好就业吗,wordpress怎么不缩略图pyfolio可以分析backtrader的策略#xff0c;并生成一系列好看的图表#xff0c;但是由于pyfolio直接install的稳定版有缺陷#xff0c;开发版也存在诸多问题#xff0c;使用的依赖版本都偏低#xff0c;试用了一下之后还是更推荐quantstats。
1、安装依赖
pip install …pyfolio可以分析backtrader的策略并生成一系列好看的图表但是由于pyfolio直接install的稳定版有缺陷开发版也存在诸多问题使用的依赖版本都偏低试用了一下之后还是更推荐quantstats。
1、安装依赖
pip install pyfolio
# 直接install是稳定版会报各式各样的错误要用git拉开发版
pip install githttps://github.com/quantopian/pyfolio但是git拉也可能报各种http代理等问题可以使用如下方法解决 克隆 GitHub 仓库 打开命令行或终端然后使用以下命令将 pyfolio 仓库克隆到本地 bashCopy code 如果git clone https://github.com/quantopian/pyfolio.git报错可以用下面格式 git clone gitgithub.com:quantopian/pyfolio.git 这将在当前目录下创建一个名为 “pyfolio” 的文件夹并将仓库的所有代码下载到其中。 切换到仓库目录 使用以下命令进入 pyfolio 文件夹 bashCopy code cd pyfolio 安装 在 pyfolio 文件夹中执行以下命令安装开发版本的代码 bashCopy code pip install -e . -e 选项表示以 “editable” 模式安装这意味着你对代码的修改会立即反映在安装的库中。这对于开发和测试非常有用。
pyfolio策略源码
#!/usr/bin/env python
# -*- coding: UTF-8 -*-AuthorAiryv
Projecttest
Filequantstats_demo.py
Date2024/1/1 21:45
desc:
from datetime import datetimeimport backtrader as bt # 升级到最新版
import matplotlib.pyplot as plt # 由于 Backtrader 的问题此处要求 pip install matplotlib3.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(symbol600028, adjusthfq).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], periodself.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(size100) # 执行买入else:if self.data_close[0] self.sma[0]: # 执行卖出条件判断收盘价格跌破20日均线self.order self.sell(size100) # 执行卖出# 更新指令状态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(datanamestock_hfq_df, fromdatestart_date, todateend_date) # 加载数据
# databt.feeds.PandasData(datanamedf,fromdatestart_date,todateend_date)#加银数据
cerebro.adddata(data) # 将数据传入回测系统
cerebro.addstrategy(MyStrategy) # 将交易策略加载到回测系统中
# 加入pyfolio分析者
cerebro.addanalyzer(bt.analyzers.PyFolio, _namepyfolio)
start_cash 1000000
cerebro.broker.setcash(start_cash) # 设置初始资本为 100000
cerebro.broker.setcommission(commission0.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(stylecandlestick) # 画图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,positionspositions,transactionstransactions,live_start_date2023-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,
# positionspositions,
# transactionstransactions,
# live_start_date2010-01-03,
# round_tripsTrue)
# pf.create_full_tear_sheet(returns,live_start_date2010-01-03)
# cerebro.plot()
错误解决
解决后可能报错 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()即可 AttributeError: module pandas has no attribute Float64Index 原因是pandas版本太高了(2.0.1)安装低版本
pip uninstall pandas
pip install pandas1.5.3 -i https://pypi.tuna.tsinghua.edu.cn/simpleFile ...\pyfolio\timeseries.py, line 896, in get_max_drawdown_underwater 将timeseries.py893行改为
# valley np.argmin(underwater) # end of the period
valley underwater.idxmin()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 pricegrouped_rest t.groupby([block_dir, block_time]).agg({amount: sum,symbol: first,dt: first})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(ones1).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}))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 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中运行结果如图