Ejemplo n.º 1
0
    def __init__(self,
                 start_dt,
                 exchange,
                 data_handler,
                 account_id=None,
                 base_currency="USD",
                 initial_funds=0.0,
                 fee_model=ZeroFeeModel(),
                 slippage_model=None,
                 market_impact_model=None):
        self.start_dt = start_dt
        self.exchange = exchange
        self.data_handler = data_handler
        self.current_dt = start_dt
        self.account_id = account_id

        self.base_currency = self._set_base_currency(base_currency)
        self.initial_funds = self._set_initial_funds(initial_funds)
        self.fee_model = self._set_fee_model(fee_model)
        self.slippage_model = None  # TODO: Implement
        self.market_impact_model = None  # TODO: Implement

        self.cash_balances = self._set_cash_balances()
        self.portfolios = self._set_initial_portfolios()
        self.open_orders = self._set_initial_open_orders()

        print('Initialising simulated broker "%s"...' % self.account_id)
Ejemplo n.º 2
0
    def __init__(
        self,
        start_dt:pd.Timestamp,
        exchange:Exchange,
        data_handler:DataHandler,
        account_id:str="000001",
        base_currency:str="USD",
        initial_funds:float=1e6,
        fee_model:FeeModel=ZeroFeeModel(),
        slippage_model=None,
        market_impact_model=None
    ):

        super(SimulatedBroker, self).__init__(account_id=account_id, data_handler=data_handler, exchange=exchange, fee_model=self._set_fee_model(fee_model))
        self.start_dt = start_dt
        #self.exchange = exchange
        #self.data_handler = data_handler
        self.current_dt = start_dt
        #self.account_id = account_id

        self.base_currency = self._set_base_currency(base_currency)
        self.initial_funds = self._set_initial_funds(initial_funds)
        #self.fee_model = self._set_fee_model(fee_model)
        self.slippage_model = None  # TODO: Implement
        self.market_impact_model = None  # TODO: Implement

        self.cash_balances = self._set_cash_balances()
        self.portfolios = self._set_initial_portfolios()
        self.open_orders = self._set_initial_open_orders()

        if settings.PRINT_EVENTS:
            print('Initialising simulated broker "%s"...' % self.account_id)
Ejemplo n.º 3
0
def test_commission_is_zero_uniformly():
    """
    Tests that each method returns zero commission,
    irrespective of asset, consideration or broker.
    """
    zbc = ZeroFeeModel()
    asset = AssetMock()
    quantity = 100
    consideration = 1000.0
    broker = BrokerMock()

    assert zbc._calc_commission(asset, quantity, consideration,
                                broker=broker) == 0.0
    assert zbc._calc_tax(asset, quantity, consideration, broker=broker) == 0.0
    assert zbc.calc_total_cost(asset, quantity, consideration,
                               broker=broker) == 0.0
Ejemplo n.º 4
0
def test_all_cases_of_set_broker_commission():
    """
    Tests that _set_broker_commission correctly sets the
    appropriate broker commission model depending upon
    user choice.
    """
    start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
    exchange = ExchangeMock()
    data_handler = DataHandlerMock()

    # Broker commission is None
    sb1 = SimulatedBroker(start_dt, exchange, data_handler)
    assert sb1.fee_model.__class__.__name__ == "ZeroFeeModel"

    # Broker commission is specified as a subclass
    # of FeeModel abstract base class
    bc2 = ZeroFeeModel()
    sb2 = SimulatedBroker(
        start_dt, exchange, data_handler, fee_model=bc2
    )
    assert sb2.fee_model.__class__.__name__ == "ZeroFeeModel"

    # FeeModel is mis-specified and thus
    # raises a TypeError
    with pytest.raises(TypeError):
        SimulatedBroker(
            start_dt, exchange, data_handler, fee_model="bad_fee_model"
        )
