def test_get_capped_forecast(self):

        # fixed, normal cap
        self.assertAlmostEqual(
            self.system.forecastScaleCap.get_capped_forecast(
                "EDOLLAR", "ewmac8").tail(1).values[0], 0.871230635)

        # estimated, normal cap
        config = copy.copy(self.config)
        config.use_forecast_scale_estimates = True

        system2 = System([self.rawdata, self.rules,
                          self.forecast_scale_cap()], self.data, config)
        self.assertAlmostEqual(system2.forecastScaleCap.get_forecast_scalar(
            "EDOLLAR", "ewmac8").tail(1).values[0],
                               5.8,
                               places=1)

        # binding cap
        config.use_forecast_scale_estimates = False
        config.forecast_cap = 0.2
        system3 = System([self.rawdata, self.rules,
                          self.forecast_scale_cap()], self.data, config)
        self.assertAlmostEqual(
            system3.forecastScaleCap.get_capped_forecast(
                "EDOLLAR", "ewmac8").tail(1).values[0], 0.2)
    def test_get_forecast_scalar(self):
        # fixed
        ## From config
        self.assertEqual(self.system.forecastScaleCap.get_forecast_scalar("EDOLLAR", "ewmac8"), 5.3)

        ## default
        config = copy.copy(self.config)
        unused = config.trading_rules['ewmac8'].pop('forecast_scalar')
        system2 = System([self.rawdata, self.rules, self.forecast_scale_cap()], self.data, config)
        self.assertEqual(system2.forecastScaleCap.get_forecast_scalar("EDOLLAR", "ewmac8"),   1.0)

        ## other config location
        setattr(config, 'forecast_scalars', dict(ewmac8=11.0))
        system3 = System([self.rawdata, self.rules, self.forecast_scale_cap()], self.data, config)
        self.assertEqual(system3.forecastScaleCap.get_forecast_scalar("EDOLLAR", "ewmac8"), 11.0)


        # estimated
        config = copy.copy(self.config)
        config.use_forecast_scale_estimates = True

        system2 = System([self.rawdata, self.rules, self.forecast_scale_cap()], self.data, config)
        ## From default
        self.assertAlmostEqual(system2.forecastScaleCap.get_forecast_scalar("EDOLLAR", "ewmac8").tail(1).values[0],  5.85109081)

        ## From config
        scale_config=dict(pool_instruments=False)
        config.forecast_scalar_estimate=scale_config
        system2=System([self.rawdata, self.rules, self.forecast_scale_cap()], self.data, config)
        self.assertAlmostEqual(system2.forecastScaleCap.get_forecast_scalar("EDOLLAR", "ewmac8").tail(1).values[0], 5.653444301)
Exemplo n.º 3
0
def simplesystem(data=None, config=None, log_level="on"):
    """
    Example of how to 'wrap' a complete system
    """
    if config is None:
        config = Config("systems.provided.example.simplesystemconfig.yaml")
    if data is None:
        data = csvFuturesSimData()

    my_system = System(
        [
            Account(),
            Portfolios(),
            PositionSizing(),
            ForecastCombine(),
            ForecastScaleCap(),
            Rules(),
        ],
        data,
        config,
    )

    my_system.set_logging_level(log_level)

    return my_system
Exemplo n.º 4
0
def futures_system(sim_data=arg_not_supplied,
                   config_filename="systems.provided.rob_system.config.yaml"):

    if sim_data is arg_not_supplied:
        sim_data = dbFuturesSimData()

    config = Config(config_filename)

    system = System(
        [
            Risk(),
            accountForOptimisedStage(),
            optimisedPositions(),
            Portfolios(),
            PositionSizing(),
            myFuturesRawData(),
            ForecastCombine(),
            volAttenForecastScaleCap(),
            Rules(),
        ],
        sim_data,
        config,
    )
    system.set_logging_level("on")

    return system
