def test__get_current_exposure(self): """ Test the result of _get_current_exposure function for a non-future ticker by inspecting the parameters passed to alpha models get_signal function. """ alpha_model_strategy = AlphaModelStrategy(self.ts, {self.alpha_model: [self.ticker]}, use_stop_losses=False) # In case of empty portfolio get_signal function should have current exposure set to OUT alpha_model_strategy.on_before_market_open() self.alpha_model.get_signal.assert_called_with(self.ticker, Exposure.OUT) # Open long position in the portfolio self.positions_in_portfolio = [Mock(spec=BacktestPosition, **{ 'contract.return_value': Contract("Example Ticker", "STK", "SIM_EXCHANGE"), 'quantity.return_value': 10, 'start_time': str_to_date("2000-01-01") })] alpha_model_strategy.on_before_market_open() self.alpha_model.get_signal.assert_called_with(self.ticker, Exposure.LONG) # Open short position in the portfolio self.positions_in_portfolio = [Mock(spec=BacktestPosition, **{ 'contract.return_value': Contract("Example Ticker", "STK", "SIM_EXCHANGE"), 'quantity.return_value': -10, 'start_time': str_to_date("2000-01-01") })] alpha_model_strategy.on_before_market_open() self.alpha_model.get_signal.assert_called_with(self.ticker, Exposure.SHORT) # Verify if in case of two positions for the same contract an exception will be raised by the strategy self.positions_in_portfolio = [BacktestPositionFactory.create_position(c) for c in ( Contract("Example Ticker", "STK", "SIM_EXCHANGE"), Contract("Example Ticker", "STK", "SIM_EXCHANGE"))] self.assertRaises(AssertionError, alpha_model_strategy.on_before_market_open)
def ticker_to_contract( self, ticker: Union[BloombergTicker, BloombergFutureTicker]) -> Contract: """ Maps ticker to corresponding ticker. The security type is derived according to the type of the Ticker - in case of BloombergTicker the 'STK' security type is chosen and in case of BloombergFutureTicker - the 'FUT' security type. Parameters ---------- ticker: BloombergTicker, BloombergFutureTicker ticker that should be mapped Returns ------- Contract corresponding contract """ if isinstance(ticker, BloombergFutureTicker): contract = Contract(symbol=ticker.ticker, security_type='FUT', exchange='SIM_EXCHANGE', contract_size=ticker.point_value) self._contract_to_future_ticker[contract] = ticker return contract elif isinstance(ticker, BloombergTicker): return Contract(symbol=ticker.ticker, security_type='STK', exchange='SIM_EXCHANGE') else: raise ValueError( "Not able to derive security type for ticker {}".format( ticker.ticker))
def test__get_current_exposure__future_ticker(self): """ Test the result of _get_current_exposure function for a future ticker in case of an empty portfolio and in case if a position for the given specific ticker exists. """ expected_current_exposure_values = [] # Set current specific ticker to ExampleZ00 Comdty and open position in the portfolio for the current ticker self.future_ticker.get_current_specific_ticker.return_value = BloombergTicker("ExampleZ00 Comdty") futures_alpha_model_strategy = AlphaModelStrategy(self.ts, {self.alpha_model: [self.future_ticker]}, use_stop_losses=False) # In case of empty portfolio get_signal function should have current exposure set to OUT futures_alpha_model_strategy.on_before_market_open() expected_current_exposure_values.append(Exposure.OUT) self.alpha_model.get_signal.assert_called_with(self.future_ticker, Exposure.OUT) self.positions_in_portfolio = [Mock(spec=BacktestPosition, **{ 'contract.return_value': Contract("ExampleZ00 Comdty", "FUT", "SIM_EXCHANGE"), 'quantity.return_value': 10, 'start_time': str_to_date("2000-01-01") })] futures_alpha_model_strategy.on_before_market_open() self.alpha_model.get_signal.assert_called_with(self.future_ticker, Exposure.LONG) self.positions_in_portfolio = [BacktestPositionFactory.create_position(c) for c in ( Contract("ExampleZ00 Comdty", "STK", "SIM_EXCHANGE"), Contract("ExampleZ00 Comdty", "STK", "SIM_EXCHANGE"))] self.assertRaises(AssertionError, futures_alpha_model_strategy.on_before_market_open)
def test__get_current_exposure__future_ticker_rolling(self, generate_close_orders): """ Test the result of _get_current_exposure function for a future ticker in case if a position for an expired contract exists in portfolio and the rolling should be performed. """ # Set the future ticker to point to a new specific ticker, different from the one in the position from portfolio self.future_ticker.get_current_specific_ticker.return_value = BloombergTicker("ExampleN01 Comdty") futures_alpha_model_strategy = AlphaModelStrategy(self.ts, {self.alpha_model: [self.future_ticker]}, use_stop_losses=False) self.positions_in_portfolio = [Mock(spec=BacktestPosition, **{ 'contract.return_value': Contract("ExampleZ00 Comdty", "FUT", "SIM_EXCHANGE"), 'quantity.return_value': 10, 'start_time': str_to_date("2000-01-01") })] futures_alpha_model_strategy.on_before_market_open() self.alpha_model.get_signal.assert_called_once_with(self.future_ticker, Exposure.LONG) self.positions_in_portfolio = [Mock(spec=BacktestPosition, **{ 'contract.return_value': Contract("ExampleZ00 Comdty", "FUT", "SIM_EXCHANGE"), 'quantity.return_value': 10, 'start_time': str_to_date("2000-01-01") }), Mock(spec=BacktestPosition, **{ 'contract.return_value': Contract("ExampleZ00 Comdty", "FUT", "SIM_EXCHANGE"), 'quantity.return_value': 20, 'start_time': str_to_date("2000-01-02") })] self.assertRaises(AssertionError, futures_alpha_model_strategy.on_before_market_open)
def setUpClass(cls): cls.initial_cash = 1000000 # 1M cls.contract = Contract('AAPL US Equity', security_type='STK', exchange='NYSE') cls.contract_size = 75 cls.fut_contract = Contract('CTZ9 Comdty', security_type='FUT', exchange='CME', contract_size=cls.contract_size) tickers = [DummyTicker(cls.contract.symbol), DummyTicker(cls.fut_contract.symbol)] cls.prices_series = QFSeries(data=[120, 250], index=tickers) cls.prices_up = QFSeries(data=[130, 270], index=tickers) cls.prices_down = QFSeries(data=[100, 210], index=tickers) cls.start_time = str_to_date('2017-01-01') cls.random_time = str_to_date('2017-02-02') cls.end_time = str_to_date('2018-02-03') cls.trades_generator = TradesGenerator()
def test_generate_close_orders__multiple_orders_close( self, future_ticker, order_factory, broker): """ There exist positions open in the portfolio for tickers, which belong to the same family as the future_ticker. Test if the order factory will be called with the necessary function and parameters to close the existing positions and if any errors have been logged (as the expiration dates did not occur, no logs should be generated). """ # Make the broker return positions with contracts_in_portfolio from the get_positions function contracts_in_portfolio = [ Contract("CLG00 Comdty", "FUT", "SIM_EXCHANGE"), Contract("CLN00 Comdty", "FUT", "SIM_EXCHANGE") ] broker.get_positions.side_effect = lambda: [ BacktestPositionFactory.create_position(c) for c in contracts_in_portfolio ] # Set current ticker to be different then any ticker from expired_contracts future_ticker.get_current_specific_ticker.return_value = BloombergTicker( "CLG01 Comdty") future_ticker.belongs_to_family.return_value = True future_ticker.get_expiration_dates.return_value = QFSeries( data=[ BloombergTicker("CLG00 Comdty"), BloombergTicker("CLN00 Comdty") ], index=[ self.current_date - RelativeDelta(days=10), self.current_date + RelativeDelta(days=5) ]) rolling_orders_generator = FuturesRollingOrdersGenerator( [future_ticker], self.timer, broker, order_factory, self.contract_ticker_mapper) rolling_orders_generator.logger = MagicMock() rolling_orders_generator.generate_close_orders() # The order factory should be called exactly once and in should contain all contracts from # contracts_in_portfolio order_factory.target_percent_orders.assert_called_once_with( {c: 0 for c in contracts_in_portfolio}, MarketOrder(), TimeInForce.GTC) # The logger error function should be called only once, as only expiration date of one of the contracts in the # portfolio already passed rolling_orders_generator.logger.error.assert_called_once()
def setUp(self): self.contract = Contract('AAPL US Equity', security_type='STK', exchange='NYSE') self.start_time = str_to_date('2017-01-01') # dummy time self.random_time = str_to_date('2017-02-02') # dummy time self.end_time = str_to_date('2018-02-03') # dummy time
def test__adjust_number_of_open_positions__multiple_models_3(self, generate_close_orders): """ Test description: - max number of positions is 1 - portfolio contains position with contract ExampleZ00 Comdty - ExampleZ00 Comdty ane Example Ticker are traded by two independent alpha models - there is signal with suggested exposure LONG for Example Ticker and OUT for ExampleN00 Comdty - Expected output: Example Ticker suggested exposure will be changed to OUT """ self.future_ticker.get_current_specific_ticker.return_value = BloombergTicker("ExampleN00 Comdty") alpha_model_2 = MagicMock() alpha_model_strategy = AlphaModelStrategy(self.ts, { self.alpha_model: [self.future_ticker], alpha_model_2: [BloombergTicker("Example Ticker")] }, use_stop_losses=False, max_open_positions=1) self.alpha_model.get_signal.return_value = Signal(self.future_ticker, Exposure.OUT, 1) alpha_model_2.get_signal.return_value = Signal(BloombergTicker("Example Ticker"), Exposure.LONG, 1) self.positions_in_portfolio = [Mock(spec=BacktestPosition, **{ 'contract.return_value': Contract("ExampleZ00 Comdty", "FUT", "SIM_EXCHANGE"), 'quantity.return_value': -10, 'start_time': str_to_date("2000-01-01") })] alpha_model_strategy.on_before_market_open() self.ts.position_sizer.size_signals.assert_called_once() args, kwargs = self.ts.position_sizer.size_signals.call_args_list[0] signals, _ = args expected_signals = [Signal(self.future_ticker, Exposure.OUT, 1), Signal(BloombergTicker("Example Ticker"), Exposure.OUT, 1)] self.assertCountEqual(signals, expected_signals)
def test__adjust_number_of_open_positions_4(self): """ Test description: - max number of positions is 1 - portfolio contains position with contract ExampleZ00 Comdty - there is signal for ExampleZ00 Comdty with suggested exposure OUT and for Example Ticker - LONG - Expected output: Example Ticker will be changed to OUT """ self.future_ticker.get_current_specific_ticker.return_value = BloombergTicker("AN01 Index") alpha_model_strategy = AlphaModelStrategy(self.ts, {self.alpha_model: [BloombergTicker("ExampleZ00 Comdty"), BloombergTicker("Example Ticker")]}, use_stop_losses=False, max_open_positions=1) exposures = { BloombergTicker("ExampleZ00 Comdty"): Exposure.OUT, BloombergTicker("Example Ticker"): Exposure.LONG, } self.alpha_model.get_signal.side_effect = lambda ticker, _: Signal(ticker, exposures[ticker], 1) self.positions_in_portfolio = [Mock(spec=BacktestPosition, **{ 'contract.return_value': Contract("ExampleZ00 Comdty", "FUT", "SIM_EXCHANGE"), 'quantity.return_value': -10, 'start_time': str_to_date("2000-01-01") })] alpha_model_strategy.on_before_market_open() self.ts.position_sizer.size_signals.assert_called_once() args, kwargs = self.ts.position_sizer.size_signals.call_args_list[0] signals, _ = args expected_signals = [Signal(BloombergTicker("ExampleZ00 Comdty"), Exposure.OUT, 1), Signal(BloombergTicker("Example Ticker"), Exposure.OUT, 1)] self.assertCountEqual(signals, expected_signals)
def test_generate_close_orders__no_valid_ticker(self, future_ticker, order_factory, broker): """ There exist a position open in the portfolio for tickers, which belong to the same family as the future_ticker. Currently there is no valid ticker for the FutureTicker, which means the contract corresponding to the open position expired and the position should be closed. """ contract_in_portfolio = Contract("CLG00 Comdty", "FUT", "SIM_EXCHANGE") broker.get_positions.return_value = [ BacktestPositionFactory.create_position(contract_in_portfolio) ] # No valid ticker currently exists for the future ticker future_ticker.get_current_specific_ticker.side_effect = NoValidTickerException( ) future_ticker.belongs_to_family.return_value = True future_ticker.get_expiration_dates.return_value = QFSeries( data=[BloombergTicker("CLG00 Comdty")], index=[self.current_date - RelativeDelta(days=10)]) rolling_orders_generator = FuturesRollingOrdersGenerator( [future_ticker], self.timer, broker, order_factory, self.contract_ticker_mapper) rolling_orders_generator.generate_close_orders() # The order factory should be called exactly once and in should contain all contracts from # contracts_in_portfolio order_factory.target_percent_orders.assert_called_once_with( {contract_in_portfolio: 0}, MarketOrder(), TimeInForce.GTC)
class BuyAndHoldStrategy(object): """ A testing strategy that simply purchases (longs) an asset as soon as it starts and then holds until the completion of a backtest. """ CONTRACT = Contract(symbol="SPY US Equity", security_type='STK', exchange='NASDAQ') TICKER = BloombergTicker("SPY US Equity") def __init__(self, broker: Broker, order_factory: OrderFactory, scheduler: Scheduler): self.order_factory = order_factory self.broker = broker self.invested = False scheduler.subscribe(BeforeMarketOpenEvent, listener=self) def on_before_market_open(self, _: BeforeMarketOpenEvent): self.calculate_signals() def calculate_signals(self): if not self.invested: orders = self.order_factory.percent_orders({self.CONTRACT: 1.0}, MarketOrder(), TimeInForce.GTC) self.broker.place_orders(orders) self.invested = True
def test__adjust_number_of_open_positions_2(self, generate_close_orders): """ Test description: - max number of positions is 1 - portfolio contains position with contract ExampleZ00 Comdty - there is a signal with suggested exposure LONG for ExampleN01 Comdty - Expected output: ExampleN01 Comdty suggested exposure will be unchanged """ self.future_ticker.get_current_specific_ticker.return_value = BloombergTicker( "ExampleN01 Comdty") alpha_model_strategy = AlphaModelStrategy( self.ts, {self.alpha_model: [self.future_ticker]}, use_stop_losses=False, max_open_positions=1) self.alpha_model.get_signal.return_value = Signal( self.future_ticker, Exposure.LONG, 1) self.positions_in_portfolio = [ Mock(spec=BacktestPosition, **{ 'contract.return_value': Contract("ExampleZ00 Comdty", "FUT", "SIM_EXCHANGE"), 'quantity.return_value': -10, 'start_time': str_to_date("2000-01-01") }) ] alpha_model_strategy.on_before_market_open() self.ts.position_sizer.size_signals.assert_called_with( [Signal(self.future_ticker, Exposure.LONG, 1)], False)
def setUpClass(cls): cls.ticker = BloombergTicker('AAPL US Equity') cls.last_price = 110 cls.initial_position = 200 cls.initial_allocation = 0.5 # 50% of our portfolio is invested in AAPL cls.contract = Contract(cls.ticker.ticker, 'STK', 'SIM_EXCHANGE') cls.initial_risk = 0.02 cls.max_target_percentage = 1.5
def test_generate_close_orders__current_ticker_in_portfolio( self, future_ticker, order_factory, broker): """ There exist positions open in the portfolio for tickers, which belong to the same family as the future_ticker and for the current ticker. Test if only the expired contracts will be closed. """ expired_contract = Contract("CLG00 Comdty", "FUT", "SIM_EXCHANGE") current_contract = Contract("CLG01 Comdty", "FUT", "SIM_EXCHANGE") contracts_in_portfolio = [expired_contract, current_contract] broker.get_positions.side_effect = lambda: [ BacktestPositionFactory.create_position(c) for c in contracts_in_portfolio ] # Set current ticker to be different then ticker corresponding to expired_contract future_ticker.get_current_specific_ticker.return_value = BloombergTicker( "CLG01 Comdty") future_ticker.belongs_to_family.return_value = True future_ticker.get_expiration_dates.return_value = QFSeries( data=[ BloombergTicker("CLG00 Comdty"), BloombergTicker("CLG01 Comdty") ], index=[ self.current_date + RelativeDelta(days=1), self.current_date + RelativeDelta(days=5) ]) rolling_orders_generator = FuturesRollingOrdersGenerator( [future_ticker], self.timer, broker, order_factory, self.contract_ticker_mapper) rolling_orders_generator.logger = MagicMock() rolling_orders_generator.generate_close_orders() # The order factory should be called exactly once and in should contain all contracts from # contracts_in_portfolio order_factory.target_percent_orders.assert_called_once_with( {expired_contract: 0}, MarketOrder(), TimeInForce.GTC) # The logger error function should not have been called rolling_orders_generator.logger.error.assert_not_called()
def get_data(): start_date = str_to_date('2017-01-01') end_date = str_to_date('2017-12-31') number_of_trades = 200 contract = Contract("Example Comdty", "STK", "SIM EXCHANGE") trades = [ Trade(start_date, end_date, contract, pnl, 0, 1, pnl / 10000) for pnl in np.random.normal(0, 200, number_of_trades) ] return trades, 1, start_date, end_date
def position(self, account: str, ib_contract: IBContract, position: float, avgCost: float): contract = Contract(ib_contract.symbol, ib_contract.secType, ib_contract.exchange) if not position.is_integer(): self.logger.warning( "Position {} has non-integer quantity = {}".format( contract, position)) position_info = BrokerPosition(contract, int(position), avgCost) self.position_list.append(position_info)
def get_data(): start_date = str_to_date('2017-01-01') end_date = str_to_date('2017-12-31') number_of_trades = 200 contract = Contract("Example Comdty", "STK", "SIM EXCHANGE") percentage_risk = 0.05 risk = 10000000 * percentage_risk trades = [ Trade(start_date, end_date, contract, pnl, 0, 1, risk) for pnl in np.random.normal(0.01, 0.2, number_of_trades) ] return trades, 1, start_date, end_date
def test_generate_close_orders__multiple_future_tickers( self, future_ticker, order_factory, broker): contracts_in_portfolio = [ Contract("CLG00 Comdty", "FUT", "SIM_EXCHANGE"), Contract("CLG01 Comdty", "FUT", "SIM_EXCHANGE") ] specific_tickers = [ BloombergTicker("CLG00 Comdty"), BloombergTicker("CLG01 Comdty") ] contracts_in_portfolio_2 = [ Contract("CTG00 Comdty", "FUT", "SIM_EXCHANGE"), Contract("CTG01 Comdty", "FUT", "SIM_EXCHANGE") ] specific_tickers_2 = [ BloombergTicker("CTG00 Comdty"), BloombergTicker("CTG01 Comdty") ] broker.get_positions.side_effect = lambda: [ BacktestPositionFactory.create_position(c) for c in contracts_in_portfolio + contracts_in_portfolio_2 ] # Generate the FuturesRollingOrdersGenerator for two different Future Tickers future_ticker.get_current_specific_ticker.return_value = BloombergTicker( "CLG01 Comdty") future_ticker.belongs_to_family.side_effect = lambda t: t in specific_tickers future_ticker.get_expiration_dates.return_value = QFSeries( data=specific_tickers, index=[ self.current_date - RelativeDelta(days=10), self.current_date + RelativeDelta(days=5) ]) future_ticker2 = MagicMock() future_ticker2.get_current_specific_ticker.return_value = BloombergTicker( "CTG01 Comdty") future_ticker2.belongs_to_family.side_effect = lambda t: t in specific_tickers_2 future_ticker2.get_expiration_dates.return_value = QFSeries( data=specific_tickers_2, index=[ self.current_date - RelativeDelta(days=10), self.current_date + RelativeDelta(days=5) ]) rolling_orders_generator = FuturesRollingOrdersGenerator( [future_ticker, future_ticker2], self.timer, broker, order_factory, self.contract_ticker_mapper) rolling_orders_generator.logger = MagicMock() rolling_orders_generator.generate_close_orders() order_factory.target_percent_orders.assert_called_once_with( { Contract("CLG00 Comdty", "FUT", "SIM_EXCHANGE"): 0, Contract("CTG00 Comdty", "FUT", "SIM_EXCHANGE"): 0 }, MarketOrder(), TimeInForce.GTC)
def _parse_transactions_file( self, path_to_transactions_file: str) -> List[Transaction]: """ Parse the Transactions csv file created by the Monitor and generate a list of transactions objects. """ transactions_df = pd.read_csv(path_to_transactions_file) transactions = [ Transaction(time=pd.to_datetime(row.loc["Timestamp"]), contract=Contract( symbol=row.loc["Contract symbol"], security_type=row.loc["Security type"], exchange=row.loc["Exchange"], contract_size=row.loc["Contract size"]), quantity=row.loc["Quantity"], price=row.loc["Price"], commission=row.loc["Commission"]) for _, row in transactions_df.iterrows() ] return transactions
def test_generate_close_orders__no_orders_close(self, future_ticker, order_factory, broker): """ Test if the FuturesRollingOrdersGenerator does not close positions for contracts which are still valid. """ contract_in_portfolio = Contract("CLG01 Comdty", "FUT", "SIM_EXCHANGE") broker.get_positions.return_value = [ BacktestPositionFactory.create_position(contract_in_portfolio) ] future_ticker.get_current_specific_ticker.return_value = BloombergTicker( "CLG01 Comdty") rolling_orders_generator = FuturesRollingOrdersGenerator( [future_ticker], self.timer, broker, order_factory, self.contract_ticker_mapper) rolling_orders_generator.generate_close_orders() order_factory.target_percent_orders.assert_not_called()
def main(): start_date = str_to_date('2018-01-01') initial_value = 1000 portfolio = Portfolio(None, initial_value, None, None) backtest_result = BacktestResult(portfolio, 'Monitor Test', start_date=start_date) backtest_result.start_time = start_date settings = container.resolve(Settings) # type: Settings pdf_exporter = container.resolve(PDFExporter) # type: PDFExporter xlsx_exporter = container.resolve(ExcelExporter) # type: ExcelExporter monitor = BacktestMonitor(backtest_result, settings, pdf_exporter, xlsx_exporter) # put first point # noinspection PyProtectedMember portfolio.dates.append(start_date) # noinspection PyProtectedMember portfolio.portfolio_values.append(initial_value) # create an Transaction timestamp = str_to_date("2010-01-01") contract = Contract("MSFT US Equity", security_type="STK", exchange="NYSE") quantity = 13 price = 100.5 commission = 1.2 transaction = Transaction(timestamp, contract, quantity, price, commission) for i in range(50): date = start_date + timedelta(days=i) # noinspection PyProtectedMember past_value = portfolio.portfolio_values[-1] rand = randint(0, 100) - 50 # noinspection PyProtectedMember portfolio.dates.append(date) # noinspection PyProtectedMember portfolio.portfolio_values.append(past_value + rand) monitor.end_of_day_update(date) monitor.record_transaction(transaction) time.sleep(0.1) monitor.end_of_trading_update()
def setUp(self): self.scheduling_time_delay = 1 start_date = str_to_date("2018-02-04") before_close = start_date + MarketCloseEvent.trigger_time( ) - RelativeDelta(minutes=self.scheduling_time_delay) self.timer = SettableTimer(initial_time=before_close) contracts_to_tickers_mapper = SimulatedBloombergContractTickerMapper() msft_contract = Contract("MSFT US Equity", security_type='STK', exchange='TEST') self.msft_ticker = contracts_to_tickers_mapper.contract_to_ticker( msft_contract) self.data_handler = Mock(spec=DataHandler) self.scheduler = Mock(spec=Scheduler) self.commission_model = FixedCommissionModel(commission=0.0) self.monitor = Mock(spec=AbstractMonitor) self.portfolio = Mock(spec=Portfolio) slippage_model = PriceBasedSlippage(0.0, self.data_handler, contracts_to_tickers_mapper) self.exec_handler = SimulatedExecutionHandler( self.data_handler, self.timer, self.scheduler, self.monitor, self.commission_model, contracts_to_tickers_mapper, self.portfolio, slippage_model, RelativeDelta(minutes=self.scheduling_time_delay)) self.order_1 = Order(msft_contract, quantity=10, execution_style=MarketOrder(), time_in_force=TimeInForce.OPG) self.order_2 = Order(msft_contract, quantity=-5, execution_style=MarketOrder(), time_in_force=TimeInForce.OPG) self.order_3 = Order(msft_contract, quantity=-7, execution_style=MarketOrder(), time_in_force=TimeInForce.OPG) self.order_4 = Order(msft_contract, quantity=4, execution_style=MarketOnCloseOrder(), time_in_force=TimeInForce.DAY)
def openOrder(self, orderId: OrderId, ib_contract: IBContract, ib_order: IBOrder, orderState: OrderState): contract = Contract(ib_contract.symbol, ib_contract.secType, ib_contract.exchange) if ib_order.orderType.upper() == 'STP': execution_style = StopOrder(ib_order.auxPrice) elif ib_order.orderType.upper() == 'MKT': execution_style = MarketOrder() else: error_message = "Order Type is not supported: {}".format( ib_order.orderType) self.logger.error(error_message) raise ValueError(error_message) if ib_order.action.upper() == 'SELL': quantity = -ib_order.totalQuantity elif ib_order.action.upper() == 'BUY': quantity = ib_order.totalQuantity else: error_message = "Order Action is not supported: {}".format( ib_order.action) self.logger.error(error_message) raise ValueError(error_message) if ib_order.tif.upper() == 'DAY': time_in_force = TimeInForce.DAY elif ib_order.tif.upper() == 'GTC': time_in_force = TimeInForce.GTC elif ib_order.tif.upper() == 'OPG': time_in_force = TimeInForce.OPG else: error_message = "Time in Force is not supported: {}".format( ib_order.tif) self.logger.error(error_message) raise ValueError(error_message) order = Order(contract=contract, quantity=quantity, execution_style=execution_style, time_in_force=time_in_force, order_state=orderState.status) order.id = int(orderId) self.order_list.append(order)
def setUpClass(cls): cls.contract = Contract('AAPL US Equity', 'STK', 'NASDAQ') cls.ticker = BloombergTicker('AAPL US Equity') cls.current_portfolio_value = 1000.0 cls.share_price = 10.0 position = Mock(spec=Position) position.quantity.return_value = 10 position.contract.return_value = cls.contract broker = Mock(spec=Broker) broker.get_portfolio_value.return_value = cls.current_portfolio_value broker.get_positions.return_value = [position] data_handler = Mock(spec=DataHandler) data_handler.get_last_available_price.return_value = QFSeries([cls.share_price], index=[cls.ticker]) cls.order_factory = OrderFactory(broker, data_handler, SimulatedBloombergContractTickerMapper())
def setUp(self): self.start_date = str_to_date("2018-02-04") self.msft_contract = Contract(self.MSFT_TICKER_STR, security_type='SEK', exchange='TEST') self.msft_ticker = BloombergTicker(self.MSFT_TICKER_STR) self.contracts_to_tickers_mapper = DummyBloombergContractTickerMapper() timer = SettableTimer(initial_time=self.start_date) self.data_handler = mock(strict=True) self.scheduler = mock() self.commission_model = FixedCommissionModel(commission=0.0) self.monitor = _MonitorMock() self.spied_monitor = spy(self.monitor) self.portfolio = mock() slippage_model = PriceBasedSlippage(0.0) self.exec_hanlder = SimulatedExecutionHandler( self.data_handler, timer, self.scheduler, self.spied_monitor, self.commission_model, self.contracts_to_tickers_mapper, self.portfolio, slippage_model) self._set_current_msft_price(100.0) self.stop_loss_order_1 = Order(self.msft_contract, quantity=-1, execution_style=StopOrder(95.0), time_in_force=TimeInForce.GTC) self.stop_loss_order_2 = Order(self.msft_contract, quantity=-1, execution_style=StopOrder(90.0), time_in_force=TimeInForce.GTC) self.stop_loss_order_3 = Order(self.msft_contract, quantity=-1, execution_style=StopOrder(50.0), time_in_force=TimeInForce.DAY) self.exec_hanlder.accept_orders([ self.stop_loss_order_1, self.stop_loss_order_2, self.stop_loss_order_3 ])
def setUpClass(cls): cls.contract = Contract('AAPL US Equity', 'STK', 'NASDAQ') cls.ticker = BloombergTicker('AAPL US Equity') cls.current_portfolio_value = 1000.0 cls.share_price = 10.0 position = mock(strict=True) when(position).quantity().thenReturn(10) when(position).contract().thenReturn(cls.contract) broker = mock(strict=True) when(broker).get_portfolio_value().thenReturn( cls.current_portfolio_value) when(broker).get_positions().thenReturn([position]) data_handler = mock(strict=True) when(data_handler).get_last_available_price([cls.ticker]).thenReturn( pd.Series([cls.share_price], index=[cls.ticker])) cls.order_factory = OrderFactory(broker, data_handler, DummyBloombergContractTickerMapper())
def setUpClass(cls): cls.ticker = BloombergTicker('AAPL US Equity') cls.last_price = 110 cls.initial_position = 200 cls.initial_allocation = 0.5 # 50% of our portfolio is invested in AAPL cls.contract = Contract(cls.ticker.ticker, 'STK', 'SIM_EXCHANGE') cls.initial_risk = 0.02 position = BrokerPosition(cls.contract, cls.initial_position, 25) broker = mock(strict=True) when(broker).get_positions().thenReturn([position]) data_handler = mock(strict=True) when(data_handler).get_last_available_price(cls.ticker).thenReturn(110) order_factory = _OrderFactoryMock( cls.initial_position, cls.initial_allocation) # type: OrderFactory contract_ticker_mapper = DummyBloombergContractTickerMapper() cls.simple_position_sizer = SimplePositionSizer( broker, data_handler, order_factory, contract_ticker_mapper) cls.initial_risk_position_sizer = InitialRiskPositionSizer( broker, data_handler, order_factory, contract_ticker_mapper, cls.initial_risk)
def ticker_to_contract(self, ticker: Ticker) -> Contract: return Contract(symbol=ticker.ticker, security_type='STK', exchange='SIM_EXCHANGE')
def setUpClass(cls): cls.contract = Contract('AAPL US Equity', security_type='STK', exchange='SIM_EXCHANGE') cls.start_time = str_to_date('2019-01-01') cls.time = str_to_date('2020-01-01')
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from qf_lib.backtesting.contract.contract import Contract from qf_lib.backtesting.portfolio.transaction import Transaction from qf_lib.common.utils.dateutils.string_to_date import str_to_date time = str_to_date("2010-01-01") ticker = Contract("MSFT US Equity", security_type='SEK', exchange='TEST_XCHANGE') quantity = 13 price = 100.5 commission = 1.2 def main(): transaction = Transaction(time, ticker, quantity, price, commission) print(transaction) if __name__ == '__main__': main()