def test_history(self): universe = pd.DataFrame({ "A": range(10), "B": range(10), "C": range(10) }) trades = [ trade("A", entry=1, exit=2, take=3, stop=-4), [2, -3] * trade(["B", "C"], entry=3, exit=9, take=5, stop=-2), ] strategy = DeterminedStrategy(trades).run(universe) history = strategy.history() expected = pd.DataFrame({ "trade_id": [0, 1, 1], "asset": ["A", "B", "C"], "lot": [1, 2, -3], "entry": [1, 3, 3], "close": [2, 5, 5], "exit": [2, 9, 9], "take": [3, 5, 5], "stop": [-4, -2, -2], "pnl": [1, 4, -6], }) pd.testing.assert_frame_equal(history, expected, check_dtype=False)
def test_logic(self): s0 = create_strategy(lambda universe: [trade("A")]) s1 = create_strategy(lambda universe: [trade("B"), trade("C")]) container = StrategyContainer(s0=s0, s1=s1) universe = ... result = container(universe) assert container(universe) == s0(universe) + s1(universe)
def test_repr(self): t = trade("A") assert repr(t) == "trade(['A'], lot=[1.])" t = trade("A", lot=2, take=3.0, stop=-3.0, entry="B0", exit="B1") assert ( repr(t) == "trade(['A'], lot=[2], entry=B0, exit=B1, take=3.0, stop=-3.0)")
def test_nonexitent(self): """non-existent asset, entry, exit""" universe = pd.DataFrame({"A": range(10)}) with pytest.raises(KeyError): t = trade("NONEXISTENT").execute(universe) with pytest.raises(KeyError): t = trade("A", entry=99).execute(universe) with pytest.raises(KeyError): t = trade("A", entry=0, exit=99).execute(universe)
def test_array_value_linearity_mul(self, a, seed): np.random.seed(seed) universe = self.universe_hand lot0 = np.random.randn(2) t0 = list(lot0) * trade(["A", "B"], entry=1, exit=3) ta = list(a * lot0) * trade(["A", "B"], entry=1, exit=3) result = ta.array_value(universe) expected = a * t0.array_value(universe) assert np.allclose(result, expected)
def test_array_value_linearity_add(self, seed): np.random.seed(seed) universe = self.universe_hand lot0, lot1 = np.random.randn(2), np.random.randn(2) t0 = list(lot0) * trade(["A", "B"], entry=1, exit=3) t1 = list(lot1) * trade(["A", "B"], entry=1, exit=3) ta = list(lot0 + lot1) * trade(["A", "B"], entry=1, exit=3) result = ta.array_value(universe) expected = t0.array_value(universe) + t1.array_value(universe) assert np.allclose(result, expected)
def test_final_pnl_linearity_mul(self, a, seed): np.random.seed(seed) universe = self.universe_hand lot0 = np.random.randn(2) t0 = list(lot0) * trade(["A", "B"], entry=1, exit=3) ta = list(a * lot0) * trade(["A", "B"], entry=1, exit=3) t0.execute(universe) ta.execute(universe) result = ta.final_pnl(universe) expected = a * t0.final_pnl(universe) assert np.allclose(result, expected)
def test_handmade(self): universe = pd.DataFrame({ "A": [3.0, 1.0, 4.0, 1.0, 5.0, 9.0, 2.0], "B": [2.0, 7.0, 1.0, 8.0, 1.0, 8.0, 1.0], }) trades = [ 2 * trade("A", entry=1, exit=5).execute(universe), -3 * trade("B", entry=2, exit=4).execute(universe), ] result = ts.abs_exposure(trades, universe) expected = np.array([0.0, 2.0, 11.0, 26.0, 13.0, 18.0, 0.0]) assert_equal(result, expected)
def test_init_array(self): t = trade("A", lot=1.0) assert isinstance(t.asset, np.ndarray) assert isinstance(t.lot, np.ndarray) t = trade("A", lot=[1.0]) assert isinstance(t.asset, np.ndarray) assert isinstance(t.lot, np.ndarray) t = trade(["A"], lot=[1.0]) assert isinstance(t.asset, np.ndarray) assert isinstance(t.lot, np.ndarray) t = trade(["A", "B"], lot=1.0) t = trade(["A", "B"], lot=[1.0, 2.0]) assert isinstance(t.asset, np.ndarray) assert isinstance(t.lot, np.ndarray)
def test_final_pnl_lineality_add(self, seed): np.random.seed(seed) universe = self.universe_hand lot0, lot1 = np.random.randn(2), np.random.randn(2) t0 = list(lot0) * trade(["A", "B"], entry=1, exit=3) t1 = list(lot1) * trade(["A", "B"], entry=1, exit=3) ta = list(lot0 + lot1) * trade(["A", "B"], entry=1, exit=3) t0.execute(universe) t1.execute(universe) ta.execute(universe) result = ta.final_pnl(universe) expected = t0.final_pnl(universe) + t1.final_pnl(universe) assert np.allclose(result, expected)
def test_abs_exposure(self): universe = pd.DataFrame( { "A0": [1.0, 2.0, 3.0, 4.0, 5.0], "A1": [2.0, 3.0, 4.0, 5.0, 6.0], "A2": [3.0, 4.0, 5.0, 6.0, 7.0], }, dtype=float, ) strategy = create_strategy(lambda _: [ [1, -1] * trade(["A0", "A2"], entry=1, exit=3), [-1, 2] * trade(["A1", "A2"], entry=2, exit=4), ]).run(universe, verbose=False) result = strategy.abs_exposure() expect = pd.Series([0, 0, 8, 15, 20], index=universe.index) pd.testing.assert_series_equal(result, expect, check_dtype=False)
def test_handmade(self): universe = pd.DataFrame({"A": [0.0, 3.0, 1.0, 4.0, 1.0, 5.0, 9.0, 2.0]}) trades = [trade("A").execute(universe)] result = ts.drawdown(trades, universe) expected = np.array([0.0, 0.0, -2.0, 0.0, -3.0, 0.0, 0.0, -7.0]) assert_equal(result, expected)
def test_array_value_value_hand(self): t = [2.0, -3.0] * trade(["A", "B"], entry=1, exit=3) result = t.array_value(self.universe_hand) expected = np.array([ [6.0, -6.0], [2.0, -21.0], [8.0, -3.0], [2.0, -24.0], [10.0, -6.0], [18.0, -24.0], [4.0, -3.0], ]) assert np.allclose(result, expected) t = [-3.0, 2.0] * trade(["B", "A"], entry=1, exit=3) result = t.array_value(universe=self.universe_hand) expected = expected[:, [1, 0]] assert np.allclose(result, expected)
def logic(self, universe): for _ in range(self._n_trades): n_assets = np.random.randint(1, self.max_n_assets + 1, size=1)[0] asset = list(np.random.choice(universe.columns, n_assets)) lot = list( random_uniform(self.min_lot, self.max_lot, size=n_assets)) entry, exit = sorted(np.random.choice(universe.index, 2)) yield (lot * trade(asset, entry=entry, exit=exit))
def test(self): np.random.seed(42) universe = pd.DataFrame({"A": range(100)}) lots = np.random.randn(100) trades = [lot * trade("A", entry=0) for lot in lots] trades = [t.execute(universe) for t in trades] result = num_win(trades, universe) expected = (lots > 0).sum() assert result == expected
def test(self): np.random.seed(42) universe = pd.DataFrame({"A": range(100)}) lots = np.random.randn(100) trades = [lot * trade("A", entry=0) for lot in lots] trades = [t.execute(universe) for t in trades] metric = rate_lose(trades, universe) expected = (lots <= 0).sum() / len(trades) assert metric == expected
def test_truediv(self, a): t = trade("A", entry=0, exit=1, take=2.0, stop=-3.0) result = t / a expect = trade("A", lot=[1 / a], entry=0, exit=1, take=2.0, stop=-3.0) assert result == expect t = trade(["A", "B"], lot=[1.0, -2.0], entry=0, exit=1, take=2.0, stop=-3.0) result = t / a expect = trade(["A", "B"], lot=[1 / a, -2.0 / a], entry=0, exit=1, take=2.0, stop=-3.0) assert result == expect
def test_monotonous(self): """ result = 0 if wealth is monotonously increasing """ universe = pd.DataFrame({"A": np.linspace(1, 2, 100)}) trades = [trade("A").execute(universe)] result = ts.drawdown(trades, universe) expected = np.zeros_like(result) assert_equal(result, expected)
def test(self): np.random.seed(42) universe = pd.DataFrame({"A": range(100)}) lots = np.random.randn(100) trades = [lot * trade("A", entry=0) for lot in lots] trades = [t.execute(universe) for t in trades] tot_pnl = avg_pnl(trades, universe) * len(trades) expected = final_wealth(trades, universe).item() assert np.isclose(tot_pnl, expected)
def test_exposure(self): universe = pd.DataFrame( { "A0": [1.0, 2.0, 3.0, 4.0, 5.0], "A1": [2.0, 3.0, 4.0, 5.0, 6.0], "A2": [3.0, 4.0, 5.0, 6.0, 7.0], }, dtype=float, ) strategy = create_strategy(lambda universe: [ [1, -1] * trade(["A0", "A2"], entry=1, exit=3), [-1, 2] * trade(["A1", "A2"], entry=2, exit=4), ]).run(universe, verbose=False) result = strategy.exposure() expect = pd.DataFrame( [[0, 0, 0], [0, 0, 0], [3, 0, -5], [4, -5, 6], [0, -6, 14]], index=universe.index, columns=universe.columns, ) pd.testing.assert_frame_equal(result, expect, check_dtype=False)
def test_wealth(self): # TODO test for when exit != close universe = pd.DataFrame({ "A": range(10), "B": range(10), "C": range(10) }) # TODO remove it when #129 will be fixed --- universe = universe.astype(float) # --- trades = [trade("A", entry=1, exit=3), trade("B", entry=2, exit=4)] strategy = DeterminedStrategy(trades).run(universe) wealth = strategy.wealth() expected = pd.Series([0, 0, 1, 3, 4, 4, 4, 4, 4, 4], index=universe.index) pd.testing.assert_series_equal(wealth, expected, check_dtype=False)
def test(self): np.random.seed(42) universe = pd.DataFrame({"A": range(100)}) lots = np.random.randn(100) trades = [lot * trade("A", entry=0) for lot in lots] trades = [t.execute(universe) for t in trades] tot_win = avg_win(trades, universe) * num_win(trades, universe) pnls = np.array([t.final_pnl(universe) for t in trades]) expected = np.sum(pnls[pnls > 0]) assert tot_win == expected
def test_mul(self, a): t = trade("A", entry=0, exit=1, take=2.0, stop=-3.0) result = a * t expect = trade("A", lot=[a], entry=0, exit=1, take=2.0, stop=-3.0) assert result == expect result = t * a assert result == expect t = trade(["A", "B"], lot=[1.0, -2.0], entry=0, exit=1, take=2.0, stop=-3.0) result = a * t expect = trade(["A", "B"], lot=[a, -2.0 * a], entry=0, exit=1, take=2.0, stop=-3.0) assert result == expect result = t * a assert result == expect
def test_init_shape(self): t = trade("A", lot=1.0) assert t.asset.shape == (1, ) assert t.lot.shape == (1, ) t = trade(["A"], lot=1.0) assert t.asset.shape == (1, ) assert t.lot.shape == (1, ) t = trade("A", lot=[1.0]) assert t.asset.shape == (1, ) assert t.lot.shape == (1, ) t = trade(["A", "B"], lot=1.0) assert t.asset.shape == (2, ) assert t.lot.shape == (2, ) t = trade(["A", "B"], lot=[1.0]) assert t.asset.shape == (2, ) assert t.lot.shape == (2, ) t = trade(["A", "B"], lot=[1.0, 2.0]) assert t.asset.shape == (2, ) assert t.lot.shape == (2, )
def logic(self, universe): yield (self.param_1 * trade("A")) yield (self.param_2 * trade("B"))
def logic(self, universe): asset = list(self.weight.keys()) price = universe.loc[:, asset].iloc[0].values lot = list(np.array(list(self.weight.values())) / price) yield lot * trade(asset, entry=universe.index[0])
def my_strategy(universe, param_1, param_2): """ Example logic """ yield (param_1 * trade("A")) yield (param_2 * trade("B"))
def test_init_from_func(self): strategy = create_strategy(self.my_strategy, param_1=1.0, param_2=2.0) universe = self.universe assert strategy(universe) == [1.0 * trade("A"), 2.0 * trade("B")]
def test_init_from_init(self): strategy = MyStrategy(param_1=1.0, param_2=2.0) universe = self.universe assert strategy(universe) == [1.0 * trade("A"), 2.0 * trade("B")]
def test(): universe = pd.DataFrame({"A": range(10)}) trades = [trade("A", entry=1, exit=3)] strategy = DeterminedStrategy(trades).run(universe) wealth = strategy.wealth()