Exemplo n.º 1
0
    def testCallingTradingRule(self):

        # config=Config(dict(trading_rules=dict(ewmac=dict(function="systems.provided.rules.ewmac..ewmac_forecast_with_defaults"))))
        NOTUSEDrawdata, data, NOTUSEDconfig = get_test_object()

        rawdata = RawData()
        rules = Rules()
        system = System([rawdata, rules], data)

        # Call with default data and config
        rule = TradingRule(ewmac_forecast_with_defaults)
        ans = rule.call(system, "EDOLLAR")
        self.assertAlmostEqual(ans.tail(1).values[0], -3.280028, 5)

        # Change the data source
        rule = TradingRule(
            (
                "systems.provided.rules.ewmac.ewmac_forecast_with_defaults_no_vol",
                ["rawdata.get_daily_prices", "rawdata.daily_returns_volatility"],
                dict(),
            )
        )

        ans = rule.call(system, "EDOLLAR")
        self.assertAlmostEqual(ans.tail(1).values[0], -1.24349, 5)

        rule = TradingRule(
            dict(
                function="systems.provided.rules.ewmac.ewmac_forecast_with_defaults_no_vol",
                data=["rawdata.get_daily_prices", "rawdata.daily_returns_volatility"],
                other_args=dict(Lfast=50, Lslow=200),
            )
        )
        ans = rule.call(system, "EDOLLAR")
        self.assertAlmostEqual(ans.tail(1).values[0], -3.025001057146)
Exemplo n.º 2
0
    def testCarryRule(self):
        NOTUSEDrawdata, data, NOTUSEDconfig = get_test_object()

        rawdata = RawData()
        rules = Rules()
        system = System([rawdata, rules], data)
        rule = TradingRule(
            carry,
            [
                "rawdata.daily_annualised_roll",
            ],
            dict(smooth_days=90),
        )
        ans = rule.call(system, "EDOLLAR")
        self.assertAlmostEqual(ans.tail(1).values[0], 0.138302, 5)
Exemplo n.º 3
0
def _process_dict_of_trading_rules(trading_rules: dict):
    processed_rules = dict(
        [
            (keyname, TradingRule(trading_rules[keyname]))
            for keyname in trading_rules
        ]
    )
    return processed_rules
Exemplo n.º 4
0
def _process_trading_rules_in_list(trading_rules: list):
    processed_rules = dict(
        [
            ("rule%d" % ruleid, TradingRule(rule))
            for (ruleid, rule) in enumerate(trading_rules)
        ]
    )
    return processed_rules
Exemplo n.º 5
0
    def test_simple_system_trading_rule(self, data, raw_data, ewmac_8, ewmac_32):

        ewmac_rule = TradingRule(ewmac)
        print(ewmac_rule)

        my_rules = Rules(dict(ewmac8=ewmac_8, ewmac32=ewmac_32))
        print(my_rules.trading_rules()["ewmac32"])

        my_system = System([my_rules, raw_data], data)
        my_system.rules.get_raw_forecast("EDOLLAR", "ewmac32").tail(5)
Exemplo n.º 6
0
    def testProcessTradingRuleSpec(self):

        ruleA = TradingRule(ewmac_forecast_with_defaults)
        ruleB = TradingRule(
            dict(
                function=
                "systems.provided.example.rules.ewmac_forecast_with_defaults_no_vol",
                data=[
                    "rawdata.daily_prices", "rawdata.daily_returns_volatility"
                ],
                other_args=dict(Lfast=50, Lslow=200),
            ))

        trading_rules = dict(ruleA=ruleA, ruleB=ruleB)
        ans = process_trading_rules(trading_rules)
        assert "ruleA" in ans.keys()
        assert "ruleB" in ans.keys()

        trading_rules = [ruleA, ruleB]
        ans = process_trading_rules(trading_rules)
        assert "rule1" in ans.keys()

        ans = process_trading_rules(ruleA)
        assert ans["rule0"].function == ewmac_forecast_with_defaults

        ans = process_trading_rules(ewmac_forecast_with_defaults)
        assert ans["rule0"].function == ewmac_forecast_with_defaults

        ans = process_trading_rules([
            dict(
                function=
                "systems.provided.example.rules.ewmac_forecast_with_defaults_no_vol",
                data=[
                    "rawdata.daily_prices", "rawdata.daily_returns_volatility"
                ],
                other_args=dict(Lfast=50, Lslow=200),
            )
        ])
        assert ans["rule0"].other_args["Lfast"] == 50
