def run(): """ Run the code that illustrates the pairs trading strategy """ data = make_data() # Define the "entry" strategy of the trade. In this case, we give each asset unit weight and trade it trade_entry = bt.AlgoStack( bt.algos.RunOnce(), WeighPair(1.), bt.algos.Rebalance() ) # Define the "exit" strategy of the trade. Here we exit when we cross either an upper/lower # threshold on the price of the strategy, or hold it for a fixed length of time. trade_exit = bt.AlgoStack( bt.algos.Or( [PriceCompare( 96., is_greater=False ), PriceCompare( 104., is_greater=True), bt.algos.RunAfterDays( 5 ) ] ), ClosePositions() ) # Combine the entry, exit and debug algos for each trade trade_algos = [ bt.algos.Or( [ trade_entry, trade_exit, DebugTradeLevel() ] )] # Define the strategy for the master portfolio. strategy_algos = [ PairsSignal( threshold = 4., indicator_name = 'my_indicator' ), SetupPairsTrades( trade_algos ), SizePairsTrades( pct_of_capital = 0.2 ), DebugPortfolioLevel() ] # Build and run the strategy strategy = bt.Strategy( 'PairsStrategy', strategy_algos ) test = bt.Backtest( strategy, data, additional_data={'my_indicator':data} ) out = bt.run( test ) print(out.stats) return out
def test_algo_stack(): algo1 = DummyAlgo(return_value=True) algo2 = DummyAlgo(return_value=False) algo3 = DummyAlgo(return_value=True) target = mock.MagicMock() stack = bt.AlgoStack(algo1, algo2, algo3) actual = stack(target) assert not actual assert algo1.called assert algo2.called assert not algo3.called