Exemplo n.º 5
0
    def testRules(self):

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

        rules = Rules(
            dict(
                function=
                "systems.provided.example.rules.ewmac_forecast_with_defaults"))
        system = System([rules], data)

        ans = system.rules.get_raw_forecast("EDOLLAR", "rule0")
        self.assertAlmostEqual(ans.tail(1).values[0], -3.280028, 5)

        config = Config(
            dict(trading_rules=dict(ewmac=dict(
                function=
                "systems.provided.example.rules.ewmac_forecast_with_defaults"))
                 ))
        rules = Rules()
        system = System([rules], data, config)
        ans = system.rules.get_raw_forecast("EDOLLAR", "ewmac")
        self.assertAlmostEqual(ans.tail(1).values[0], -3.28002839, 5)

        config = Config("systems.provided.example.exampleconfig.yaml")
        rawdata = RawData()

        rules = Rules()
        system = System([rules, rawdata], data, config)
        ans = system.rules.get_raw_forecast("EDOLLAR", "ewmac8")
        self.assertAlmostEqual(ans.tail(1).values[0], -2.158634, 5)
Exemplo n.º 6
0
def futures_system(data=None, config=None, trading_rules=None, log_level="terse"):
    """

    :param data: data object (defaults to reading from csv files)
    :type data: sysdata.data.Data, or anything that inherits from it

    :param config: Configuration object (defaults to futuresconfig.yaml in this directory)
    :type config: sysdata.configdata.Config

    :param trading_rules: Set of trading rules to use (defaults to set specified in config object)
    :param trading_rules: list or dict of TradingRules, or something that can be parsed to that

    :param log_level: Set of trading rules to use (defaults to set specified in config object)
    :type log_level: str

    """

    if data is None:
        data = csvFuturesData()

    if config is None:
        config = Config(
            "systems.provided.futures_chapter15.futuresestimateconfig.yaml")

    rules = Rules(trading_rules)

    system = System([Account(), Portfolios(), PositionSizing(), FuturesRawData(), ForecastCombine(),
                     ForecastScaleCap(), rules], data, config)

    system.set_logging_level(log_level) 

    return system