Exemplo n.º 7
0
    def testinitTradingRules(self):
        rule = TradingRule((ewmac_forecast_with_defaults, [], {}))
        assert rule.function == ewmac_forecast_with_defaults
        rule2 = TradingRule(rule)

        assert (rule.function, rule.data, rule.other_args) == (
            rule2.function,
            rule2.data,
            rule2.other_args,
        )

        rule3 = TradingRule(
            ewmac_forecast_with_defaults,
            ["data.get_instrument_price"],
            dict(Lfast=50, Lslow=200),
        )

        assert rule3.data == ["data.get_instrument_price"]

        rule4 = TradingRule(
            ewmac_forecast_with_defaults,
            "data.get_instrument_price",
            dict(Lfast=50, Lslow=200),
        )

        assert rule4.data == ["data.get_instrument_price"]

        try:
            rule4 = TradingRule(
                ewmac_forecast_with_defaults, "data.get_instrument_price"
            )
            rule5 = TradingRule((ewmac_forecast_with_defaults,))

            raise Exception("Should have failed with 2 tuple")
        except BaseException:
            pass

        rule7 = TradingRule(
            "systems.provided.rules.ewmac.ewmac_forecast_with_defaults",
            [],
            dict(Lfast=50, Lslow=200),
        )
        assert rule7.function == rule.function

        try:
            rule8 = TradingRule(
                "not.a.real.rule.just.a.string.of.arbitrary.text",
                [],
                dict(Lfast=50, Lslow=200),
            )
            raise Exception("Should have failed with non existent rule")
        except BaseException:
            pass

        rule9 = TradingRule(dict(function=ewmac_forecast_with_defaults))

        try:
            rule10 = TradingRule(dict(functionette=ewmac_forecast_with_defaults))
            raise Exception("Should have failed with no function keyword")
        except BaseException:
            pass

        rule11 = TradingRule(
            dict(
                function="systems.provided.rules.ewmac.ewmac_forecast_with_defaults",
                other_args=dict(Lfast=50),
                data=[],
            )
        )

        rule12 = TradingRule(ewmac_forecast_with_defaults, other_args=dict(Lfast=30))
        rule13 = TradingRule(
            "systems.provided.rules.ewmac.ewmac_forecast_with_defaults",
            data="data.get_pricedata",
        )
        assert rule13.data == ["data.get_pricedata"]

        rule14 = TradingRule(ewmac_forecast_with_defaults)

        try:
            rule15 = TradingRule(set())
            raise Exception("Should have failed with other data type")
        except BaseException:
            pass
Exemplo n.º 8
0
my_rules = Rules(dict(ewmac=ewmac))
print(my_rules.trading_rules())

from systems.basesystem import System

my_system = System([my_rules], data)
print(my_system)

print(my_system.rules.get_raw_forecast("EDOLLAR", "ewmac").tail(5))
"""
Define a TradingRule
"""

from systems.trading_rules import TradingRule

ewmac_rule = TradingRule(ewmac)
my_rules = Rules(dict(ewmac=ewmac_rule))
ewmac_rule
"""
... or two...
"""

ewmac_8 = TradingRule((ewmac, [], dict(Lfast=8, Lslow=32)))
ewmac_32 = TradingRule(
    dict(
        function=ewmac,
        other_args=dict(
            Lfast=32,
            Lslow=128)))