Ejemplo n.º 5
0
def test_initial_settings_for_default_simulated_broker():
    """
    Tests that the SimulatedBroker settings are set
    correctly for default settings.
    """
    start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
    exchange = ExchangeMock()
    data_handler = DataHandlerMock()

    # Test a default SimulatedBroker
    sb1 = SimulatedBroker(start_dt, exchange, data_handler)

    assert sb1.start_dt == start_dt
    assert sb1.current_dt == start_dt
    assert sb1.exchange == exchange
    assert sb1.account_id is None
    assert sb1.base_currency == "USD"
    assert sb1.initial_funds == 0.0
    assert type(sb1.fee_model) == ZeroFeeModel

    tcb1 = dict(
        zip(
            settings.SUPPORTED['CURRENCIES'],
            [0.0] * len(settings.SUPPORTED['CURRENCIES'])
        )
    )

    assert sb1.cash_balances == tcb1
    assert sb1.portfolios == {}
    assert sb1.open_orders == {}

    # Test a SimulatedBroker with some parameters set
    sb2 = SimulatedBroker(
        start_dt, exchange, data_handler, account_id="ACCT1234",
        base_currency="GBP", initial_funds=1e6,
        fee_model=ZeroFeeModel()
    )

    assert sb2.start_dt == start_dt
    assert sb2.current_dt == start_dt
    assert sb2.exchange == exchange
    assert sb2.account_id == "ACCT1234"
    assert sb2.base_currency == "GBP"
    assert sb2.initial_funds == 1e6
    assert type(sb2.fee_model) == ZeroFeeModel

    tcb2 = dict(
        zip(
            settings.SUPPORTED['CURRENCIES'],
            [0.0] * len(settings.SUPPORTED['CURRENCIES'])
        )
    )
    tcb2["GBP"] = 1e6

    assert sb2.cash_balances == tcb2
    assert sb2.portfolios == {}
    assert sb2.open_orders == {}
Ejemplo n.º 6
0
    def __init__(
        self,
        start_dt,
        end_dt,
        universe,
        alpha_model,
        risk_model=None,
        signals=None,
        initial_cash=1e6,
        rebalance='weekly',
        account_name=DEFAULT_ACCOUNT_NAME,
        portfolio_id=DEFAULT_PORTFOLIO_ID,
        portfolio_name=DEFAULT_PORTFOLIO_NAME,
        long_only=False,
        fee_model=ZeroFeeModel(),
        burn_in_dt=None,
        data_handler=None,
        **kwargs
    ):
        self.start_dt = start_dt
        self.end_dt = end_dt
        self.universe = universe
        self.alpha_model = alpha_model
        self.risk_model = risk_model
        self.signals = signals
        self.initial_cash = initial_cash
        self.rebalance = rebalance
        self.account_name = account_name
        self.portfolio_id = portfolio_id
        self.portfolio_name = portfolio_name
        self.long_only = long_only
        self.fee_model = fee_model
        self.burn_in_dt = burn_in_dt

        self.exchange = self._create_exchange()
        self.data_handler = self._create_data_handler(data_handler)
        self.broker = self._create_broker()
        self.sim_engine = self._create_simulation_engine()

        if rebalance == 'weekly':
            if 'rebalance_weekday' in kwargs:
                self.rebalance_weekday = kwargs['rebalance_weekday']
            else:
                raise ValueError(
                    "Rebalance frequency was set to 'weekly' but no specific "
                    "weekday was provided. Try adding the 'rebalance_weekday' "
                    "keyword argument to the instantiation of "
                    "BacktestTradingSession, e.g. with 'WED'."
                )
        self.rebalance_schedule = self._create_rebalance_event_times()

        self.qts = self._create_quant_trading_system(**kwargs)
        self.equity_curve = []
        self.target_allocations = []
Ejemplo n.º 7
0
        'EQ:SPY': 0.6,
        'EQ:AGG': 0.4
    })
    strategy_backtest = BacktestTradingSession(start_dt,
                                               end_dt,
                                               strategy_universe,
                                               strategy_alpha_model,
                                               rebalance='end_of_month',
                                               cash_buffer_percentage=0.01,
                                               data_handler=data_handler,
                                               fee_model=fee_model)
    strategy_backtest.run()

    # Construct benchmark assets (60/40 without fees)
    benchmark_backtest = BacktestTradingSession(start_dt,
                                                end_dt,
                                                strategy_universe,
                                                strategy_alpha_model,
                                                rebalance='end_of_month',
                                                cash_buffer_percentage=0.01,
                                                data_handler=data_handler,
                                                fee_model=ZeroFeeModel())
    benchmark_backtest.run()

    # Performance Output
    tearsheet = TearsheetStatistics(
        strategy_equity=strategy_backtest.get_equity_curve(),
        benchmark_equity=benchmark_backtest.get_equity_curve(),
        title='60/40 US Equities/Bonds (With/Without Fees)')
    tearsheet.plot_results()