Exemplo n.º 7
0
    def testRules(self):

        # config=Config(dict(trading_rules=dict(ewmac=dict(function="systems.provided.example.rules.ewmac_forecast_with_defaults"))))
        data = csvFuturesData("sysdata.tests")

        rules = Rules(
            dict(
                function=
                "systems.provided.example.rules.ewmac_forecast_with_defaults"))
        system = System([rules], data)

        ans = system.rules.get_raw_forecast("EDOLLAR", "rule0")
        self.assertAlmostEqual(ans.tail(1).values[0], 2.1384223788141838, 5)

        config = Config(
            dict(trading_rules=dict(ewmac=dict(
                function=
                "systems.provided.example.rules.ewmac_forecast_with_defaults"))
                 ))
        rules = Rules()
        system = System([rules], data, config)
        ans = system.rules.get_raw_forecast("EDOLLAR", "ewmac")
        self.assertAlmostEqual(ans.tail(1).values[0], 2.1384223788141838, 5)

        config = Config("systems.provided.example.exampleconfig.yaml")
        rawdata = RawData()

        rules = Rules()
        system = System([rules, rawdata], data, config)
        ans = system.rules.get_raw_forecast("EDOLLAR", "ewmac8")
        self.assertAlmostEqual(ans.tail(1).values[0], 0.16438313875, 5)
    def test_get_raw_fixed_forecast_weights(self):

        # fixed weights:
        #    nested dict (in config)
        ans1a = self.system.combForecast.get_forecast_weights("EDOLLAR")
        self.assertAlmostEqual(ans1a.ewmac16.values[-1], 0.5)

        ans1b = self.system.combForecast.get_raw_forecast_weights("BUND")
        self.assertEqual(ans1b.ewmac8.values[-1], 1.0)

        #    missing; equal weights
        config = copy.copy(self.config)
        del (config.forecast_weights)
        system2 = System(
            [self.rawdata, self.rules, self.fcs,
             self.forecast_combine()], self.data, config)
        ans2 = system2.combForecast.get_forecast_weights("BUND")
        self.assertAlmostEqual(ans2.ewmac8.values[-1], 0.49917057)  # smoothing

        #    non nested dict
        config.forecast_weights = dict(ewmac8=0.1, ewmac16=0.9)
        system3 = System(
            [self.rawdata, self.rules, self.fcs,
             self.forecast_combine()], self.data, config)
        ans3 = system3.combForecast.get_forecast_weights("BUND")
        self.assertEqual(ans3.ewmac8.values[-1], 0.099834114877206212)
    def test_get_trading_rule_list(self):

        # fixed weights
        ans = self.system.combForecast.get_trading_rule_list("EDOLLAR")
        self.assertEqual(ans, ['ewmac16', 'ewmac8'])

        ans2 = self.system.combForecast.get_trading_rule_list("BUND")
        self.assertEqual(ans2, ['ewmac8'])

        # fixed weights - non nested dict
        config = copy.copy(self.config)
        config.forecast_weights = dict(ewmac8=.5, ewmac16=.5)
        system2 = System(
            [self.rawdata, self.rules, self.fcs,
             self.forecast_combine()], self.data, config)
        ans3 = system2.combForecast.get_trading_rule_list("EDOLLAR")
        self.assertEqual(ans3, ['ewmac16', 'ewmac8'])
        ans4 = system2.combForecast.get_trading_rule_list("BUND")
        self.assertEqual(ans4, ans3)

        # fixed weights - missing
        del (config.forecast_weights)
        system3 = System(
            [self.rawdata, self.rules, self.fcs,
             self.forecast_combine()], self.data, config)
        ans5 = system3.combForecast.get_trading_rule_list("EDOLLAR")
        self.assertEqual(ans5, ['ewmac16', 'ewmac8'])

        # estimated weights - missing
        config.use_forecast_weight_estimates = True
        system4 = System(
            [self.rawdata, self.rules, self.fcs,
             self.forecast_combine()], self.data, config)
        ans6 = system4.combForecast.get_trading_rule_list("EDOLLAR")
        self.assertEqual(ans6, ['ewmac16', 'ewmac8'])

        # estimated weights - non nested
        setattr(config, "rule_variations", ["ewmac8"])
        system5 = System(
            [self.rawdata, self.rules, self.fcs,
             self.forecast_combine()], self.data, config)
        ans6 = system5.combForecast.get_trading_rule_list("EDOLLAR")
        self.assertEqual(ans6, ['ewmac8'])

        #estimated weights - nested dict
        setattr(
            config, "rule_variations",
            dict(EDOLLAR=["ewmac8"],
                 BUND=["ewmac16"],
                 US10=["ewmac8", "ewmac16"]))
        system6 = System(
            [self.rawdata, self.rules, self.fcs,
             self.forecast_combine()], self.data, config)
        ans7 = system6.combForecast.get_trading_rule_list("EDOLLAR")
        self.assertEqual(ans7, ['ewmac8'])
        ans8 = system6.combForecast.get_trading_rule_list("BUND")
        self.assertEqual(ans8, ['ewmac16'])
        ans8 = system6.combForecast.get_trading_rule_list("US10")
        self.assertEqual(ans8, ['ewmac16', 'ewmac8'])  # missing
Exemplo n.º 10
0
def random_system_for_regression(config, rules, log_level="on"):

    my_system = System([Account(), PortfoliosFixed(), PositionSizing(), ForecastCombineEstimated(), ForecastScaleCapEstimated(), rules,
                        RawData()], csvFuturesData(), config)

    my_system.set_logging_level(log_level)

    return my_system
Exemplo n.º 11
0
def futures_system(data=None, config=None, trading_rules=None, log_level="on"):
    """

    :param data: data object (defaults to reading from csv files)
    :type data: sysdata.data.Data, or anything that inherits from it

    :param config: Configuration object (defaults to futuresconfig.yaml in this directory)
    :type config: sysdata.configdata.Config

    :param trading_rules: Set of trading rules to use (defaults to set specified in config object)
    :type trading_rules: list or dict of TradingRules, or something that can be parsed to that

    :param log_level: How much logging to do
    :type log_level: str


    >>> system=futures_system(log_level="off")
    >>> system
    System with stages: accounts, portfolio, positionSize, rawdata, combForecast, forecastScaleCap, rules
    >>> system.rules.get_raw_forecast("EDOLLAR", "ewmac2_8").dropna().head(2)
                ewmac2_8
    1983-10-10  0.695929
    1983-10-11 -0.604704

                ewmac2_8
    2015-04-21  0.172416
    2015-04-22 -0.477559
    >>> system.rules.get_raw_forecast("EDOLLAR", "carry").dropna().head(2)
                   carry
    1983-10-10  0.952297
    1983-10-11  0.854075

                   carry
    2015-04-21  0.350892
    2015-04-22  0.350892
    """

    if data is None:
        data = csvFuturesData()

    if config is None:
        config = Config(
            "systems.provided.futures_chapter15.futuresconfig.yaml")

    rules = Rules(trading_rules)

    system = System([
        Account(),
        PortfoliosFixed(),
        PositionSizing(),
        FuturesRawData(),
        ForecastCombine(),
        ForecastScaleCap(), rules
    ], data, config)

    system.set_logging_level(log_level)

    return system
