Backtesting.py 是 Python 下的一个回测框架,但是你不用需要在他的类里实现什么指标。基本上你只需要加载历史数据,然后转换成 pandas 的 dataframe,然后用 pandas_ta 这个库计算指标和信号,然后再在 Backtesting.py 的策略类实现信号买卖就可以了。
螺纹钢2405 5 分钟图的简单回测
弄一个简单的 supertrend 策略,添加了止盈和止损。
- 最大收益 108%
- 最终收益 108%
- 最大回撤 -8.4%
- 历时 89 天
- 21 笔交易,包括多空
- 绿色是成功的交易段
- 红色是失败的交易段
Start 2023-08-17 21:35:00+08:00
End 2024-02-07 11:25:00+08:00
Duration 173 days 13:50:00
Exposure Time [%] 78.8
Equity Final [$] 108185.079963
Equity Peak [$] 108185.079963
Return [%] 8.18508
Buy & Hold Return [%] 4.480874
Return (Ann.) [%] 18.295331
Volatility (Ann.) [%] 12.531943
Sharpe Ratio 1.459896
Sortino Ratio 2.518898
Calmar Ratio 2.182325
Max. Drawdown [%] -8.383414
Avg. Drawdown [%] -0.462499
Max. Drawdown Duration 84 days 17:30:00
Avg. Drawdown Duration 2 days 13:01:00
# Trades 21
Win Rate [%] 47.619048
Best Trade [%] 4.325431
Worst Trade [%] -1.802946
Avg. Trade [%] 0.380934
Max. Trade Duration 25 days 12:55:00
Avg. Trade Duration 6 days 12:46:00
Profit Factor 1.797981
Expectancy [%] 0.396803
SQN 0.961494
_strategy MyStrategy
_equity_curve Equity Draw...
_trades Size EntryBar ExitBar EntryPrice Exi...
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
def ind_supertrend(data):
supert = ta.supertrend(
data.High.s, data.Low.s, data.Close.s, length=10, multiplier=10
)["SUPERT_10_10.0"]
return supert
class MyStrategy(Strategy):
def init(self):
self.supert = self.I(ind_supertrend, self.data)
def next(self):
price = self.data.Close
atr = self.data.ATRr_14
if crossover(price, self.supert):
self.position.close()
sl = price - atr * 10
tp = price + atr * 25
self.buy(sl = sl, tp = tp)
elif crossover(self.supert, price):
self.position.close()
sl = price + atr * 10
tp = price - atr * 25
self.sell(sl = sl, tp = tp)
bt = Backtest(
df_new, # df_new 是要加载 OHLCV 数据及指标数据
MyStrategy,
cash=100_000,
commission=0,
hedging=True, # 可做空
#exclusive_orders=True,
trade_on_close=True,
)
stats = bt.run()
bt.plot()
stats.to_frame()
pd.options.display.max_columns = None
pd.options.display.max_rows = None
stats._trades
这个是按着涨跌比例来赚钱,不是商品期货的涨跌点,也无杠杆,所以只需要检验策略的胜率和回撤即可。
参考
- https://github.com/kernc/backtesting.py/blob/master/doc/examples/Quick%20Start%20User%20Guide.ipynb
- https://greyhoundanalytics.com/blog/custom-indicators-in-backtestingpy/
- https://www.youtube.com/watch?v=k6i903uNZ6E
- https://github.com/cgohlke/talib-build/releases
- https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Trade
- https://github.com/zunda-lab/fx_backtest/blob/main/src/unit_backtesting.py#L67
- https://qiita.com/TKfumi/items/4744f34a10863f0d3cfb
- https://qiita.com/TKfumi/items/ffb617898211a794bf9e
- https://qiita.com/TKfumi/items/17301ca962a0da9fcbce
- https://github.com/mpquant/MyTT
- https://gitee.com/wkingnet/stock-analysis/blob/master/func_TDX.py