首页 > 解决方案 > zipline 自定义捆绑回测

问题描述

我使用https://github.com/aspromatis/Backtesting-RSI-Algo/backtest.py的 zipline_bundle 项目中的自定义捆绑包测试了资产分配。我更改了如下代码以包含我自己的投资组合。

#%%
import talib
from zipline.api import order_target, record, symbol, order_target_percent

'''   
This example algorithm uses the Relative Strength Index indicator as a buy/sell signal.
When the RSI is over 70, a stock can be seen as overbought and it's time to sell.
When the RSI is below 30, a stock can be seen as oversold and it's time to buy.
'''

# Setup our variables
def initialize(context):
    
    # what stock to trade - FAANG in this example
    # stocklist = ['FB', 'AMZN', 'AAPL', 'NFLX', 'GOOG']
    stocklist = ['SPY','TLT','IEF','GLD','DBC']
    context.securities = {
        'SPY': 0.25,
        'TLT': 0.3,
        'IEF': 0.3,
        'GLD': 0.075,
        'DBC': 0.075
    }

     # make a list of symbols for the list of tickers
    context.stocks = [symbol(s) for s in stocklist]
    
     # create equal weights of each stock to hold in our portfolio
     # context.target_pct_per_stock = 1.0 / len(context.stocks)
    
    # create initial RSI threshold values for low (oversold and buy signal) and high (overbought and sell signal)
    context.LOW_RSI = 30
    context.HIGH_RSI = 70

# Rebalance daily.
def handle_data(context, data):
    
    # Load historical pricing data for the stocks, using daily frequncy and a rolling 20 days
    prices = data.history(context.stocks, 'price', bar_count=20, frequency="1d")
    
    rsis = {}
    
    # Loop through our list of stocks
    for stock in context.stocks:
        # Get the rsi of this stock.
        rsi = talib.RSI(prices[stock], timeperiod=14)[-1]
        rsis[stock] = rsi
        
        current_position = context.portfolio.positions[stock].amount
        
        # RSI is above 70 and we own shares, time to sell
        if rsi > context.HIGH_RSI and current_position > 0 and data.can_trade(stock):
            order_target(stock, 0)
   
        # RSI is below 30 and we don't have any shares, time to buy
        elif rsi < context.LOW_RSI and current_position == 0 and data.can_trade(stock):
            order_target_percent(stock, context.securities[stock])

    # record the current RSI values of each stock for later ispection
    record(vb_rsi=rsis[symbol('SPY')],
           tlt_rsi=rsis[symbol('TLT')],
           ief_rsi=rsis[symbol('IEF')],
           gld_rsi=rsis[symbol('GLD')],
           dbc_rsi=rsis[symbol('DBC')],
          )

我使用以下命令运行了上面的代码

zipline run -f backtest-erol.py --start 2014-1-1 --end 2018-1-1 --no-benchmark -o myperf.pickle --bundle custom-bundle

自定义捆绑包具有相关代码的价格历史记录。在执行期间,我得到以下异常。

/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/empyrical/stats.py:710: RuntimeWarning: invalid value encountered in true_divide
  np.divide(
/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/empyrical/stats.py:799: RuntimeWarning: invalid value encountered in true_divide
  np.divide(average_annual_return, annualized_downside_risk, out=out)
Traceback (most recent call last):
  File "/Users/rnu/Documents/virtualenv3/financials/bin/zipline", line 8, in <module>
    sys.exit(main())
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/click/core.py", line 1128, in __call__
    return self.main(*args, **kwargs)
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/click/core.py", line 1053, in main
    rv = self.invoke(ctx)
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/click/core.py", line 1659, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/click/core.py", line 1395, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/click/core.py", line 754, in invoke
    return __callback(*args, **kwargs)
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/zipline/__main__.py", line 106, in _
    return f(*args, **kwargs)
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/click/decorators.py", line 26, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/zipline/__main__.py", line 300, in run
    return _run(
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/zipline/utils/run_algo.py", line 200, in _run
    perf = TradingAlgorithm(
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/zipline/algorithm.py", line 624, in run
    for perf in self.get_generator():
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/zipline/gens/tradesimulation.py", line 228, in transform
    for capital_change_packet in every_bar(dt):
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/zipline/gens/tradesimulation.py", line 143, in every_bar
    handle_data(algo, current_data, dt_to_use)
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/zipline/utils/events.py", line 206, in handle_data
    event.handle_data(
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/zipline/utils/events.py", line 229, in handle_data
    self.callback(context, data)
  File "/Users/rnu/Documents/virtualenv3/financials/lib/python3.8/site-packages/zipline/algorithm.py", line 447, in handle_data
    self._handle_data(self, data)
  File "backtest-erol.py", line 57, in handle_data
    order_target_percent(stock, context.securities[stock])
KeyError: Equity(0 [DBC])

有没有人尝试过使用自定义投资组合和交易策略进行 zipline 回测?任何想法如何使它工作。

标签: back-testingzipline

解决方案


推荐阅读