Exemplo n.º 12
0
def futures_system(data=None, config=None, trading_rules=None, log_level="on"):
    """

    :param data: data object (defaults to reading from csv files)
    :type data: sysdata.data.Data, or anything that inherits from it

    :param config: Configuration object (defaults to futuresconfig.yaml in this directory)
    :type config: sysdata.configdata.Config

    :param trading_rules: Set of trading rules to use (defaults to set specified in config object)
    :type trading_rules: list or dict of TradingRules, or something that can be parsed to that

    :param log_level: How much logging to do
    :type log_level: str


    >>> system=futures_system(log_level="off")
    >>> system
    System with stages: accounts, portfolio, positionSize, rawdata, combForecast, forecastScaleCap, rules
    >>> system.rules.get_raw_forecast("EDOLLAR", "ewmac2_8").dropna().head(2)
                ewmac2_8
    1983-10-10  0.695929
    1983-10-11 -0.604704

                ewmac2_8
    2015-04-21  0.172416
    2015-04-22 -0.477559
    >>> system.rules.get_raw_forecast("EDOLLAR", "carry").dropna().head(2)
                   carry
    1983-10-10  0.952297
    1983-10-11  0.854075

                   carry
    2015-04-21  0.350892
    2015-04-22  0.350892
    """

    if data is None:
        data = csvFuturesData()

    if config is None:
        config = Config(
            "systems.provided.futures_chapter15.futuresconfig.yaml")

    rules = Rules(trading_rules)

    system = System([
        Account(), Portfolios(), PositionSizing(), FuturesRawData(),
        ForecastCombine(), ForecastScaleCap(), rules
    ], data, config)

    system.set_logging_level(log_level)

    return system
Exemplo n.º 13
0
def random_system_for_regression(data, config, rules, log_level="on"):

    my_system = System([
        Account(), PortfoliosFixed(), PositionSizing(),
        ForecastCombineEstimated(), ForecastScaleCapEstimated(), rules,
        RawData()
    ], data, config)

    my_system.set_logging_level(log_level)

    return my_system
Exemplo n.º 14
0
def simplesystem(data=None, config=None, log_level="on"):
    """
    Example of how to 'wrap' a complete system
    """
    if config is None:
        config = Config("systems.provided.example.simplesystemconfig.yaml")
    if data is None:
        data = csvFuturesData()

    my_system = System([Account(), PortfoliosFixed(), PositionSizing(), ForecastCombineFixed(), ForecastScaleCapFixed(), Rules()
                        ], data, config)
    
    my_system.set_logging_level(log_level)

    return my_system
