def setUpClass(cls) -> None: cls.end_date = str_to_date('2015-10-08') cls.start_date = cls.end_date - RelativeDelta(years=2) cls.timer = SettableTimer(cls.end_date) cls.frequency = Frequency.DAILY cls.TICKER_1 = BloombergFutureTicker("Cotton", "CT{} Comdty", 1, 3) cls.TICKER_2 = BloombergFutureTicker("Corn", 'C {} Comdty', 1, 5)
def test_contract_ticker_mapping_multiple_tickers_matching_contract(self): """ Test contract to ticker mapping in case if many tickers correspond to the same contract. """ mapping = { BloombergFutureTicker('Copper1', 'HG{} Comdty', 1, 1, 250): IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD"), BloombergFutureTicker('Copper2', 'HG{} Comdty', 1, 2, 250): IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD"), } with self.assertRaises(AssertionError): IBContractTickerMapper(mapping, self.data_provider)
def setUpClass(cls): cls.start_date = str_to_date('2008-10-08') cls.end_date = str_to_date('2018-12-20') cls.timer = SettableTimer() cls.timer.set_current_time(cls.end_date) cls.frequency = Frequency.DAILY cls.ticker_1 = BloombergFutureTicker("Euroswiss", "ES{} Index", 1, 3, 100, "HMUZ") cls.ticker_2 = BloombergFutureTicker("Corn", "C {} Comdty", 1, 3, 100, "HKNUZ") MarketCloseEvent.set_trigger_time({"hour": 20, "minute": 00, "second": 0, "microsecond": 0})
def test_get_ticker_1st_contract_6_days_before_exp_date(self): exp_dates_to_ticker_str = { str_to_date("2016-12-16"): BloombergTicker('ESZ16 Index'), str_to_date("2017-03-17"): BloombergTicker('ESH17 Index') } future_ticker = BloombergFutureTicker("Euroswiss", "ES{} Index", 1, 6, 100, "HMUZ") future_ticker.initialize_data_provider(self.timer, self.data_provider) # Check dates before 2016-12-16 self.timer.set_current_time(str_to_date('2016-11-11')) self.assertEqual(future_ticker.get_current_specific_ticker(), exp_dates_to_ticker_str[str_to_date("2016-12-16")]) self.timer.set_current_time(str_to_date('2016-12-10')) self.assertEqual(future_ticker.get_current_specific_ticker(), exp_dates_to_ticker_str[str_to_date("2016-12-16")]) self.timer.set_current_time( str_to_date('2016-12-10 23:55:00.0', DateFormat.FULL_ISO)) self.assertEqual(future_ticker.get_current_specific_ticker(), exp_dates_to_ticker_str[str_to_date("2016-12-16")]) self.timer.set_current_time(str_to_date('2016-12-16')) self.assertEqual(future_ticker.get_current_specific_ticker(), exp_dates_to_ticker_str[str_to_date("2017-03-17")])
def test_contract_ticker_mapping_many_future_tickers(self): """ Test futures contract to ticker mapping in case if many future tickers correspond to the given ticker. """ mapping = { BloombergFutureTicker('Copper', 'HG{} Comdty', 1, 1, 250): IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD"), BloombergFutureTicker('Copper', 'HG{} Comdty', 1, 17, 250): IBContract("HG", SecurityType.FUTURE, "NYMEX", "250", "USD"), } contract_ticker_mapper = IBContractTickerMapper( mapping, self.data_provider) with self.assertRaises(ValueError): ticker = BloombergTicker("HGH20 Comdty", SecurityType.FUTURE, 250) contract_ticker_mapper.ticker_to_contract(ticker)
def test_get_ticker_2nd_contract_1_day_before_exp_date(self): exp_dates_to_ticker_str = { str_to_date("2016-06-30"): BloombergTicker('C N16 Comdty'), str_to_date("2016-08-31"): BloombergTicker('C U16 Comdty'), str_to_date("2016-11-30"): BloombergTicker('C Z16 Comdty') } future_ticker = BloombergFutureTicker("Corn", "C {} Comdty", 2, 1, 100, "HKNUZ") future_ticker.initialize_data_provider(self.timer, self.data_provider) self.timer.set_current_time(str_to_date('2016-06-03')) self.assertEqual(future_ticker.get_current_specific_ticker(), exp_dates_to_ticker_str[str_to_date("2016-08-31")]) self.timer.set_current_time(str_to_date('2016-06-29')) self.assertEqual(future_ticker.get_current_specific_ticker(), exp_dates_to_ticker_str[str_to_date("2016-08-31")]) self.timer.set_current_time( str_to_date('2016-06-29 23:59:59.0', DateFormat.FULL_ISO)) self.assertEqual(future_ticker.get_current_specific_ticker(), exp_dates_to_ticker_str[str_to_date("2016-08-31")]) self.timer.set_current_time(str_to_date('2016-06-30')) self.assertEqual(future_ticker.get_current_specific_ticker(), exp_dates_to_ticker_str[str_to_date("2016-11-30")])
def run_strategy(data_provider: DataProvider) -> Tuple[float, str]: """ Returns the strategy end result and checksum of the preloaded data. """ model_tickers = [BloombergFutureTicker("Corn", "C {} Comdty", 1, 10, 1)] start_date = str_to_date('2003-05-30') end_date = str_to_date('2009-01-01') initial_risk = 0.006 # ----- build trading session ----- # session_builder = container.resolve(BacktestTradingSessionBuilder) # type: BacktestTradingSessionBuilder session_builder.set_backtest_name('Simple Futures Strategy') session_builder.set_position_sizer(InitialRiskPositionSizer, initial_risk=initial_risk) session_builder.set_frequency(Frequency.DAILY) session_builder.set_data_provider(data_provider) session_builder.set_monitor_settings(BacktestMonitorSettings.no_stats()) ts = session_builder.build(start_date, end_date) # ----- build models ----- # model = SimpleFuturesModel(fast_time_period=50, slow_time_period=100, risk_estimation_factor=3, data_handler=ts.data_handler) model_tickers_dict = {model: model_tickers} # ----- start trading ----- # AlphaModelStrategy(ts, model_tickers_dict, use_stop_losses=False) ts.use_data_preloading(model_tickers) print(ts.get_preloaded_data_checksum()) ts.start_trading() data_checksum = ts.get_preloaded_data_checksum() actual_end_value = ts.portfolio.portfolio_eod_series()[-1] return actual_end_value, data_checksum
def test_future_ticker_to_contract_mapping(self): """ Test mapping of future tickers onto IB contracts. """ mapping = { BloombergFutureTicker('Copper', 'HG{} Comdty', 1, 1, 250): IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD"), } contract_ticker_mapper = IBContractTickerMapper( mapping, self.data_provider) # Map a specific ticker to contract ticker = BloombergTicker("HGH20 Comdty", SecurityType.FUTURE, 250) actual_contract = contract_ticker_mapper.ticker_to_contract(ticker) expected_contract = IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD", str_to_date("2020-03-20")) self.assertEqual(actual_contract, expected_contract) # Map a future ticker to contract future_ticker = Mock(spec=BloombergFutureTicker) future_ticker.get_current_specific_ticker.return_value = BloombergTicker( "HGN20 Comdty", SecurityType.FUTURE, 250) actual_contract = contract_ticker_mapper.ticker_to_contract( future_ticker) expected_contract = IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD", str_to_date("2020-06-20")) self.assertEqual(actual_contract, expected_contract)
def test_duplicate_future_tickers(self): future_ticker_1 = BloombergFutureTicker("Copper", "HG{} Comdty", 1, 4) future_ticker_2 = BloombergFutureTicker("Example", "Example{} Comdty", 1, 4) bbg_ib_symbols_mapping = { future_ticker_1: IBContract("EXAMPLE", SecurityType.FUTURE, "DIFFERENT_EXCHANGE", "25000"), future_ticker_2: IBContract("EXAMPLE", SecurityType.FUTURE, "EXAMPLE_EXCHANGE", "25000"), } with self.assertRaises(Exception): IBContractTickerMapper(bbg_ib_symbols_mapping, self.data_provider)
def setUpClass(cls): cls.frequency = Frequency.DAILY cls.tickers = [ BloombergFutureTicker("Cotton", "CTF0 Comdty", 1, 3), BloombergFutureTicker("Corn", 'C {} Comdty', 1, 5, 50, "HMUZ") ] timer.set_current_time(str_to_date('2017-12-20')) for ticker in cls.tickers: ticker.initialize_data_provider(timer, bbg_provider) cls.start_date = str_to_date('2015-10-08') cls.end_date = str_to_date('2017-12-20') MarketCloseEvent.set_trigger_time({ "hour": 20, "minute": 00, "second": 0, "microsecond": 0 })
def test_invalid_contract_to_specific_future_ticker_mapping(self): """ Test futures contract to ticker mapping in case if the last trade date is invalid. """ mapping = { BloombergFutureTicker('Copper', 'HG{} Comdty', 1, 1, 250): IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD"), } contract_ticker_mapper = IBContractTickerMapper( mapping, self.data_provider) contract = IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD", str_to_date("2020-06-25")) with self.assertRaises(ValueError): contract_ticker_mapper.contract_to_ticker(contract)
def test_contract_to_specific_future_ticker_mapping(self): mapping = { BloombergFutureTicker('Copper', 'HG{} Comdty', 1, 1, 250): IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD"), } contract_ticker_mapper = IBContractTickerMapper( mapping, self.data_provider) contract = IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD", str_to_date("2020-06-20")) actual_ticker = contract_ticker_mapper.contract_to_ticker(contract) expected_ticker = BloombergTicker("HGN20 Comdty", SecurityType.FUTURE, 250) self.assertEqual(actual_ticker, expected_ticker)
def setUpClass(cls): cls.tickers = [ BloombergTicker("MSFT US Equity"), BloombergTicker("AUDUSD Curncy"), BloombergFutureTicker("Heating Oil", "HO{} Comdty", 1, 1, 100), ] cls.prices_start_date = str_to_date("2020-01-02") cls.test_start_date = str_to_date("2020-01-03") cls.test_end_date = str_to_date("2020-01-09") cls.fields = [ PriceField.Open, PriceField.High, PriceField.Low, PriceField.Close ] cls.frequency = Frequency.DAILY
def test_no_data_provider(self): fut_ticker = BloombergFutureTicker("Copper", "HG{} Comdty", 1, 4) bbg_ib_symbols_mapping = { fut_ticker: IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000") } with self.assertRaises(ValueError): contract_ticker_mapper = IBContractTickerMapper( bbg_ib_symbols_mapping, data_provider=None) contract_ticker_mapper.contract_to_ticker( IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", last_trade_date=datetime(2021, 9, 9)))
def test_duplicate_future_and_equity_tickers(self): future_ticker_1 = BloombergFutureTicker("Copper", "HG{} Comdty", 1, 4) bbg_ib_symbols_mapping = { future_ticker_1: IBContract("EXAMPLE", SecurityType.FUTURE, "DIFFERENT_EXCHANGE", "25000"), BloombergTicker("Example Index"): IBContract("EXAMPLE", SecurityType.STOCK, "EXAMPLE_EXCHANGE"), } contract_ticker_mapper = IBContractTickerMapper( bbg_ib_symbols_mapping, self.data_provider) contract = IBContract("EXAMPLE", SecurityType.STOCK, "EXAMPLE_EXCHANGE") ticker = contract_ticker_mapper.contract_to_ticker(contract) self.assertEqual(ticker.as_string(), "Example Index")
def test_get_signals__one_future_ticker(self, ticker_mock): fut_ticker_1 = BloombergFutureTicker("Ticker name", "family id", 1, 1) ticker_mock.return_value = "Specific ticker" number_of_days = 30 start_date = str_to_date("2000-01-01") rolling_date = start_date + RelativeDelta(days=number_of_days - 1) signals_register = SignalsRegister() for date in date_range(start_date, rolling_date, freq="D"): signals_register.save_signals([Signal(fut_ticker_1, Exposure.LONG, 0.0)], date) signals_df = signals_register.get_signals() self.assertEqual(type(signals_df), QFDataFrame) self.assertEqual(signals_df.shape, (number_of_days, 1))
def map_future_ticker_to_contract(): mapping = { BloombergFutureTicker('Copper', 'HG{} Comdty', 1, 1, 250): IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD"), BloombergTicker("PAH20 Comdty", SecurityType.FUTURE, 100): IBContract("PA", SecurityType.FUTURE, "NYMEX", "100", "", str_to_date("2020-03-27")) } data_provider = container.resolve(BloombergDataProvider) contract_ticker_mapper = IBContractTickerMapper(mapping, data_provider) current_time = str_to_date("2020-12-01") for future_ticker in mapping.keys(): if isinstance(future_ticker, BloombergFutureTicker): future_ticker.initialize_data_provider(SettableTimer(current_time), data_provider) print("\nMapping PAH20 Comdty ticker to IB contract") ticker = BloombergTicker("PAH20 Comdty", SecurityType.FUTURE, 100) contract = contract_ticker_mapper.ticker_to_contract(ticker) print(f"Ticker mapped onto the following contract: {contract}") print("\nMapping IBContract onto ticker") contract = IBContract("PA", SecurityType.FUTURE, "NYMEX", "100", "", str_to_date("2020-03-27")) ticker = contract_ticker_mapper.contract_to_ticker(contract) print(f"Contract mapped onto the following ticker: {ticker}") print( "\nMapping HGH20 Comdty ticker - Copper, March 2020 futures contracts") ticker = BloombergTicker("HGH20 Comdty", SecurityType.FUTURE, 250) contract = contract_ticker_mapper.ticker_to_contract(ticker) print(f"Ticker mapped onto the following contract: {contract}") print("\nMapping IBContract onto ticker") contract = IBContract("HG", SecurityType.FUTURE, "NYMEX", "25000", "USD", str_to_date("2021-01-27")) ticker = contract_ticker_mapper.contract_to_ticker(contract) print(f"Contract mapped onto the following ticker: {ticker}")
def _mock_data_provider(self): dates_index = pd.bdate_range(start=self.prices_start_date, end=self.test_end_date) fields_number = len(self.fields) tickers = [ BloombergTicker("MSFT US Equity"), BloombergTicker("AUDUSD Curncy"), BloombergTicker( "HOZ9 Comdty"), # Mock three contracts for Heating Oil BloombergTicker("HOF0 Comdty"), BloombergTicker("HOG0 Comdty"), ] # Mock price data array values = [ [ # 02-01-2020 # MSFT US Equity, AUDUSD Curncy, Heating Oil (3 contracts) prices [90], [90], [90], [90], [90] ], [ # 03-01-2020 [95], [95], [85], [100], [85] ], [ # 06-01-2020 [110], [100], [90], [100], [90] # The Heating Oil contract will create an open position ], [ # 07-01-2020 [90], [110], [95], [np.nan], [ 95 ] # Rolling for Heating Oil occurs, new Heating Oil contract is bought ], [ # 08-01-2020 [80], [120], [100], [100], [ 100 ] # Previous Heating Oil is sold (there was no price on the 7th) ], [ # 09-01-2020 [80], [120], [100], [100], [100] ], ] # Open, High, Low and Close prices are equal every day values = [[price * fields_number for price in day_prices] for day_prices in values] mocked_prices = QFDataArray.create(dates_index, tickers, self.fields, data=values) # Mock expiration dates exp_dates = { BloombergFutureTicker("Heating Oil", "HO{} Comdty", 1, 1, 100): QFDataFrame(data={ ExpirationDateField.FirstNotice: [ str_to_date("2019-12-01"), str_to_date("2020-01-07"), str_to_date("2020-02-03") ], ExpirationDateField.LastTradeableDate: [ str_to_date("2019-12-01"), str_to_date("2020-01-07"), str_to_date("2020-02-03") ], }, index=[ BloombergTicker("HOZ9 Comdty"), BloombergTicker("HOF0 Comdty"), BloombergTicker("HOG0 Comdty") ]) } return PresetDataProvider(data=mocked_prices, exp_dates=exp_dates, start_date=str_to_date("2019-12-01"), end_date=self.test_end_date, frequency=self.frequency)