my_rules = Rules(dict(ewmac8=ewmac_8, ewmac32=ewmac_32))
print(my_rules.trading_rules()["ewmac32"])
Exemplo n.º 9
0
    def test_simple_system(self):
        """
        This is (mostly) the code from 'examples.introduction.simplesystem',
        but without graph plotting
        """
        data = csvFuturesSimData()
        my_rules = Rules(ewmac)
        print(my_rules.trading_rules())

        my_rules = Rules(dict(ewmac=ewmac))
        print(my_rules.trading_rules())

        my_system = System([my_rules], data)
        print(my_system)
        print(my_system.rules.get_raw_forecast("EDOLLAR", "ewmac").tail(5))

        ewmac_rule = TradingRule(ewmac)
        my_rules = Rules(dict(ewmac=ewmac_rule))
        print(ewmac_rule)

        ewmac_8 = TradingRule((ewmac, [], dict(Lfast=8, Lslow=32)))
        ewmac_32 = TradingRule(
            dict(function=ewmac, other_args=dict(Lfast=32, Lslow=128)))
        my_rules = Rules(dict(ewmac8=ewmac_8, ewmac32=ewmac_32))
        print(my_rules.trading_rules()["ewmac32"])

        my_system = System([my_rules], data)
        my_system.rules.get_raw_forecast("EDOLLAR", "ewmac32").tail(5)

        my_config = Config()
        print(my_config)

        empty_rules = Rules()
        my_config.trading_rules = dict(ewmac8=ewmac_8, ewmac32=ewmac_32)
        my_system = System([empty_rules], data, my_config)
        my_system.rules.get_raw_forecast("EDOLLAR", "ewmac32").tail(5)

        # we can estimate these ourselves
        my_config.instruments = ["US10", "EDOLLAR", "CORN", "SP500"]
        my_config.use_forecast_scale_estimates = True

        fcs = ForecastScaleCap()
        my_system = System([fcs, my_rules], data, my_config)
        my_config.forecast_scalar_estimate["pool_instruments"] = False
        print(
            my_system.forecastScaleCap.get_forecast_scalar(
                "EDOLLAR", "ewmac32").tail(5))

        # or we can use the values from the book
        my_config.forecast_scalars = dict(ewmac8=5.3, ewmac32=2.65)
        my_config.use_forecast_scale_estimates = False
        fcs = ForecastScaleCap()
        my_system = System([fcs, my_rules], data, my_config)
        print(
            my_system.forecastScaleCap.get_capped_forecast(
                "EDOLLAR", "ewmac32").tail(5))

        # defaults
        combiner = ForecastCombine()
        my_system = System([fcs, my_rules, combiner], data, my_config)
        print(my_system.combForecast.get_forecast_weights("EDOLLAR").tail(5))
        print(
            my_system.combForecast.get_forecast_diversification_multiplier(
                "EDOLLAR").tail(5))

        # estimates:
        my_account = Account()
        combiner = ForecastCombine()

        my_config.forecast_weight_estimate = dict(method="one_period")
        my_config.use_forecast_weight_estimates = True
        my_config.use_forecast_div_mult_estimates = True

        my_system = System([my_account, fcs, my_rules, combiner], data,
                           my_config)

        # this is a bit slow, better to know what's going on
        my_system.set_logging_level("on")

        print(my_system.combForecast.get_forecast_weights("US10").tail(5))
        print(
            my_system.combForecast.get_forecast_diversification_multiplier(
                "US10").tail(5))

        # fixed:
        my_config.forecast_weights = dict(ewmac8=0.5, ewmac32=0.5)
        my_config.forecast_div_multiplier = 1.1
        my_config.use_forecast_weight_estimates = False
        my_config.use_forecast_div_mult_estimates = False

        combiner = ForecastCombine()
        my_system = System(
            [fcs, empty_rules, combiner], data,
            my_config)  # no need for accounts if no estimation done
        my_system.combForecast.get_combined_forecast("EDOLLAR").tail(5)

        # size positions
        possizer = PositionSizing()
        my_config.percentage_vol_target = 25
        my_config.notional_trading_capital = 500000
        my_config.base_currency = "GBP"

        my_system = System([fcs, my_rules, combiner, possizer], data,
                           my_config)

        print(my_system.positionSize.get_price_volatility("EDOLLAR").tail(5))
        print(my_system.positionSize.get_block_value("EDOLLAR").tail(5))
        print(my_system.positionSize.get_underlying_price("EDOLLAR"))
        print(
            my_system.positionSize.get_instrument_value_vol("EDOLLAR").tail(5))
        print(my_system.positionSize.get_volatility_scalar("EDOLLAR").tail(5))
        print(my_system.positionSize.get_vol_target_dict())
        print(my_system.positionSize.get_subsystem_position("EDOLLAR").tail(5))

        # portfolio - estimated
        portfolio = Portfolios()

        my_config.use_instrument_weight_estimates = True
        my_config.use_instrument_div_mult_estimates = True
        my_config.instrument_weight_estimate = dict(method="shrinkage",
                                                    date_method="in_sample")

        my_system = System(
            [my_account, fcs, my_rules, combiner, possizer, portfolio], data,
            my_config)

        my_system.set_logging_level("on")

        print(my_system.portfolio.get_instrument_weights().tail(5))
        print(my_system.portfolio.get_instrument_diversification_multiplier().
              tail(5))

        # or fixed
        portfolio = Portfolios()
        my_config.use_instrument_weight_estimates = False
        my_config.use_instrument_div_mult_estimates = False
        my_config.instrument_weights = dict(US10=0.1,
                                            EDOLLAR=0.4,
                                            CORN=0.3,
                                            SP500=0.2)
        my_config.instrument_div_multiplier = 1.5

        my_system = System([fcs, my_rules, combiner, possizer, portfolio],
                           data, my_config)

        print(my_system.portfolio.get_notional_position("EDOLLAR").tail(5))

        my_system = System(
            [fcs, my_rules, combiner, possizer, portfolio, my_account], data,
            my_config)
        profits = my_system.accounts.portfolio()
        print(profits.percent().stats())

        # have costs data now
        print(profits.gross.percent().stats())
        print(profits.net.percent().stats())

        my_config = Config(
            dict(trading_rules=dict(ewmac8=ewmac_8, ewmac32=ewmac_32),
                 instrument_weights=dict(US10=0.1,
                                         EDOLLAR=0.4,
                                         CORN=0.3,
                                         SP500=0.2),
                 instrument_div_multiplier=1.5,
                 forecast_scalars=dict(ewmac8=5.3, ewmac32=2.65),
                 forecast_weights=dict(ewmac8=0.5, ewmac32=0.5),
                 forecast_div_multiplier=1.1,
                 percentage_vol_target=25.00,
                 notional_trading_capital=500000,
                 base_currency="GBP"))
        print(my_config)
        my_system = System(
            [
                Account(),
                Portfolios(),
                PositionSizing(),
                ForecastCombine(),
                ForecastScaleCap(),
                Rules()
            ],
            data,
            my_config,
        )
        print(my_system.portfolio.get_notional_position("EDOLLAR").tail(5))

        my_config = Config("systems.provided.example.simplesystemconfig.yaml")
        print(my_config)
        my_system = System(
            [
                Account(),
                Portfolios(),
                PositionSizing(),
                ForecastCombine(),
                ForecastScaleCap(),
                Rules()
            ],
            data,
            my_config,
        )
        print(my_system.rules.get_raw_forecast("EDOLLAR", "ewmac32").tail(5))
        print(my_system.rules.get_raw_forecast("EDOLLAR", "ewmac8").tail(5))
        print(
            my_system.forecastScaleCap.get_capped_forecast(
                "EDOLLAR", "ewmac32").tail(5))
        print(
            my_system.forecastScaleCap.get_forecast_scalar(
                "EDOLLAR", "ewmac32"))
        print(my_system.combForecast.get_combined_forecast("EDOLLAR").tail(5))
        print(my_system.combForecast.get_forecast_weights("EDOLLAR").tail(5))

        print(my_system.positionSize.get_subsystem_position("EDOLLAR").tail(5))

        print(my_system.portfolio.get_notional_position("EDOLLAR").tail(5))
Exemplo n.º 10
0
def ewmac_32():
    return TradingRule(dict(function=ewmac, other_args=dict(Lfast=32, Lslow=128)))
Exemplo n.º 11
0
def ewmac_8():
    return TradingRule((ewmac, [], dict(Lfast=8, Lslow=32)))