Exemplo n.º 15
0
    def test_simple_system_config_import(self, data):

        my_config = Config("systems.provided.example.simplesystemconfig.yaml")
        my_config.risk_overlay = arg_not_supplied
        my_config.exclude_instrument_lists = dict(
            ignore_instruments=["MILK"],
            trading_restrictions=["BUTTER"],
            bad_markets=["CHEESE"],
        )
        print(my_config)
        my_system = System(
            [
                Account(),
                Portfolios(),
                PositionSizing(),
                ForecastCombine(),
                ForecastScaleCap(),
                Rules(),
                RawData(),
            ],
            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.º 16
0
    def testCallingTradingRule(self):

        # config=Config(dict(trading_rules=dict(ewmac=dict(function="systems.provided.example.rules.ewmac_forecast_with_defaults"))))
        data = csvFuturesData("sysdata.tests")

        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], 2.1384223788141838, 5)

        # Change the data source
        rule = TradingRule((
            "systems.provided.example.rules.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], 0.029376, 5)

        rule = TradingRule(
            dict(
                function=
                "systems.provided.example.rules.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.84426755)
Exemplo n.º 17
0
    def testCallingTradingRule(self):

        # config=Config(dict(trading_rules=dict(ewmac=dict(function="systems.provided.example.rules.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.example.rules.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.example.rules.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.º 18
0
    def test_simple_system_costs(
        self,
        data,
        raw_data,
        my_rules,
        my_config,
        fcs,
        combiner,
        possizer,
        portfolio,
        account,
    ):

        my_config.forecast_weights = dict(ewmac8=0.5, ewmac32=0.5)
        my_config.instrument_weights = dict(US10=0.1, EDOLLAR=0.4, CORN=0.3, SP500=0.2)

        my_system = System(
            [fcs, my_rules, combiner, possizer, portfolio, account, raw_data],
            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())
Exemplo n.º 19
0
 def setUp(self):
     stage = SystemStage()
     stage.name = "test"
     data = simData()
     config = Config(dict(instruments=["another_code", "code"]))
     system = System([stage], data=data, config=config)
     self.system = system
Exemplo n.º 20
0
 def setUp(self):
     (accounts, fcs, rules, rawdata, data,
      config) = get_test_object_futures_with_rules_and_capping_estimate()
     system = System(
         [accounts, rawdata, rules, fcs,
          ForecastCombineEstimated()], data, config)
     setattr(self, "system", system)
Exemplo n.º 21
0
    def test_get_daily_cash_vol_target(self):
        ans_dict = self.system.positionSize.get_vol_target_dict()
        self.assertEqual(ans_dict["base_currency"], "GBP")
        self.assertEqual(ans_dict["annual_cash_vol_target"], 16000.0)
        self.assertEqual(ans_dict["daily_cash_vol_target"], 1000.0)
        self.assertEqual(ans_dict["notional_trading_capital"], 100000.0)
        self.assertEqual(ans_dict["percentage_vol_target"], 16.0)

        # test for missing config defaults
        system2 = System(
            [
                self.rawdata,
                self.rules,
                self.fcs,
                self.forecast_combine,
                self.position_sizing(),
            ],
            self.data,
        )
        ans_dict2 = system2.positionSize.get_vol_target_dict()
        self.assertEqual(ans_dict2["base_currency"], "USD")
        self.assertEqual(ans_dict2["annual_cash_vol_target"], 160000.0)
        self.assertEqual(ans_dict2["daily_cash_vol_target"], 10000.0)
        self.assertEqual(ans_dict2["notional_trading_capital"], 1000000.0)
        self.assertEqual(ans_dict2["percentage_vol_target"], 16.0)
Exemplo n.º 22
0
def updated_buffered_positions(data: dataBlob, strategy_name: str,
                               system: System):
    log = data.log

    data_optimal_positions = dataOptimalPositions(data)

    list_of_instruments = system.get_instrument_list()
    for instrument_code in list_of_instruments:
        lower_buffer, upper_buffer = get_position_buffers_from_system(
            system, instrument_code)
        position_entry = construct_position_entry(
            data=data,
            system=system,
            instrument_code=instrument_code,
            lower_buffer=lower_buffer,
            upper_buffer=upper_buffer,
        )
        instrument_strategy = instrumentStrategy(
            instrument_code=instrument_code, strategy_name=strategy_name)
        data_optimal_positions.update_optimal_position_for_instrument_strategy(
            instrument_strategy=instrument_strategy,
            position_entry=position_entry)
        log.msg(
            "New buffered positions %.3f %.3f" %
            (position_entry.lower_position, position_entry.upper_position),
            instrument_code=instrument_code,
        )
Exemplo n.º 23
0
    def setUp(self):

        (
            posobject,
            combobject,
            capobject,
            rules,
            rawdata,
            data,
            config,
        ) = get_test_object_futures_with_pos_sizing()
        system = System(
            [rawdata, rules, posobject, combobject, capobject, Portfolios()],
            data,
            config,
        )

        self.system = system
        self.config = config
        self.rules = rules
        self.rawdata = rawdata
        self.fcs = capobject
        self.forecast_combine = combobject
        self.data = data
        self.possizing = posobject
        self.portfolios = Portfolios
Exemplo n.º 24
0
    def test_estimated_dm(self):
        config = copy.copy(self.config)
        config.use_instrument_weight_estimates = True
        system2 = System(
            [
                self.rawdata,
                self.rules,
                self.possizing,
                self.forecast_combine,
                self.fcs,
                Account(),
                self.portfolios(),
            ],
            self.data,
            config,
        )
        ans = system2.portfolio.get_instrument_correlation_matrix(
        ).corr_list[-1]

        self.assertAlmostEqual(ans[0][1], 0.3889, places=3)
        self.assertAlmostEqual(ans[0][2], 0.5014, places=3)
        self.assertAlmostEqual(ans[1][2], 0.8771, places=3)

        ans = system2.portfolio.get_estimated_instrument_diversification_multiplier(
        )
        self.assertAlmostEqual(ans.values[-1], 1.1855, places=3)
Exemplo n.º 25
0
    def setUp(self):

        system = System(
            [testStage1(), testStage2()],
            Data(),
            Config(dict(instruments=["code", "another_code"])))
        self.system = system
Exemplo n.º 26
0
def futures_system(
        data=None,
        config=None,
        trading_rules=None,
        log_level="terse"):
    """

    :param data: data object (defaults to reading from csv files)
    :type data: sysdata.data.simData, or anything that inherits from it

    :param config: Configuration object (defaults to futuresconfig.yaml in this directory)
    :type config: sysdata.configdata.Config

    :param trading_rules: Set of trading rules to use (defaults to set specified in config object)
    :param trading_rules: list or dict of TradingRules, or something that can be parsed to that

    :param log_level: Set of trading rules to use (defaults to set specified in config object)
    :type log_level: str

    """

    if data is None:
        data = csvFuturesSimData()

    if config is None:
        config = Config(
            "systems.provided.futures_chapter15.futuresestimateconfig.yaml")

    rules = Rules(trading_rules)

    system = System(
        [
            Account(),
            Portfolios(),
            PositionSizing(),
            FuturesRawData(),
            ForecastCombine(),
            ForecastScaleCap(),
            rules,
        ],
        data,
        config,
    )

    system.set_logging_level(log_level)

    return system
 def setUp(self):
     (rules, rawdata, data, config) = get_test_object_futures_with_rules()
     system = System([rawdata, rules, ForecastScaleCap()], data, config)
     self.system = system
     self.config = config
     self.rules = rules
     self.rawdata = rawdata
     self.forecast_scale_cap = ForecastScaleCap
     self.data = data
Exemplo n.º 28
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.º 29
0
    def testCarryRule(self):
        NOTUSEDrawdata, data, NOTUSEDconfig = get_test_object()

        rawdata = FuturesRawData()
        rules = Rules()
        system = System([rawdata, rules], data)
        rule = TradingRule(carry2, [
            "rawdata.daily_annualised_roll",
        ], dict(smooth_days=90))
        ans = rule.call(system, "EDOLLAR")
        self.assertAlmostEqual(ans.tail(1).values[0], 0.138302, 5)
    def test_get_forecast_cap(self):

        ans=self.system.forecastScaleCap.get_forecast_cap()
        self.assertEqual(ans, 21.0)

        ## test defaults
        config = self.config
        del(config.forecast_cap)
        system3=System([self.rawdata, self.rules, self.forecast_scale_cap()], self.data, config)
        ans=system3.forecastScaleCap.get_forecast_cap()
        self.assertEqual(ans, 20.0)
    def setUpWithEstimatedReturns(self):
        config = copy.copy(self.config)
        config.use_forecast_weight_estimates = True
        config.use_forecast_div_mult_estimates = True
        new_system = System([
            self.rawdata, self.rules, self.fcs,
            self.forecast_combine(),
            Account()
        ], self.data, config)

        return new_system
Exemplo n.º 32
0
    def testCarryRule(self):
        data = csvFuturesData("sysdata.tests")

        rawdata = FuturesRawData()
        rules = Rules()
        system = System([rawdata, rules], data)
        rule = TradingRule(carry, [
            "rawdata.daily_annualised_roll", "rawdata.daily_returns_volatility"
        ], dict(smooth_days=90))
        ans = rule.call(system, "EDOLLAR")
        self.assertAlmostEqual(ans.iloc[-1][0], 0.411686026, 5)
Exemplo n.º 33
0
def futures_system(data, config):

    system = System(
        [
            Risk(),
            accountForOptimisedStage(),
            optimisedPositions(),
            Portfolios(),
            PositionSizing(),
            RawData(),
            ForecastCombine(),
            ForecastScaleCap(),
            Rules(),
        ],
        data,
        config,
    )
    system.set_logging_level("on")

    return system
Exemplo n.º 34
0
    def setUp(self):
        class testStage(SystemStage):
            @property
            def name(self):
                return "test"

        stage = testStage()
        data = simData()
        config = Config(dict(instruments=["another_code", "code"]))
        system = System([stage], data=data, config=config)
        self.system = system
Exemplo n.º 35
0
from syscore.accounting import *

from systems.basesystem import System
from systems.account import Account
from systems.tests.testdata import get_test_object_futures_with_portfolios
(portfolio, posobject, combobject, capobject, rules, rawdata, data, config)=get_test_object_futures_with_portfolios()
system=System([portfolio, posobject, combobject, capobject, rules, rawdata, Account()], data, config)

instrument_code="EDOLLAR"

rule_variations=system.rules.trading_rules()
rule_variation_name="ewmac16"

this_stage=system.accounts
price = this_stage.get_daily_price(instrument_code)
get_daily_returns_volatility = this_stage.get_daily_returns_volatility(
    instrument_code)

forecast = this_stage.get_capped_forecast(
                                              instrument_code, rule_variation_name)

accountCurve(percentage=True, price=price, forecast=forecast, get_daily_returns_volatility=get_daily_returns_volatility)


instruments=system.get_instrument_list()

capital = this_stage.get_notional_capital()
ann_risk_target=system.positionSize.get_daily_cash_vol_target()['percentage_vol_target']/100.0

acc_list=[]
Exemplo n.º 36
0
    def testName(self):
        stage = SystemStage()
        stage.name = "test"
        data=Data()
        stage._protected = ["protected"]

        system = System([stage], data, None)
        print(system._cache)

        system.set_item_in_cache(3, ("test","a"), "US10")
        print(system._cache)

        self.assertEqual(system.get_item_from_cache(("test","a"), "US10"), 3)

        def afunction(system, instrument_code, stage, wibble, another_wibble=10):
            return instrument_code + wibble + str(another_wibble) + stage.name

        def anestedfunction(system, instrument_code,
                            keyname, stage, wibble, another_wibble=10):
            return instrument_code + wibble + keyname + str(another_wibble) + stage.name

        ans = system.calc_or_cache("b", "c", afunction, stage,  "d")
        print(system._cache)

        ans = system.calc_or_cache("b", "c", afunction, stage, "d", 20.0)
        print(system._cache)

        ans = system.calc_or_cache_nested(
            "c", "SP500", "thing", anestedfunction, stage, "k")
        print(system._cache)

        ans = system.calc_or_cache("b", ALL_KEYNAME, afunction, stage, "e", 120.0)
        print(system._cache)

        ans = system.calc_or_cache(
            "protected", ALL_KEYNAME, afunction, stage, "e", 120.0)

        ans = system.get_item_from_cache(("test""c"), "SP500", "thing")
        print(system._cache)

        system._delete_item_from_cache(("test","b"), "c")
        print(system._cache)

        ans = system.set_item_in_cache(10.0, ("test", "protected"), "SP500")
        print(system._cache)

        print(system.get_item_from_cache(("test","b"), ALL_KEYNAME))

        ans = system.set_item_in_cache( "protected", ("test2",10.0), "SP500")

        print(system._cache)

        print(system.get_items_across_system())
        print(system.get_items_with_data())
        print(system.get_protected_items())
        print(system.get_items_for_instrument("SP500"))
        print(system.get_itemnames_for_stage("test"))

        
        system.delete_items_for_stage("test2")

        print(system._cache)

        system.delete_items_across_system()

        print(system._cache)

        system.delete_items_across_system(True)

        print(system._cache)

        system.delete_items_for_instrument("SP500")
        print(system._cache)

        system.delete_items_for_instrument("SP500", True)
        print(system._cache)

        system.delete_item(("test","a"))

        print(system._cache)
Exemplo n.º 37
0
from systems.forecasting import Rules

"""
We can create rules in a number of different ways

Note that to make our rule work it needs to have
"""
my_rules = Rules(ewmac)
print(my_rules.trading_rules())

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.forecasting import TradingRule
ewmac_rule = TradingRule(ewmac)
my_rules = Rules(dict(ewmac=ewmac_rule))
ewmac_rule