pmorissette / bt

bt - flexible backtesting for Python
http://pmorissette.github.io/bt
MIT License
2.17k stars 418 forks source link

issue with multiple children strategies #309

Open idiaconescu opened 3 years ago

idiaconescu commented 3 years ago

The following master algo of 2 children sub-strategies should return 2 stocks only but it returns 4, so it looks like it's not taking in account the children:

import bt data = bt.get('aapl,mcd,agg,tld')

mom_s = bt.Strategy('mom_s', [bt.algos.RunMonthly(), bt.algos.SelectAll(), bt.algos.SelectMomentum(1), bt.algos.Rebalance()], [ 'aapl','mcd'])

bond_s = bt.Strategy('bond_s', [bt.algos.RunMonthly(), bt.algos.SelectAll(), bt.algos.SelectMomentum(1), bt.algos.Rebalance()], [ 'agg','tld'])

master = bt.Strategy('master', [bt.algos.RunMonthly(),

                            bt.algos.SelectAll(),
                            bt.algos.WeighEqually(),
                            bt.algos.Rebalance()],
                [mom_s, bond_s])

t = bt.Backtest(master, data) r = bt.run(t)

r.get_security_weights().iloc[-1].where(df_res.iloc[-1]>0).dropna()

aapl 0.163599 mcd 0.166983 agg 0.169678 tld 0.157027 Name: 2021-05-14 00:00:00, dtype: float64


If you modify the master to have one sub-strategy + one stock then it works fine

import bt data = bt.get('aapl,mcd,agg,tld')

mom_s = bt.Strategy('mom_s', [bt.algos.RunMonthly(), bt.algos.SelectAll(), bt.algos.SelectMomentum(1), bt.algos.Rebalance()], [ 'aapl','mcd'])

master = bt.Strategy('master', [bt.algos.RunMonthly(),

                            bt.algos.SelectAll(),
                            bt.algos.WeighEqually(),
                            bt.algos.Rebalance()],
                [mom_s, 'agg'])

t = bt.Backtest(master, data) r = bt.run(t)

r.get_security_weights().iloc[-1].where(df_res.iloc[-1]>0).dropna()

mcd 0.496051 agg 0.503890 Name: 2021-05-14 00:00:00, dtype: float64

danilogalisteu commented 3 years ago

What is df_res?

SimonHovmark commented 2 years ago

Are you able to run the code without getting the below exception?

Position is open (non-zero: 500.0) and latest price is NaN for security ('mom_s', '') on 2016-01-04 00:00:00. Cannot update node value.