'Backtesting with Trading Strategies - CrossOverMA
I have been trying a crossover MA strategy using bt library. The strategy: 65(SPY)/35(AGG) portfolio as a default. IF the 50 day moving average for SPY crosses above the 200 day moving average, the investor would go 10% overweight SPY, so the portfolio would change to 75/25. If the SPY 50 day moving average crosses below the 200, the portfolio would change to 55/45. I believe the problem lies within the bt.algos.weighspecified. I think I can only put one numerical value for the following securities. Is it even possible to do alternating weights? Thanks
I have the following code:
spy_agg_data_MA
spy_agg_data_MA['mean_close_50'] = spy_agg_data_MA['SPY'].rolling(50).mean()
spy_agg_data_MA['mean_close_200'] = spy_agg_data_MA['SPY'].rolling(200).mean()
spy_agg_data_MA.dropna(inplace = True)
spy_agg_data_MA # Dataset that contains SPY, AGG, 50 MA, 200MA
spy_agg_data_MA['SPY_weights'] = np.where(spy_agg_data_MA['mean_close_50']>spy_agg_data_MA['mean_close_200'], .75,.65)
spy_agg_data_MA['AGG_weights'] = np.where(spy_agg_data_MA['mean_close_50']>spy_agg_data_MA['mean_close_200'], .25,.35)
spy_agg_data_MA #Now, the dataset has two more columns; spy weight and agg weight depending on MAs
SPY_weights = spy_agg_data_MA['SPY_weights']
AGG_weights = spy_agg_data_MA['AGG_weights']
target_weights = pd.concat([SPY_weights,AGG_weights], axis = 1)
target_weights #This might be redundant, but I put the two columns into another dataset
name = 'SPY_AGG_weightrebal'
strategy_2 = bt.Strategy(
name,
[
bt.algos.RunWeekly(),
bt.algos.SelectAll(),
bt.algos.WeighSpecified(SPY = target_weights['SPY_weights'], AGG = target_weights['AGG_weights']),
bt.algos.Rebalance()
]
)
backtest_2 = bt.Backtest(strategy_2, spy_agg_data_MA[['SPY','AGG']])
res = bt.run(backtest_2)```
The error: cannot convert the series to <class 'float'>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
