instruction
stringclasses
1 value
input
stringlengths
81
758
output
stringlengths
420
23.9k
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Basic template algorithm simply initializes the date range and cash. This is a skeleton framework you can use for designing an algorithm.
```python from AlgorithmImports import * class BasicTemplateAlgorithm(QCAlgorithm): '''Basic template algorithm simply initializes the date range and cash''' def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2013,10, 7) #Set Start Date self.set_end_date(2013,10,11) #Set End Date self.set_cash(100000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data self.add_equity("SPY", Resolution.MINUTE) self.debug("numpy test >>> print numpy.pi: " + str(np.pi)) def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' if not self.portfolio.invested: self.set_holdings("SPY", 1) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests Out of The Money (OTM) future option expiry for short calls. We expect 2 orders from the algorithm, which are: * Initial entry, sell ES Call Option (expiring OTM) - Profit the option premium, since the option was not assigned. * Liquidation of ES call OTM contract on the last trade date Additionally, we test delistings for future options and assert that our portfolio holdings reflect the orders the algorithm has submitted.
```python from AlgorithmImports import * class FutureOptionShortCallOTMExpiryRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2020, 1, 5) self.set_end_date(2020, 6, 30) self.es19m20 = self.add_future_contract( Symbol.create_future( Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 6, 19)), Resolution.MINUTE).symbol # Select a future option expiring ITM, and adds it to the algorithm. self.es_option = self.add_future_option_contract( list( sorted( [x for x in self.option_chain(self.es19m20) if x.id.strike_price >= 3400.0 and x.id.option_right == OptionRight.CALL], key=lambda x: x.id.strike_price ) )[0], Resolution.MINUTE).symbol self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3400.0, datetime(2020, 6, 19)) if self.es_option != self.expected_contract: raise AssertionError(f"Contract {self.expected_contract} was not found in the chain") self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order) def scheduled_market_order(self): self.market_order(self.es_option, -1) def on_data(self, data: Slice): # Assert delistings, so that we can make sure that we receive the delisting warnings at # the expected time. These assertions detect bug #4872 for delisting in data.delistings.values(): if delisting.type == DelistingType.WARNING: if delisting.time != datetime(2020, 6, 19): raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}") if delisting.type == DelistingType.DELISTED: if delisting.time != datetime(2020, 6, 20): raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}") def on_order_event(self, order_event: OrderEvent): if order_event.status != OrderStatus.FILLED: # There's lots of noise with OnOrderEvent, but we're only interested in fills. return if not self.securities.contains_key(order_event.symbol): raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}") security = self.securities[order_event.symbol] if security.symbol == self.es19m20: raise AssertionError(f"Expected no order events for underlying Symbol {security.symbol}") if security.symbol == self.expected_contract: self.assert_future_option_contract_order(order_event, security) else: raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}") self.log(f"{order_event}") def assert_future_option_contract_order(self, order_event: OrderEvent, option_contract: Security): if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1: raise AssertionError(f"No holdings were created for option contract {option_contract.symbol}") if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0: raise AssertionError("Expected no options holdings after closing position") if order_event.is_assignment: raise AssertionError(f"Assignment was not expected for {order_event.symbol}") def on_end_of_algorithm(self): if self.portfolio.invested: raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm to assert the behavior of <see cref="RsiAlphaModel"/>.
```python from AlgorithmImports import * from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm from Alphas.RsiAlphaModel import RsiAlphaModel class RsiAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm): def initialize(self): super().initialize() self.set_alpha(RsiAlphaModel()) def on_end_of_algorithm(self): # We have removed all securities from the universe. The Alpha Model should remove the consolidator consolidator_count = sum([s.consolidators.count for s in self.subscription_manager.subscriptions]) if consolidator_count > 0: raise AssertionError(f"The number of consolidators should be zero. Actual: {consolidator_count}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This algorithm showcases some features of the IObjectStore feature.
```python from AlgorithmImports import * from io import StringIO class ObjectStoreExampleAlgorithm(QCAlgorithm): '''This algorithm showcases some features of the IObjectStore feature. One use case is to make consecutive backtests run faster by caching the results of potentially time consuming operations. In this example, we save the results of a history call. This pattern can be equally applied to a machine learning model being trained and then saving the model weights in the object store. ''' spy_close_object_store_key = "spy_close" spy_close_history = RollingWindow(252) spy_close_ema10_history = RollingWindow(252) spy_close_ema50_history = RollingWindow(252) def initialize(self): self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.SPY = self.add_equity("SPY", Resolution.MINUTE).symbol self.spy_close = self.identity(self.SPY, Resolution.DAILY) self.spy_close_ema10 = IndicatorExtensions.ema(self.spy_close, 10) self.spy_close_ema50 = IndicatorExtensions.ema(self.spy_close, 50) # track last year of close and EMA10/EMA50 self.spy_close.updated += lambda _, args: self.spy_close_history.add(args) self.spy_close_ema10.updated += lambda _, args: self.spy_close_ema10_history.add(args) self.spy_close_ema50.updated += lambda _, args: self.spy_close_ema50_history.add(args) if self.object_store.contains_key(self.spy_close_object_store_key): # our object store has our historical data saved, read the data # and push it through the indicators to warm everything up values = self.object_store.read(self.spy_close_object_store_key) self.debug(f'{self.spy_close_object_store_key} key exists in object store.') history = pd.read_csv(StringIO(values), header=None, index_col=0, squeeze=True) history.index = pd.to_datetime(history.index) for time, close in history.items(): self.spy_close.update(time, close) else: self.debug(f'{self.spy_close_object_store_key} key does not exist in object store. Fetching history...') # if our object store doesn't have our data, fetch the history to initialize # we're pulling the last year's worth of SPY daily trade bars to fee into our indicators history = self.history(self.SPY, timedelta(365), Resolution.DAILY).close.unstack(0).squeeze() for time, close in history.items(): self.spy_close.update(time, close) # save our warm up data so next time we don't need to issue the history request self.object_store.save(self.spy_close_object_store_key, '\n'.join(reversed([f'{x.end_time},{x.value}' for x in self.spy_close_history]))) # Can also use ObjectStore.save_bytes(key, byte[]) # and to read ObjectStore.read_bytes(key) => byte[] # we can also get a file path for our data. some ML libraries require model # weights to be loaded directly from a file path. The object store can provide # a file path for any key by: ObjectStore.get_file_path(key) => string (file path) def on_data(self, slice): close = self.spy_close ema10 = self.spy_close_ema10 ema50 = self.spy_close_ema50 if ema10 > close and ema10 > ema50: self.set_holdings(self.SPY, 1) elif ema10 < close and ema10 < ema50: self.set_holdings(self.SPY, -1) elif ema10 < ema50 and self.portfolio[self.SPY].is_long: self.liquidate(self.SPY) elif ema10 > ema50 and self.portfolio[self.SPY].is_short: self.liquidate(self.SPY) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression test for consistency of hour data over a reverse split event in US equities.
```python from AlgorithmImports import * class HourSplitRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2014, 6, 6) self.set_end_date(2014, 6, 9) self.set_cash(100000) self.set_benchmark(lambda x: 0) self._symbol = self.add_equity("AAPL", Resolution.HOUR).symbol def on_data(self, slice): if slice.bars.count == 0: return if (not self.portfolio.invested) and self.time.date() == self.end_date.date(): self.buy(self._symbol, 1) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm to test zeroed benchmark through BrokerageModel override
```python from AlgorithmImports import * class ZeroedBenchmarkRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_cash(100000) self.set_start_date(2013,10,7) self.set_end_date(2013,10,8) # Add Equity self.add_equity("SPY", Resolution.HOUR) # Use our Test Brokerage Model with zerod default benchmark self.set_brokerage_model(TestBrokerageModel()) def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' if not self.portfolio.invested: self.set_holdings("SPY", 1) class TestBrokerageModel(DefaultBrokerageModel): def get_benchmark(self, securities): return FuncBenchmark(self.func) def func(self, datetime): return 0 ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This algorithm sends a list of portfolio targets from algorithm's Portfolio to Collective2 API every time the ema indicators crosses between themselves.
```python from AlgorithmImports import * class Collective2PortfolioSignalExportDemonstrationAlgorithm(QCAlgorithm): def initialize(self): ''' Initialize the date and add all equity symbols present in list _symbols ''' self.set_start_date(2013, 10, 7) #Set Start Date self.set_end_date(2013, 10, 11) #Set End Date self.set_cash(100000) #Set Strategy Cash # Symbols accepted by Collective2. Collective2 accepts stock, future, forex and US stock option symbols self.add_equity("GOOG") self._symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA, None, None), Symbol.create("EURUSD", SecurityType.FOREX, Market.OANDA, None, None), Symbol.create_future("ES", Market.CME, datetime(2023, 12, 15), None), Symbol.create_option("GOOG", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 130, datetime(2023, 9, 1)) ] for item in self._symbols: self.add_security(item) self.fast = self.ema("SPY", 10) self.slow = self.ema("SPY", 100) # Initialize these flags, to check when the ema indicators crosses between themselves self.ema_fast_is_not_set = True self.ema_fast_was_above = False # Collective2 APIv4 KEY: This value is provided by Collective2 in their webpage in your account section (See https://collective2.com/account-info) # See API documentation at https://trade.collective2.com/c2-api self.collective2_apikey = "YOUR APIV4 KEY" # Collective2 System ID: This value is found beside the system's name (strategy's name) on the main system page self.collective2_system_id = 0 # Disable automatic exports as we manually set them self.signal_export.automatic_export_time_span = None # Set Collective2 signal export provider self.signal_export.add_signal_export_provider(Collective2SignalExport(self.collective2_apikey, self.collective2_system_id)) self.first_call = True self.set_warm_up(100) def on_data(self, data): ''' Reduce the quantity of holdings for one security and increase the holdings to the another one when the EMA's indicators crosses between themselves, then send a signal to Collective2 API ''' if self.is_warming_up: return # Place an order as soon as possible to send a signal. if self.first_call: self.set_holdings("SPY", 0.1) self.signal_export.set_target_portfolio_from_portfolio() self.first_call = False fast = self.fast.current.value slow = self.slow.current.value # Set the value of flag _ema_fast_was_above, to know when the ema indicators crosses between themselves if self.ema_fast_is_not_set == True: if fast > slow *1.001: self.ema_fast_was_above = True else: self.ema_fast_was_above = False self.ema_fast_is_not_set = False # Check whether ema fast and ema slow crosses. If they do, set holdings to SPY # or reduce its holdings, and send signals to Collective2 API from your Portfolio if fast > slow * 1.001 and (not self.ema_fast_was_above): self.set_holdings("SPY", 0.1) self.signal_export.set_target_portfolio_from_portfolio() elif fast < slow * 0.999 and (self.ema_fast_was_above): self.set_holdings("SPY", 0.01) self.signal_export.set_target_portfolio_from_portfolio() ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm reproducing data type bugs in the Consolidate API. Related to GH 4205.
```python from AlgorithmImports import * from CustomDataRegressionAlgorithm import Bitcoin class ConsolidateRegressionAlgorithm(QCAlgorithm): # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. def initialize(self): self.set_start_date(2020, 1, 5) self.set_end_date(2020, 1, 20) SP500 = Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME) symbol = list(self.futures_chain(SP500))[0] self._future = self.add_future_contract(symbol) tradable_dates_count = len(list(Time.each_tradeable_day_in_time_zone(self._future.exchange.hours, self.start_date, self.end_date, self._future.exchange.time_zone, False))) self._expected_consolidation_counts = [] self.consolidate(symbol, Calendar.MONTHLY, lambda bar: self.update_monthly_consolidator(bar)) # shouldn't consolidate self.consolidate(symbol, Calendar.WEEKLY, TickType.TRADE, lambda bar: self.update_weekly_consolidator(bar)) self.consolidate(symbol, Resolution.DAILY, lambda bar: self.update_trade_bar(bar, 0)) self._expected_consolidation_counts.append(tradable_dates_count) self.consolidate(symbol, Resolution.DAILY, TickType.QUOTE, lambda bar: self.update_quote_bar(bar, 1)) self._expected_consolidation_counts.append(tradable_dates_count) self.consolidate(symbol, timedelta(1), lambda bar: self.update_trade_bar(bar, 2)) self._expected_consolidation_counts.append(tradable_dates_count - 1) self.consolidate(symbol, timedelta(1), TickType.QUOTE, lambda bar: self.update_quote_bar(bar, 3)) self._expected_consolidation_counts.append(tradable_dates_count - 1) # sending None tick type self.consolidate(symbol, timedelta(1), None, lambda bar: self.update_trade_bar(bar, 4)) self._expected_consolidation_counts.append(tradable_dates_count - 1) self.consolidate(symbol, Resolution.DAILY, None, lambda bar: self.update_trade_bar(bar, 5)) self._expected_consolidation_counts.append(tradable_dates_count) self._consolidation_counts = [0] * len(self._expected_consolidation_counts) self._smas = [SimpleMovingAverage(10) for x in self._consolidation_counts] self._last_sma_updates = [datetime.min for x in self._consolidation_counts] self._monthly_consolidator_sma = SimpleMovingAverage(10) self._monthly_consolidation_count = 0 self._weekly_consolidator_sma = SimpleMovingAverage(10) self._weekly_consolidation_count = 0 self._last_weekly_sma_update = datetime.min # custom data self._custom_data_consolidator = 0 custom_symbol = self.add_data(Bitcoin, "BTC", Resolution.DAILY).symbol self.consolidate(custom_symbol, timedelta(1), lambda bar: self.increment_counter(1)) self._custom_data_consolidator2 = 0 self.consolidate(custom_symbol, Resolution.DAILY, lambda bar: self.increment_counter(2)) def increment_counter(self, id): if id == 1: self._custom_data_consolidator += 1 if id == 2: self._custom_data_consolidator2 += 1 def update_trade_bar(self, bar, position): self._smas[position].update(bar.end_time, bar.volume) self._last_sma_updates[position] = bar.end_time self._consolidation_counts[position] += 1 def update_quote_bar(self, bar, position): self._smas[position].update(bar.end_time, bar.ask.high) self._last_sma_updates[position] = bar.end_time self._consolidation_counts[position] += 1 def update_monthly_consolidator(self, bar): self._monthly_consolidator_sma.update(bar.end_time, bar.volume) self._monthly_consolidation_count += 1 def update_weekly_consolidator(self, bar): self._weekly_consolidator_sma.update(bar.end_time, bar.volume) self._last_weekly_sma_update = bar.end_time self._weekly_consolidation_count += 1 def on_end_of_algorithm(self): for i, expected_consolidation_count in enumerate(self._expected_consolidation_counts): consolidation_count = self._consolidation_counts[i] if consolidation_count != expected_consolidation_count: raise ValueError(f"Unexpected consolidation count for index {i}: expected {expected_consolidation_count} but was {consolidation_count}") expected_weekly_consolidations = (self.end_date - self.start_date).days // 7 if self._weekly_consolidation_count != expected_weekly_consolidations: raise ValueError(f"Expected {expected_weekly_consolidations} weekly consolidations but found {self._weekly_consolidation_count}") if self._custom_data_consolidator == 0: raise ValueError("Custom data consolidator did not consolidate any data") if self._custom_data_consolidator2 == 0: raise ValueError("Custom data consolidator 2 did not consolidate any data") for i, sma in enumerate(self._smas): if sma.samples != self._expected_consolidation_counts[i]: raise AssertionError(f"Expected {self._expected_consolidation_counts[i]} samples in each SMA but found {sma.samples} in SMA in index {i}") last_update = self._last_sma_updates[i] if sma.current.time != last_update: raise AssertionError(f"Expected SMA in index {i} to have been last updated at {last_update} but was {sma.current.time}") if self._monthly_consolidation_count != 0 or self._monthly_consolidator_sma.samples != 0: raise AssertionError("Expected monthly consolidator to not have consolidated any data") if self._weekly_consolidator_sma.samples != expected_weekly_consolidations: raise AssertionError(f"Expected {expected_weekly_consolidations} samples in the weekly consolidator SMA but found {self._weekly_consolidator_sma.samples}") if self._weekly_consolidator_sma.current.time != self._last_weekly_sma_update: raise AssertionError(f"Expected weekly consolidator SMA to have been last updated at {self._last_weekly_sma_update} but was {self._weekly_consolidator_sma.current.time}") # on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here. def on_data(self, data): if not self.portfolio.invested and self._future.has_data: self.set_holdings(self._future.symbol, 0.5) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Demostrates the use of <see cref="VolumeRenkoConsolidator"/> for creating constant volume bar
```python from AlgorithmImports import * class VolumeRenkoConsolidatorAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.set_cash(100000) self._sma = SimpleMovingAverage(10) self._tick_consolidated = False self._spy = self.add_equity("SPY", Resolution.MINUTE).symbol self._tradebar_volume_consolidator = VolumeRenkoConsolidator(1000000) self._tradebar_volume_consolidator.data_consolidated += self.on_spy_data_consolidated self._ibm = self.add_equity("IBM", Resolution.TICK).symbol self._tick_volume_consolidator = VolumeRenkoConsolidator(1000000) self._tick_volume_consolidator.data_consolidated += self.on_ibm_data_consolidated history = self.history[TradeBar](self._spy, 1000, Resolution.MINUTE) for bar in history: self._tradebar_volume_consolidator.update(bar) def on_spy_data_consolidated(self, sender, bar): self._sma.update(bar.end_time, bar.value) self.debug(f"SPY {bar.time} to {bar.end_time} :: O:{bar.open} H:{bar.high} L:{bar.low} C:{bar.close} V:{bar.volume}") if bar.volume != 1000000: raise AssertionError("Volume of consolidated bar does not match set value!") def on_ibm_data_consolidated(self, sender, bar): self.debug(f"IBM {bar.time} to {bar.end_time} :: O:{bar.open} H:{bar.high} L:{bar.low} C:{bar.close} V:{bar.volume}") if bar.volume != 1000000: raise AssertionError("Volume of consolidated bar does not match set value!") self._tick_consolidated = True def on_data(self, slice): # Update by TradeBar if slice.bars.contains_key(self._spy): self._tradebar_volume_consolidator.update(slice.bars[self._spy]) # Update by Tick if slice.ticks.contains_key(self._ibm): for tick in slice.ticks[self._ibm]: self._tick_volume_consolidator.update(tick) if self._sma.is_ready and self._sma.current.value < self.securities[self._spy].price: self.set_holdings(self._spy, 1) else: self.set_holdings(self._spy, 0) def on_end_of_algorithm(self): if not self._tick_consolidated: raise AssertionError("Tick consolidator was never been called") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests option exercise and assignment functionality We open two positions and go with them into expiration. We expect to see our long position exercised and short position assigned.
```python from AlgorithmImports import * class OptionSplitRegressionAlgorithm(QCAlgorithm): def initialize(self): # this test opens position in the first day of trading, lives through stock split (7 for 1), # and closes adjusted position on the second day self.set_cash(1000000) self.set_start_date(2014,6,6) self.set_end_date(2014,6,9) option = self.add_option("AAPL") # set our strike/expiry filter for this option chain option.set_filter(self.universe_func) self.set_benchmark("AAPL") self.contract = None def on_data(self, slice): if not self.portfolio.invested: if self.time.hour > 9 and self.time.minute > 0: for kvp in slice.option_chains: chain = kvp.value contracts = filter(lambda x: x.strike == 650 and x.right == OptionRight.CALL, chain) sorted_contracts = sorted(contracts, key = lambda x: x.expiry) if len(sorted_contracts) > 1: self.contract = sorted_contracts[1] self.buy(self.contract.symbol, 1) elif self.time.day > 6 and self.time.hour > 14 and self.time.minute > 0: self.liquidate() if self.portfolio.invested: options_hold = [x for x in self.portfolio.securities if x.value.holdings.absolute_quantity != 0] holdings = options_hold[0].value.holdings.absolute_quantity if self.time.day == 6 and holdings != 1: self.log("Expected position quantity of 1 but was {0}".format(holdings)) if self.time.day == 9 and holdings != 7: self.log("Expected position quantity of 7 but was {0}".format(holdings)) # set our strike/expiry filter for this option chain def universe_func(self, universe): return universe.include_weeklys().strikes(-2, 2).expiration(timedelta(0), timedelta(365*2)) def on_order_event(self, order_event): self.log(str(order_event)) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Demonstration of how to define a universe using the fundamental data
```python from AlgorithmImports import * class FundamentalRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2014, 3, 26) self.set_end_date(2014, 4, 7) self.universe_settings.resolution = Resolution.DAILY self._universe = self.add_universe(self.selection_function) # before we add any symbol self.assert_fundamental_universe_data() self.add_equity("SPY") self.add_equity("AAPL") # Request fundamental data for symbols at current algorithm time ibm = Symbol.create("IBM", SecurityType.EQUITY, Market.USA) ibm_fundamental = self.fundamentals(ibm) if self.time != self.start_date or self.time != ibm_fundamental.end_time: raise ValueError(f"Unexpected Fundamental time {ibm_fundamental.end_time}") if ibm_fundamental.price == 0: raise ValueError(f"Unexpected Fundamental IBM price!") nb = Symbol.create("NB", SecurityType.EQUITY, Market.USA) fundamentals = self.fundamentals([ nb, ibm ]) if len(fundamentals) != 2: raise ValueError(f"Unexpected Fundamental count {len(fundamentals)}! Expected 2") # Request historical fundamental data for symbols history = self.history(Fundamental, timedelta(days=2)) if len(history) != 4: raise ValueError(f"Unexpected Fundamental history count {len(history)}! Expected 4") for ticker in [ "AAPL", "SPY" ]: data = history.loc[ticker] if data["value"][0] == 0: raise ValueError(f"Unexpected {data} fundamental data") if Object.reference_equals(data.earningreports.iloc[0], data.earningreports.iloc[1]): raise ValueError(f"Unexpected fundamental data instance duplication") if data.earningreports.iloc[0]._time_provider.get_utc_now() == data.earningreports.iloc[1]._time_provider.get_utc_now(): raise ValueError(f"Unexpected fundamental data instance duplication") self.assert_fundamental_universe_data() self.changes = None self.number_of_symbols_fundamental = 2 def assert_fundamental_universe_data(self): # Case A universe_data = self.history(self._universe.data_type, [self._universe.symbol], timedelta(days=2), flatten=True) self.assert_fundamental_history(universe_data, "A") # Case B (sugar on A) universe_data_per_time = self.history(self._universe, timedelta(days=2), flatten=True) self.assert_fundamental_history(universe_data_per_time, "B") # Case C: Passing through the unvierse type and symbol enumerable_of_data_dictionary = self.history[self._universe.data_type]([self._universe.symbol], 100) for selection_collection_for_a_day in enumerable_of_data_dictionary: self.assert_fundamental_enumerator(selection_collection_for_a_day[self._universe.symbol], "C") def assert_fundamental_history(self, df, case_name): dates = df.index.get_level_values('time').unique() if dates.shape[0] != 2: raise ValueError(f"Unexpected Fundamental universe dates count {dates.shape[0]}! Expected 2") for date in dates: sub_df = df.loc[date] if sub_df.shape[0] < 7000: raise ValueError(f"Unexpected historical Fundamentals data count {sub_df.shape[0]} case {case_name}! Expected > 7000") def assert_fundamental_enumerator(self, enumerable, case_name): data_point_count = 0 for fundamental in enumerable: data_point_count += 1 if type(fundamental) is not Fundamental: raise ValueError(f"Unexpected Fundamentals data type {type(fundamental)} case {case_name}! {str(fundamental)}") if data_point_count < 7000: raise ValueError(f"Unexpected historical Fundamentals data count {data_point_count} case {case_name}! Expected > 7000") # return a list of three fixed symbol objects def selection_function(self, fundamental): # sort descending by daily dollar volume sorted_by_dollar_volume = sorted([x for x in fundamental if x.price > 1], key=lambda x: x.dollar_volume, reverse=True) # sort descending by P/E ratio sorted_by_pe_ratio = sorted(sorted_by_dollar_volume, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True) # take the top entries from our sorted collection return [ x.symbol for x in sorted_by_pe_ratio[:self.number_of_symbols_fundamental] ] def on_data(self, data): # if we have no changes, do nothing if self.changes is None: return # liquidate removed securities for security in self.changes.removed_securities: if security.invested: self.liquidate(security.symbol) self.debug("Liquidated Stock: " + str(security.symbol.value)) # we want 50% allocation in each security in our universe for security in self.changes.added_securities: self.set_holdings(security.symbol, 0.02) self.changes = None # this event fires whenever we have changes to our universe def on_securities_changed(self, changes): self.changes = changes ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests that we receive the expected data when we add future option contracts individually using <see cref="AddFutureOptionContract"/>
```python from AlgorithmImports import * class AddFutureOptionContractDataStreamingRegressionAlgorithm(QCAlgorithm): def initialize(self): self.on_data_reached = False self.invested = False self.symbols_received = [] self.expected_symbols_received = [] self.data_received = {} self.set_start_date(2020, 1, 4) self.set_end_date(2020, 1, 8) self.es20h20 = self.add_future_contract( Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 3, 20)), Resolution.MINUTE).symbol self.es19m20 = self.add_future_contract( Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 6, 19)), Resolution.MINUTE).symbol # Get option contract lists for 2020/01/05 (timedelta(days=1)) because Lean has local data for that date option_chains = list(self.option_chain_provider.get_option_contract_list(self.es20h20, self.time + timedelta(days=1))) option_chains += self.option_chain_provider.get_option_contract_list(self.es19m20, self.time + timedelta(days=1)) for option_contract in option_chains: self.expected_symbols_received.append(self.add_future_option_contract(option_contract, Resolution.MINUTE).symbol) def on_data(self, data: Slice): if not data.has_data: return self.on_data_reached = True has_option_quote_bars = False for qb in data.quote_bars.values(): if qb.symbol.security_type != SecurityType.FUTURE_OPTION: continue has_option_quote_bars = True self.symbols_received.append(qb.symbol) if qb.symbol not in self.data_received: self.data_received[qb.symbol] = [] self.data_received[qb.symbol].append(qb) if self.invested or not has_option_quote_bars: return if data.contains_key(self.es20h20) and data.contains_key(self.es19m20): self.set_holdings(self.es20h20, 0.2) self.set_holdings(self.es19m20, 0.2) self.invested = True def on_end_of_algorithm(self): self.symbols_received = list(set(self.symbols_received)) self.expected_symbols_received = list(set(self.expected_symbols_received)) if not self.on_data_reached: raise AssertionError("OnData() was never called.") if len(self.symbols_received) != len(self.expected_symbols_received): raise AssertionError(f"Expected {len(self.expected_symbols_received)} option contracts Symbols, found {len(self.symbols_received)}") missing_symbols = [expected_symbol.value for expected_symbol in self.expected_symbols_received if expected_symbol not in self.symbols_received] if any(missing_symbols): raise AssertionError(f'Symbols: "{", ".join(missing_symbols)}" were not found in OnData') for expected_symbol in self.expected_symbols_received: data = self.data_received[expected_symbol] for data_point in data: data_point.end_time = datetime(1970, 1, 1) non_dupe_data_count = len(set(data)) if non_dupe_data_count < 1000: raise AssertionError(f"Received too few data points. Expected >=1000, found {non_dupe_data_count} for {expected_symbol}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Test algorithm generating insights with custom tags
```python from AlgorithmImports import * from Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel from Execution.ImmediateExecutionModel import ImmediateExecutionModel class InsightTagAlphaRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013,10,7) self.set_end_date(2013,10,11) self.set_cash(100000) self.universe_settings.resolution = Resolution.DAILY self.spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA) self.fb = Symbol.create("FB", SecurityType.EQUITY, Market.USA) self.ibm = Symbol.create("IBM", SecurityType.EQUITY, Market.USA) # set algorithm framework models self.set_universe_selection(ManualUniverseSelectionModel([self.spy, self.fb, self.ibm])) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) self.set_execution(ImmediateExecutionModel()) self.add_alpha(OneTimeAlphaModel(self.spy)) self.add_alpha(OneTimeAlphaModel(self.fb)) self.add_alpha(OneTimeAlphaModel(self.ibm)) self.insights_generated += self.on_insights_generated_verifier self._symbols_with_generated_insights = [] def on_insights_generated_verifier(self, algorithm: IAlgorithm, insights_collection: GeneratedInsightsCollection) -> None: for insight in insights_collection.insights: if insight.tag != OneTimeAlphaModel.generate_insight_tag(insight.symbol): raise AssertionError("Unexpected insight tag was emitted") self._symbols_with_generated_insights.append(insight.symbol) def on_end_of_algorithm(self) -> None: if len(self._symbols_with_generated_insights) != 3: raise AssertionError("Unexpected number of symbols with generated insights") if not self.spy in self._symbols_with_generated_insights: raise AssertionError("SPY symbol was not found in symbols with generated insights") if not self.fb in self._symbols_with_generated_insights: raise AssertionError("FB symbol was not found in symbols with generated insights") if not self.ibm in self._symbols_with_generated_insights: raise AssertionError("IBM symbol was not found in symbols with generated insights") class OneTimeAlphaModel(AlphaModel): def __init__(self, symbol): self._symbol = symbol self.triggered = False def update(self, algorithm, data): insights = [] if not self.triggered: self.triggered = True insights.append(Insight.price( self._symbol, Resolution.DAILY, 1, InsightDirection.DOWN, tag=OneTimeAlphaModel.generate_insight_tag(self._symbol))) return insights @staticmethod def generate_insight_tag(symbol: Symbol) -> str: return f"Insight generated for {symbol}" ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : In this algorithm we demonstrate how to perform some technical analysis as part of your coarse fundamental universe selection
```python from AlgorithmImports import * class EmaCrossUniverseSelectionAlgorithm(QCAlgorithm): def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2010,1,1) #Set Start Date self.set_end_date(2015,1,1) #Set End Date self.set_cash(100000) #Set Strategy Cash self.universe_settings.resolution = Resolution.DAILY self.universe_settings.leverage = 2 self.coarse_count = 10 self.averages = { } # this add universe method accepts two parameters: # - coarse selection function: accepts an IEnumerable<CoarseFundamental> and returns an IEnumerable<Symbol> self.add_universe(self.coarse_selection_function) # sort the data by daily dollar volume and take the top 'NumberOfSymbols' def coarse_selection_function(self, coarse): # We are going to use a dictionary to refer the object that will keep the moving averages for cf in coarse: if cf.symbol not in self.averages: self.averages[cf.symbol] = SymbolData(cf.symbol) # Updates the SymbolData object with current EOD price avg = self.averages[cf.symbol] avg.update(cf.end_time, cf.adjusted_price) # Filter the values of the dict: we only want up-trending securities values = list(filter(lambda x: x.is_uptrend, self.averages.values())) # Sorts the values of the dict: we want those with greater difference between the moving averages values.sort(key=lambda x: x.scale, reverse=True) for x in values[:self.coarse_count]: self.log('symbol: ' + str(x.symbol.value) + ' scale: ' + str(x.scale)) # we need to return only the symbol objects return [ x.symbol for x in values[:self.coarse_count] ] # this event fires whenever we have changes to our universe def on_securities_changed(self, changes): # liquidate removed securities for security in changes.removed_securities: if security.invested: self.liquidate(security.symbol) # we want 20% allocation in each security in our universe for security in changes.added_securities: self.set_holdings(security.symbol, 0.1) class SymbolData(object): def __init__(self, symbol): self._symbol = symbol self.tolerance = 1.01 self.fast = ExponentialMovingAverage(100) self.slow = ExponentialMovingAverage(300) self.is_uptrend = False self.scale = 0 def update(self, time, value): if self.fast.update(time, value) and self.slow.update(time, value): fast = self.fast.current.value slow = self.slow.current.value self.is_uptrend = fast > slow * self.tolerance if self.is_uptrend: self.scale = (fast - slow) / ((fast + slow) / 2.0) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This example algorithm defines its own custom coarse/fine fundamental selection model with equally weighted portfolio and a maximum sector exposure.
```python from AlgorithmImports import * from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel from Alphas.ConstantAlphaModel import ConstantAlphaModel from Execution.ImmediateExecutionModel import ImmediateExecutionModel from Risk.MaximumSectorExposureRiskManagementModel import MaximumSectorExposureRiskManagementModel class SectorExposureRiskFrameworkAlgorithm(QCAlgorithm): '''This example algorithm defines its own custom coarse/fine fundamental selection model def initialize(self): # Set requested data resolution self.universe_settings.resolution = Resolution.DAILY self.set_start_date(2014, 3, 25) self.set_end_date(2014, 4, 7) self.set_cash(100000) # set algorithm framework models self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.select_coarse, self.select_fine)) self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1))) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) self.set_risk_management(MaximumSectorExposureRiskManagementModel()) def on_order_event(self, order_event): if order_event.status == OrderStatus.FILLED: self.debug(f"Order event: {order_event}. Holding value: {self.securities[order_event.symbol].holdings.absolute_holdings_value}") def select_coarse(self, coarse): tickers = ["AAPL", "AIG", "IBM"] if self.time.date() < date(2014, 4, 1) else [ "GOOG", "BAC", "SPY" ] return [Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers] def select_fine(self, fine): return [f.symbol for f in fine] ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Tests the mapping of the ETF symbol that has a constituent universe attached to it and ensures that data is loaded after the mapping event takes place.
```python from AlgorithmImports import * class ETFConstituentUniverseFilterFunctionRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2011, 2, 1) self.set_end_date(2011, 4, 4) self.set_cash(100000) self.filter_date_constituent_symbol_count = {} self.constituent_data_encountered = {} self.constituent_symbols = [] self.mapping_event_occurred = False self.universe_settings.resolution = Resolution.HOUR self.aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA) self.qqq = self.add_equity("QQQ", Resolution.DAILY).symbol self.add_universe(self.universe.etf(self.qqq, self.universe_settings, self.filter_etfs)) def filter_etfs(self, constituents): constituent_symbols = [i.symbol for i in constituents] if self.aapl not in constituent_symbols: raise AssertionError("AAPL not found in QQQ constituents") self.filter_date_constituent_symbol_count[self.utc_time.date()] = len(constituent_symbols) for symbol in constituent_symbols: self.constituent_symbols.append(symbol) self.constituent_symbols = list(set(self.constituent_symbols)) return constituent_symbols def on_data(self, data): if len(data.symbol_changed_events) != 0: for symbol_changed in data.symbol_changed_events.values(): if symbol_changed.symbol != self.qqq: raise AssertionError(f"Mapped symbol is not QQQ. Instead, found: {symbol_changed.symbol}") if symbol_changed.old_symbol != "QQQQ": raise AssertionError(f"Old QQQ Symbol is not QQQQ. Instead, found: {symbol_changed.old_symbol}") if symbol_changed.new_symbol != "QQQ": raise AssertionError(f"New QQQ Symbol is not QQQ. Instead, found: {symbol_changed.new_symbol}") self.mapping_event_occurred = True if self.qqq in data and len([i for i in data.keys()]) == 1: return if self.utc_time.date() not in self.constituent_data_encountered: self.constituent_data_encountered[self.utc_time.date()] = False if len([i for i in data.keys() if i in self.constituent_symbols]) != 0: self.constituent_data_encountered[self.utc_time.date()] = True if not self.portfolio.invested: self.set_holdings(self.aapl, 0.5) def on_end_of_algorithm(self): if len(self.filter_date_constituent_symbol_count) != 2: raise AssertionError(f"ETF constituent filtering function was not called 2 times (actual: {len(self.filter_date_constituent_symbol_count)}") if not self.mapping_event_occurred: raise AssertionError("No mapping/SymbolChangedEvent occurred. Expected for QQQ to be mapped from QQQQ -> QQQ") for constituent_date, constituents_count in self.filter_date_constituent_symbol_count.items(): if constituents_count < 25: raise AssertionError(f"Expected 25 or more constituents in filter function on {constituent_date}, found {constituents_count}") for constituent_date, constituent_encountered in self.constituent_data_encountered.items(): if not constituent_encountered: raise AssertionError(f"Received data in OnData(...) but it did not contain any constituent data on {constituent_date.strftime('%Y-%m-%d %H:%M:%S.%f')}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm to assert the behavior of <see cref="MaximumUnrealizedProfitPercentPerSecurity"/>.
```python from AlgorithmImports import * from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm from Risk.MaximumUnrealizedProfitPercentPerSecurity import MaximumUnrealizedProfitPercentPerSecurity class MaximumUnrealizedProfitPercentPerSecurityFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm): def initialize(self): super().initialize() self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create("AAPL", SecurityType.EQUITY, Market.USA))) self.set_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.004)) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests In The Money (ITM) index option expiry for short calls. We expect 2 orders from the algorithm, which are: * Initial entry, sell SPX Call Option (expiring ITM) * Option assignment Additionally, we test delistings for index options and assert that our portfolio holdings reflect the orders the algorithm has submitted.
```python from AlgorithmImports import * class IndexOptionShortCallITMExpiryRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2021, 1, 4) self.set_end_date(2021, 1, 31) self.set_cash(1000000) self.portfolio.set_margin_call_model(MarginCallModel.NULL); # avoid getting assigned self.set_security_initializer(CompositeSecurityInitializer(self.security_initializer, FuncSecurityInitializer(self.custom_security_initializer))) self.spx = self.add_index("SPX", Resolution.MINUTE).symbol # Select a index option expiring ITM, and adds it to the algorithm. self.spx_options = list(self.option_chain(self.spx)) self.spx_option_filtered = [i for i in self.spx_options if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1] self.spx_option = list(sorted(self.spx_option_filtered, key=lambda x: x.id.strike_price, reverse=True))[0].symbol self.add_index_option_contract(self.spx_option, Resolution.MINUTE).symbol self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3200, datetime(2021, 1, 15)) if self.spx_option != self.expected_contract: raise AssertionError(f"Contract self.expected_contract was not found in the chain") self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1)) def on_data(self, data: Slice): # Assert delistings, so that we can make sure that we receive the delisting warnings at # the expected time. These assertions detect bug #4872 for delisting in data.delistings.values(): if delisting.type == DelistingType.WARNING: if delisting.time != datetime(2021, 1, 15): raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}") if delisting.type == DelistingType.DELISTED: if delisting.time != datetime(2021, 1, 16): raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}") def on_order_event(self, order_event: OrderEvent): if order_event.status != OrderStatus.FILLED: # There's lots of noise with OnOrderEvent, but we're only interested in fills. return if order_event.symbol not in self.securities: raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}") security = self.securities[order_event.symbol] if security.symbol == self.spx: self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_contract]) elif security.symbol == self.expected_contract: self.assert_index_option_contract_order(order_event, security) else: raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}") def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security): if "Assignment" in order_event.message: if order_event.fill_price != 3200: raise AssertionError("Option was not assigned at expected strike price (3200)") if order_event.direction != OrderDirection.SELL or index.holdings.quantity != 0: raise AssertionError(f"Expected Qty: 0 index holdings for assigned index option {index.symbol}, found {index.holdings.quantity}") def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security): if order_event.direction == OrderDirection.SELL and option.holdings.quantity != -1: raise AssertionError(f"No holdings were created for option contract {option.symbol}") if order_event.is_assignment and option.holdings.quantity != 0: raise AssertionError(f"Holdings were found after option contract was assigned: {option.symbol}") ### <summary> ### Ran at the end of the algorithm to ensure the algorithm has no holdings ### </summary> ### <exception cref="Exception">The algorithm has holdings</exception> def on_end_of_algorithm(self): if self.portfolio.invested: raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}") def custom_security_initializer(self, security): if Extensions.is_option(security.symbol.security_type): security.set_option_assignment_model(NullOptionAssignmentModel()) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests Out of The Money (OTM) index option expiry for short calls. We expect 2 orders from the algorithm, which are: * Initial entry, sell SPX Call Option (expiring OTM) - Profit the option premium, since the option was not assigned. * Liquidation of SPX call OTM contract on the last trade date Additionally, we test delistings for index options and assert that our portfolio holdings reflect the orders the algorithm has submitted.
```python from AlgorithmImports import * class IndexOptionShortCallOTMExpiryRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2021, 1, 4) self.set_end_date(2021, 1, 31) self.spx = self.add_index("SPX", Resolution.MINUTE).symbol # Select a index option expiring ITM, and adds it to the algorithm. self.spx_options = list(self.option_chain(self.spx)) self.spx_options = [i for i in self.spx_options if i.id.strike_price >= 4250 and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1] self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price))[0] self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 4250, datetime(2021, 1, 15)) if self.spx_option != self.expected_contract: raise AssertionError(f"Contract {self.expected_contract} was not found in the chain") self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1)) def on_data(self, data: Slice): # Assert delistings, so that we can make sure that we receive the delisting warnings at # the expected time. These assertions detect bug #4872 for delisting in data.delistings.values(): if delisting.type == DelistingType.WARNING: if delisting.time != datetime(2021, 1, 15): raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}") if delisting.type == DelistingType.DELISTED: if delisting.time != datetime(2021, 1, 16): raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}") def on_order_event(self, order_event: OrderEvent): if order_event.status != OrderStatus.FILLED: # There's lots of noise with OnOrderEvent, but we're only interested in fills. return if order_event.symbol not in self.securities: raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}") security = self.securities[order_event.symbol] if security.symbol == self.spx: raise AssertionError(f"Expected no order events for underlying Symbol {security.symbol}") if security.symbol == self.expected_contract: self.assert_index_option_contract_order(order_event, security) else: raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}") def assert_index_option_contract_order(self, order_event: OrderEvent, option_contract: Security): if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1: raise AssertionError(f"No holdings were created for option contract {option_contract.symbol}") if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0: raise AssertionError("Expected no options holdings after closing position") if order_event.is_assignment: raise AssertionError(f"Assignment was not expected for {order_event.symbol}") ### <summary> ### Ran at the end of the algorithm to ensure the algorithm has no holdings ### </summary> ### <exception cref="Exception">The algorithm has holdings</exception> def on_end_of_algorithm(self): if self.portfolio.invested: raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : def initialize(self) -> None:
```python from AlgorithmImports import * class BasicTemplateIndexOptionsAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2021, 1, 4) self.set_end_date(2021, 2, 1) self.set_cash(1000000) self.spx = self.add_index("SPX", Resolution.MINUTE).symbol spx_options = self.add_index_option(self.spx, Resolution.MINUTE) spx_options.set_filter(lambda x: x.calls_only()) self.ema_slow = self.ema(self.spx, 80) self.ema_fast = self.ema(self.spx, 200) def on_data(self, data: Slice) -> None: if self.spx not in data.bars or not self.ema_slow.is_ready: return for chain in data.option_chains.values(): for contract in chain.contracts.values(): if self.portfolio.invested: continue if (self.ema_fast > self.ema_slow and contract.right == OptionRight.CALL) or \ (self.ema_fast < self.ema_slow and contract.right == OptionRight.PUT): self.liquidate(self.invert_option(contract.symbol)) self.market_order(contract.symbol, 1) def on_end_of_algorithm(self) -> None: if self.portfolio[self.spx].total_sale_volume > 0: raise AssertionError("Index is not tradable.") if self.portfolio.total_sale_volume == 0: raise AssertionError("Trade volume should be greater than zero by the end of this algorithm") def invert_option(self, symbol: Symbol) -> Symbol: return Symbol.create_option( symbol.underlying, symbol.id.market, symbol.id.option_style, OptionRight.PUT if symbol.id.option_right == OptionRight.CALL else OptionRight.CALL, symbol.id.strike_price, symbol.id.date ) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm showing how to define a custom insight scoring function and using the insight manager
```python from AlgorithmImports import * class InsightScoringRegressionAlgorithm(QCAlgorithm): '''Regression algorithm showing how to define a custom insight evaluator''' def initialize(self): ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2013,10,7) self.set_end_date(2013,10,11) symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ] self.set_universe_selection(ManualUniverseSelectionModel(symbols)) self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None)) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY)) self.set_execution(ImmediateExecutionModel()) self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01)) # we specify a custom insight evaluator self.insights.set_insight_score_function(CustomInsightScoreFunction(self.securities)) def on_end_of_algorithm(self): all_insights = self.insights.get_insights(lambda insight: True) if len(all_insights) != 100 or len(self.insights.get_insights()) != 100: raise ValueError(f'Unexpected insight count found {all_insights.count}') if sum(1 for insight in all_insights if insight.score.magnitude == 0 or insight.score.direction == 0) < 5: raise ValueError(f'Insights not scored!') if sum(1 for insight in all_insights if insight.score.is_final_score) < 99: raise ValueError(f'Insights not finalized!') class CustomInsightScoreFunction(): def __init__(self, securities): self._securities = securities self._open_insights = {} def score(self, insight_manager, utc_time): open_insights = insight_manager.get_active_insights(utc_time) for insight in open_insights: self._open_insights[insight.id] = insight to_remove = [] for open_insight in self._open_insights.values(): security = self._securities[open_insight.symbol] open_insight.reference_value_final = security.price score = open_insight.reference_value_final - open_insight.reference_value open_insight.score.set_score(InsightScoreType.DIRECTION, score, utc_time) open_insight.score.set_score(InsightScoreType.MAGNITUDE, score * 2, utc_time) open_insight.estimated_value = score * 100 if open_insight.is_expired(utc_time): open_insight.score.finalize(utc_time) to_remove.append(open_insight) # clean up for insight_to_remove in to_remove: self._open_insights.pop(insight_to_remove.id) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : The algorithm creates new indicator value with the existing indicator method by Indicator Extensions Demonstration of using the external custom data to request the IBM and SPY daily data
```python from AlgorithmImports import * from HistoryAlgorithm import * class CustomDataIndicatorExtensionsAlgorithm(QCAlgorithm): # Initialize the data and resolution you require for your strategy def initialize(self): self.set_start_date(2014,1,1) self.set_end_date(2018,1,1) self.set_cash(25000) self.ibm = 'IBM' self.spy = 'SPY' # Define the symbol and "type" of our generic data self.add_data(CustomDataEquity, self.ibm, Resolution.DAILY) self.add_data(CustomDataEquity, self.spy, Resolution.DAILY) # Set up default Indicators, these are just 'identities' of the closing price self.ibm_sma = self.sma(self.ibm, 1, Resolution.DAILY) self.spy_sma = self.sma(self.spy, 1, Resolution.DAILY) # This will create a new indicator whose value is sma_s_p_y / sma_i_b_m self.ratio = IndicatorExtensions.over(self.spy_sma, self.ibm_sma) # Plot indicators each time they update using the PlotIndicator function self.plot_indicator("Ratio", self.ratio) self.plot_indicator("Data", self.ibm_sma, self.spy_sma) # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. def on_data(self, data): # Wait for all indicators to fully initialize if not (self.ibm_sma.is_ready and self.spy_sma.is_ready and self.ratio.is_ready): return if not self.portfolio.invested and self.ratio.current.value > 1: self.market_order(self.ibm, 100) elif self.ratio.current.value < 1: self.liquidate() ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Demonstrate the usage of the BrokerageModel property to help improve backtesting accuracy through simulation of a specific brokerage's rules around restrictions on submitting orders as well as fee structure.
```python from AlgorithmImports import * class BrokerageModelAlgorithm(QCAlgorithm): def initialize(self): self.set_cash(100000) # Set Strategy Cash self.set_start_date(2013,10,7) # Set Start Date self.set_end_date(2013,10,11) # Set End Date self.add_equity("SPY", Resolution.SECOND) # there's two ways to set your brokerage model. The easiest would be to call # self.set_brokerage_model( BrokerageName ) # BrokerageName is an enum # self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE) # self.set_brokerage_model(BrokerageName.DEFAULT) # the other way is to call SetBrokerageModel( IBrokerageModel ) with your # own custom model. I've defined a simple extension to the default brokerage # model to take into account a requirement to maintain 500 cash in the account at all times self.set_brokerage_model(MinimumAccountBalanceBrokerageModel(self,500.00)) self.last = 1 def on_data(self, slice): # Simple buy and hold template if not self.portfolio.invested: self.set_holdings("SPY", self.last) if self.portfolio["SPY"].quantity == 0: # each time we fail to purchase we'll decrease our set holdings percentage self.debug(str(self.time) + " - Failed to purchase stock") self.last *= 0.95 else: self.debug("{} - Purchased Stock @ SetHoldings( {} )".format(self.time, self.last)) class MinimumAccountBalanceBrokerageModel(DefaultBrokerageModel): '''Custom brokerage model that requires clients to maintain a minimum cash balance''' def __init__(self, algorithm, minimum_account_balance): self.algorithm = algorithm self.minimum_account_balance = minimum_account_balance def can_submit_order(self,security, order, message): '''Prevent orders which would bring the account below a minimum cash balance''' message = None # we want to model brokerage requirement of minimum_account_balance cash value in account order_cost = order.get_value(security) cash = self.algorithm.portfolio.cash cash_after_order = cash - order_cost if cash_after_order < self.minimum_account_balance: # return a message describing why we're not allowing this order message = BrokerageMessageEvent(BrokerageMessageType.WARNING, "InsufficientRemainingCapital", "Account must maintain a minimum of ${0} USD at all times. Order ID: {1}".format(self.minimum_account_balance, order.id)) self.algorithm.error(str(message)) return False return True ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression test to check python indicator is keeping backwards compatibility with indicators that do not set WarmUpPeriod or do not inherit from PythonIndicator class.
```python from AlgorithmImports import * from collections import deque class CustomWarmUpPeriodIndicatorAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.add_equity("SPY", Resolution.SECOND) # Create three python indicators # - custom_not_warm_up does not define WarmUpPeriod parameter # - custom_warm_up defines WarmUpPeriod parameter # - custom_not_inherit defines WarmUpPeriod parameter but does not inherit from PythonIndicator class # - csharp_indicator defines WarmUpPeriod parameter and represents the traditional LEAN C# indicator self._custom_not_warm_up = CSMANotWarmUp('custom_not_warm_up', 60) self._custom_warm_up = CSMAWithWarmUp('custom_warm_up', 60) self._custom_not_inherit = CustomSMA('custom_not_inherit', 60) self._csharp_indicator = SimpleMovingAverage('csharp_indicator', 60) # Register the daily data of "SPY" to automatically update the indicators self.register_indicator("SPY", self._custom_warm_up, Resolution.MINUTE) self.register_indicator("SPY", self._custom_not_warm_up, Resolution.MINUTE) self.register_indicator("SPY", self._custom_not_inherit, Resolution.MINUTE) self.register_indicator("SPY", self._csharp_indicator, Resolution.MINUTE) # Warm up custom_warm_up indicator self.warm_up_indicator("SPY", self._custom_warm_up, Resolution.MINUTE) # Check custom_warm_up indicator has already been warmed up with the requested data assert(self._custom_warm_up.is_ready), "custom_warm_up indicator was expected to be ready" assert(self._custom_warm_up.samples == 60), "custom_warm_up indicator was expected to have processed 60 datapoints already" # Try to warm up custom_not_warm_up indicator. It's expected from LEAN to skip the warm up process # because this indicator doesn't define WarmUpPeriod parameter self.warm_up_indicator("SPY", self._custom_not_warm_up, Resolution.MINUTE) # Check custom_not_warm_up indicator is not ready and is using the default WarmUpPeriod value assert(not self._custom_not_warm_up.is_ready), "custom_not_warm_up indicator wasn't expected to be warmed up" assert(self._custom_not_warm_up.warm_up_period == 0), "custom_not_warm_up indicator WarmUpPeriod parameter was expected to be 0" # Warm up custom_not_inherit indicator. Though it does not inherit from PythonIndicator class, # it defines WarmUpPeriod parameter so it's expected to be warmed up from LEAN self.warm_up_indicator("SPY", self._custom_not_inherit, Resolution.MINUTE) # Check custom_not_inherit indicator has already been warmed up with the requested data assert(self._custom_not_inherit.is_ready), "custom_not_inherit indicator was expected to be ready" assert(self._custom_not_inherit.samples == 60), "custom_not_inherit indicator was expected to have processed 60 datapoints already" # Warm up csharp_indicator self.warm_up_indicator("SPY", self._csharp_indicator, Resolution.MINUTE) # Check csharp_indicator indicator has already been warmed up with the requested data assert(self._csharp_indicator.is_ready), "csharp_indicator indicator was expected to be ready" assert(self._csharp_indicator.samples == 60), "csharp_indicator indicator was expected to have processed 60 datapoints already" def on_data(self, data: Slice) -> None: if not self.portfolio.invested: self.set_holdings("SPY", 1) if self.time.second == 0: # Compute the difference between indicators values diff = abs(self._custom_not_warm_up.current.value - self._custom_warm_up.current.value) diff += abs(self._custom_not_inherit.value - self._custom_not_warm_up.current.value) diff += abs(self._custom_not_inherit.value - self._custom_warm_up.current.value) diff += abs(self._csharp_indicator.current.value - self._custom_warm_up.current.value) diff += abs(self._csharp_indicator.current.value - self._custom_not_warm_up.current.value) diff += abs(self._csharp_indicator.current.value - self._custom_not_inherit.value) # Check custom_not_warm_up indicator is ready when the number of samples is bigger than its WarmUpPeriod parameter assert(self._custom_not_warm_up.is_ready == (self._custom_not_warm_up.samples >= 60)), "custom_not_warm_up indicator was expected to be ready when the number of samples were bigger that its WarmUpPeriod parameter" # Check their values are the same. We only need to check if custom_not_warm_up indicator is ready because the other ones has already been asserted to be ready assert(diff <= 1e-10 or (not self._custom_not_warm_up.is_ready)), f"The values of the indicators are not the same. Indicators difference is {diff}" # Python implementation of SimpleMovingAverage. # Represents the traditional simple moving average indicator (SMA) without Warm Up Period parameter defined class CSMANotWarmUp(PythonIndicator): def __init__(self, name: str, period: int) -> None: super().__init__() self.name = name self.value = 0 self._queue = deque(maxlen=period) # Update method is mandatory def update(self, input: IndicatorDataPoint) -> bool: self._queue.appendleft(input.value) count = len(self._queue) self.value = np.sum(self._queue) / count return count == self._queue.maxlen # Python implementation of SimpleMovingAverage. # Represents the traditional simple moving average indicator (SMA) With Warm Up Period parameter defined class CSMAWithWarmUp(CSMANotWarmUp): def __init__(self, name: str, period: int) -> None: super().__init__(name, period) self.warm_up_period = period # Custom python implementation of SimpleMovingAverage. # Represents the traditional simple moving average indicator (SMA) class CustomSMA(): def __init__(self, name: str, period: int) -> None: self.name = name self.value = 0 self._queue = deque(maxlen=period) self.warm_up_period = period self.is_ready = False self.samples = 0 # Update method is mandatory def update(self, input: IndicatorDataPoint) -> bool: self.samples += 1 self._queue.appendleft(input.value) count = len(self._queue) self.value = np.sum(self._queue) / count if count == self._queue.maxlen: self.is_ready = True return self.is_ready ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Demonstration of using an external custom datasource. LEAN Engine is incredibly flexible and allows you to define your own data source. This includes any data source which has a TIME and VALUE. These are the *only* requirements. To demonstrate this we're loading in "Bitcoin" data.
```python from AlgorithmImports import * import pytz class CustomDataBitcoinAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2011, 9, 13) self.set_end_date(datetime.now().date() - timedelta(1)) self.set_cash(100000) # Define the symbol and "type" of our generic data: self.add_data(Bitcoin, "BTC") def on_data(self, data): if not data.contains_key("BTC"): return close = data["BTC"].close # If we don't have any weather "SHARES" -- invest" if not self.portfolio.invested: # Weather used as a tradable asset, like stocks, futures etc. # It's only OK to use SetHoldings with crypto when using custom data. When trading with built-in crypto data, # use the cashbook. Reference https://github.com/QuantConnect/Lean/blob/master/Algorithm.python/BasicTemplateCryptoAlgorithm.py self.set_holdings("BTC", 1) self.debug("Buying BTC 'Shares': BTC: {0}".format(close)) self.debug("Time: {0} {1}".format(datetime.now(), close)) class Bitcoin(PythonData): '''Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data''' def get_source(self, config, date, is_live_mode): if is_live_mode: return SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.REST) #return "http://my-ftp-server.com/futures-data-" + date.to_string("Ymd") + ".zip" # OR simply return a fixed small data file. Large files will slow down your backtest return SubscriptionDataSource("https://www.quantconnect.com/api/v2/proxy/quandl/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc&api_key=WyAazVXnq7ATy_fefTqm", SubscriptionTransportMedium.REMOTE_FILE) def reader(self, config, line, date, is_live_mode): coin = Bitcoin() coin.symbol = config.symbol if is_live_mode: # Example Line Format: # {"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"} try: live_btc = json.loads(line) # If value is zero, return None value = live_btc["last"] if value == 0: return None coin.end_time = datetime.now(pytz.timezone(str(config.exchange_time_zone))) coin.value = value coin["Open"] = float(live_btc["open"]) coin["High"] = float(live_btc["high"]) coin["Low"] = float(live_btc["low"]) coin["Close"] = float(live_btc["last"]) coin["Ask"] = float(live_btc["ask"]) coin["Bid"] = float(live_btc["bid"]) coin["VolumeBTC"] = float(live_btc["volume"]) coin["WeightedPrice"] = float(live_btc["vwap"]) return coin except ValueError: # Do nothing, possible error in json decoding return None # Example Line Format: # Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price # 2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356 if not (line.strip() and line[0].isdigit()): return None try: data = line.split(',') # If value is zero, return None value = data[4] if value == 0: return None coin.time = datetime.strptime(data[0], "%Y-%m-%d") coin.end_time = coin.time + timedelta(days=1) coin.value = value coin["Open"] = float(data[1]) coin["High"] = float(data[2]) coin["Low"] = float(data[3]) coin["Close"] = float(data[4]) coin["VolumeBTC"] = float(data[5]) coin["VolumeUSD"] = float(data[6]) coin["WeightedPrice"] = float(data[7]) return coin except ValueError: # Do nothing, possible error in json decoding return None ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This algorithm shows how to set a custom security initializer. A security initializer is run immediately after a new security object has been created and can be used to security models and other settings, such as data normalization mode
```python from AlgorithmImports import * class CustomSecurityInitializerAlgorithm(QCAlgorithm): def initialize(self): # set our initializer to our custom type self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE) func_security_seeder = FuncSecuritySeeder(self.custom_seed_function) self.set_security_initializer(CustomSecurityInitializer(self.brokerage_model, func_security_seeder, DataNormalizationMode.RAW)) self.set_start_date(2013,10,1) self.set_end_date(2013,11,1) self.add_equity("SPY", Resolution.HOUR) def on_data(self, data): if not self.portfolio.invested: self.set_holdings("SPY", 1) def custom_seed_function(self, security): resolution = Resolution.HOUR df = self.history(security.symbol, 1, resolution) if df.empty: return None last_bar = df.unstack(level=0).iloc[-1] date_time = last_bar.name.to_pydatetime() open = last_bar.open.values[0] high = last_bar.high.values[0] low = last_bar.low.values[0] close = last_bar.close.values[0] volume = last_bar.volume.values[0] return TradeBar(date_time, security.symbol, open, high, low, close, volume, Extensions.to_time_span(resolution)) class CustomSecurityInitializer(BrokerageModelSecurityInitializer): '''Our custom initializer that will set the data normalization mode. We sub-class the BrokerageModelSecurityInitializer so we can also take advantage of the default model/leverage setting behaviors''' def __init__(self, brokerage_model, security_seeder, data_normalization_mode): '''Initializes a new instance of the CustomSecurityInitializer class with the specified normalization mode brokerage_model -- The brokerage model used to get fill/fee/slippage/settlement models security_seeder -- The security seeder to be used data_normalization_mode -- The desired data normalization mode''' self.base = BrokerageModelSecurityInitializer(brokerage_model, security_seeder) self.data_normalization_mode = data_normalization_mode def initialize(self, security): '''Initializes the specified security by setting up the models security -- The security to be initialized seed_security -- True to seed the security, false otherwise''' # first call the default implementation self.base.initialize(security) # now apply our data normalization mode security.set_data_normalization_mode(self.data_normalization_mode) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Demonstration algorithm of time in force order settings.
```python from AlgorithmImports import * class TimeInForceAlgorithm(QCAlgorithm): # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. def initialize(self): self.set_start_date(2013,10,7) self.set_end_date(2013,10,11) self.set_cash(100000) # The default time in force setting for all orders is GoodTilCancelled (GTC), # uncomment this line to set a different time in force. # We currently only support GTC and DAY. # self.default_order_properties.time_in_force = TimeInForce.day self._symbol = self.add_equity("SPY", Resolution.MINUTE).symbol self._gtc_order_ticket1 = None self._gtc_order_ticket2 = None self._day_order_ticket1 = None self._day_order_ticket2 = None self._gtd_order_ticket1 = None self._gtd_order_ticket2 = None self._expected_order_statuses = {} # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. # Arguments: # data: Slice object keyed by symbol containing the stock data def on_data(self, data): if not self._gtc_order_ticket1: # These GTC orders will never expire and will not be canceled automatically. self.default_order_properties.time_in_force = TimeInForce.GOOD_TIL_CANCELED # this order will not be filled before the end of the backtest self._gtc_order_ticket1 = self.limit_order(self._symbol, 10, 100) self._expected_order_statuses[self._gtc_order_ticket1.order_id] = OrderStatus.SUBMITTED # this order will be filled before the end of the backtest self._gtc_order_ticket2 = self.limit_order(self._symbol, 10, 160) self._expected_order_statuses[self._gtc_order_ticket2.order_id] = OrderStatus.FILLED if not self._day_order_ticket1: # These DAY orders will expire at market close, # if not filled by then they will be canceled automatically. self.default_order_properties.time_in_force = TimeInForce.DAY # this order will not be filled before market close and will be canceled self._day_order_ticket1 = self.limit_order(self._symbol, 10, 140) self._expected_order_statuses[self._day_order_ticket1.order_id] = OrderStatus.CANCELED # this order will be filled before market close self._day_order_ticket2 = self.limit_order(self._symbol, 10, 180) self._expected_order_statuses[self._day_order_ticket2.order_id] = OrderStatus.FILLED if not self._gtd_order_ticket1: # These GTD orders will expire on October 10th at market close, # if not filled by then they will be canceled automatically. self.default_order_properties.time_in_force = TimeInForce.GOOD_TIL_DATE(datetime(2013, 10, 10)) # this order will not be filled before expiry and will be canceled self._gtd_order_ticket1 = self.limit_order(self._symbol, 10, 100) self._expected_order_statuses[self._gtd_order_ticket1.order_id] = OrderStatus.CANCELED # this order will be filled before expiry self._gtd_order_ticket2 = self.limit_order(self._symbol, 10, 160) self._expected_order_statuses[self._gtd_order_ticket2.order_id] = OrderStatus.FILLED # Order event handler. This handler will be called for all order events, including submissions, fills, cancellations. # This method can be called asynchronously, ensure you use proper locks on thread-unsafe objects def on_order_event(self, orderEvent): self.debug(f"{self.time} {orderEvent}") # End of algorithm run event handler. This method is called at the end of a backtest or live trading operation. def on_end_of_algorithm(self): for orderId, expectedStatus in self._expected_order_statuses.items(): order = self.transactions.get_order_by_id(orderId) if order.status != expectedStatus: raise AssertionError(f"Invalid status for order {orderId} - Expected: {expectedStatus}, actual: {order.status}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Black-Litterman framework algorithm Uses the HistoricalReturnsAlphaModel and the BlackLittermanPortfolioConstructionModel to create an algorithm that rebalances the portfolio according to Black-Litterman portfolio optimization
```python from AlgorithmImports import * from Alphas.HistoricalReturnsAlphaModel import HistoricalReturnsAlphaModel from Portfolio.BlackLittermanOptimizationPortfolioConstructionModel import * from Portfolio.UnconstrainedMeanVariancePortfolioOptimizer import UnconstrainedMeanVariancePortfolioOptimizer from Risk.NullRiskManagementModel import NullRiskManagementModel class BlackLittermanPortfolioOptimizationFrameworkAlgorithm(QCAlgorithm): '''Black-Litterman Optimization algorithm.''' def initialize(self): # Set requested data resolution self.universe_settings.resolution = Resolution.MINUTE # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees. # Commented so regression algorithm is more sensitive #self.settings.minimum_order_margin_portfolio_percentage = 0.005 self.set_start_date(2013,10,7) #Set Start Date self.set_end_date(2013,10,11) #Set End Date self.set_cash(100000) #Set Strategy Cash self._symbols = [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in [ 'AIG', 'BAC', 'IBM', 'SPY' ] ] optimizer = UnconstrainedMeanVariancePortfolioOptimizer() # set algorithm framework models self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selector)) self.set_alpha(HistoricalReturnsAlphaModel(resolution = Resolution.DAILY)) self.set_portfolio_construction(BlackLittermanOptimizationPortfolioConstructionModel(optimizer = optimizer)) self.set_execution(ImmediateExecutionModel()) self.set_risk_management(NullRiskManagementModel()) def coarse_selector(self, coarse): # Drops SPY after the 8th last = 3 if self.time.day > 8 else len(self._symbols) return self._symbols[0:last] def on_order_event(self, order_event): if order_event.status == OrderStatus.FILLED: self.debug(order_event) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering. This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture. All orders are sent from the brokerage, none of them will be placed by the algorithm.
```python from AlgorithmImports import * class CustomBrokerageSideOrderHandlingRegressionAlgorithm(QCAlgorithm): '''Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering. This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture. All orders are sent from the brokerage, none of them will be placed by the algorithm.''' def initialize(self): self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.set_cash(100000) self.set_brokerage_message_handler(CustomBrokerageMessageHandler(self)) self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA) def on_end_of_algorithm(self): # The security should have been added if not self.securities.contains_key(self._spy): raise AssertionError("Expected security to have been added") if self.transactions.orders_count == 0: raise AssertionError("Expected orders to be added from brokerage side") if len(list(self.portfolio.positions.groups)) != 1: raise AssertionError("Expected only one position") class CustomBrokerageMessageHandler(DefaultBrokerageMessageHandler): def __init__(self, algorithm): self._algorithm = algorithm def handle_message(self, message): self._algorithm.debug(f"{self._algorithm.time} Event: {message.message}") def handle_order(self, event_args): order = event_args.order if order.tag is None or not order.tag.isdigit(): raise AssertionError("Expected all new brokerage-side orders to have a valid tag") # We will only process orders with even tags return int(order.tag) % 2 == 0 ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Demonstration of how to chain a coarse and fine universe selection with an option chain universe selection model that will add and remove an'OptionChainUniverse' for each symbol selected on fine
```python from AlgorithmImports import * class CoarseFineOptionUniverseChainRegressionAlgorithm(QCAlgorithm): def initialize(self) -> None: '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2014,6,4) # TWX is selected the 4th and 5th and aapl after that. # If the algo ends on the 6th, TWX subscriptions will not be removed before OnEndOfAlgorithm is called: # - 6th: AAPL is selected, TWX is removed but subscriptions are not removed because the securities are invested. # - TWX and its options are liquidated. # - 7th: Since options universe selection is daily now, TWX subscriptions are removed the next day (7th) self.set_end_date(2014,6,7) self.universe_settings.resolution = Resolution.MINUTE self._twx = Symbol.create("TWX", SecurityType.EQUITY, Market.USA) self._aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA) self._last_equity_added = None self._changes = SecurityChanges.NONE self._option_count = 0 universe = self.add_universe(self.coarse_selection_function, self.fine_selection_function) self.add_universe_options(universe, self.option_filter_function) def option_filter_function(self, universe: OptionFilterUniverse) -> OptionFilterUniverse: universe.include_weeklys().front_month() contracts = list() for contract in universe: if len(contracts) == 5: break contracts.append(contract) return universe.contracts(contracts) def coarse_selection_function(self, coarse: list[CoarseFundamental]) -> list[Symbol]: if self.time <= datetime(2014,6,5): return [ self._twx ] return [ self._aapl ] def fine_selection_function(self, fine: list[FineFundamental]) -> list[Symbol]: if self.time <= datetime(2014,6,5): return [ self._twx ] return [ self._aapl ] def on_data(self, data: Slice) -> None: if self._changes == SecurityChanges.NONE or any(security.price == 0 for security in self._changes.added_securities): return # liquidate removed securities for security in self._changes.removed_securities: if security.invested: self.liquidate(security.symbol) for security in self._changes.added_securities: if not security.symbol.has_underlying: self._last_equity_added = security.symbol else: # options added should all match prev added security if security.symbol.underlying != self._last_equity_added: raise ValueError(f"Unexpected symbol added {security.symbol}") self._option_count += 1 self.set_holdings(security.symbol, 0.05) self._changes = SecurityChanges.NONE # this event fires whenever we have changes to our universe def on_securities_changed(self, changes: SecurityChanges) -> None: if self._changes == SecurityChanges.NONE: self._changes = changes return self._changes = self._changes + changes def on_end_of_algorithm(self) -> None: if self._option_count == 0: raise ValueError("Option universe chain did not add any option!") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Expiry Helper algorithm uses Expiry helper class in an Alpha Model
```python from AlgorithmImports import * class ExpiryHelperAlphaModelFrameworkAlgorithm(QCAlgorithm): '''Expiry Helper framework algorithm uses Expiry helper class in an Alpha Model''' def initialize(self) -> None: ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' # Set requested data resolution self.universe_settings.resolution = Resolution.HOUR self.set_start_date(2013,10,7) #Set Start Date self.set_end_date(2014,1,1) #Set End Date self.set_cash(100000) #Set Strategy Cash symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ] # set algorithm framework models self.set_universe_selection(ManualUniverseSelectionModel(symbols)) self.set_alpha(self.ExpiryHelperAlphaModel()) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) self.set_execution(ImmediateExecutionModel()) self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01)) self.insights_generated += self.on_insights_generated def on_insights_generated(self, s: IAlgorithm, e: GeneratedInsightsCollection) -> None: for insight in e.insights: self.log(f"{e.date_time_utc.isoweekday()}: Close Time {insight.close_time_utc} {insight.close_time_utc.isoweekday()}") class ExpiryHelperAlphaModel(AlphaModel): _next_update = None _direction = InsightDirection.UP def update(self, algorithm: QCAlgorithm, data: Slice) -> list[Insight]: if self._next_update and self._next_update > algorithm.time: return [] expiry = Expiry.END_OF_DAY # Use the Expiry helper to calculate a date/time in the future self._next_update = expiry(algorithm.time) weekday = algorithm.time.isoweekday() insights = [] for symbol in data.bars.keys(): # Expected CloseTime: next month on the same day and time if weekday == 1: insights.append(Insight.price(symbol, Expiry.ONE_MONTH, self._direction)) # Expected CloseTime: next month on the 1st at market open time elif weekday == 2: insights.append(Insight.price(symbol, Expiry.END_OF_MONTH, self._direction)) # Expected CloseTime: next Monday at market open time elif weekday == 3: insights.append(Insight.price(symbol, Expiry.END_OF_WEEK, self._direction)) # Expected CloseTime: next day (Friday) at market open time elif weekday == 4: insights.append(Insight.price(symbol, Expiry.END_OF_DAY, self._direction)) return insights ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm that validates that when using a continuous future (without a filter) the option chains are correctly populated using the mapped symbol.
```python from AlgorithmImports import * class FutureOptionContinuousFutureRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2020, 1, 4) self.set_end_date(2020, 1, 8) self.future = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, Market.CME) self.set_filter() self.add_future_option(self.future.symbol, lambda universe: universe.strikes(-1, 1)) self._has_any_option_chain_for_mapped_symbol = False def set_filter(self): """Set future filter - override in derived classes for filtered version""" pass def on_data(self, slice: Slice): if len(slice.option_chains) == 0: return self.validate_option_chains(slice) # OptionChain for mapped symbol chain = slice.option_chains[self.future.mapped] if chain is None or not any(chain): raise RegressionTestException("No option chain found for mapped symbol during algorithm execution") # Mark that we successfully received a non-empty OptionChain for mapped symbol self._has_any_option_chain_for_mapped_symbol = True def validate_option_chains(self, slice: Slice): if len(slice.option_chains) != 1: raise RegressionTestException("Expected only one option chain for the mapped symbol") def on_end_of_algorithm(self): if not self._has_any_option_chain_for_mapped_symbol: raise RegressionTestException("No non-empty option chain found for mapped symbol during algorithm execution") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Custom data universe selection regression algorithm asserting it's behavior. See GH issue #6396
```python from AlgorithmImports import * class CustomDataUniverseRegressionAlgorithm(QCAlgorithm): def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2014, 3, 24) self.set_end_date(2014, 3, 31) self.current_underlying_symbols = set() self.universe_settings.resolution = Resolution.DAILY self.add_universe(CoarseFundamental, "custom-data-universe", self.selection) self._selection_time = [datetime(2014, 3, 24), datetime(2014, 3, 25), datetime(2014, 3, 26), datetime(2014, 3, 27), datetime(2014, 3, 28), datetime(2014, 3, 29)] def selection(self, coarse): self.debug(f"Universe selection called: {self.time} Count: {len(coarse)}") expected_time = self._selection_time.pop(0) if expected_time != self.time: raise ValueError(f"Unexpected selection time {self.time} expected {expected_time}") # sort descending by daily dollar volume sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True) # return the symbol objects of the top entries from our sorted collection underlying_symbols = [ x.symbol for x in sorted_by_dollar_volume[:10] ] custom_symbols = [] for symbol in underlying_symbols: custom_symbols.append(Symbol.create_base(MyPyCustomData, symbol)) return underlying_symbols + custom_symbols def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' if not self.portfolio.invested: custom_data = data.get(MyPyCustomData) if len(custom_data) > 0: for symbol in sorted(self.current_underlying_symbols, key=lambda x: x.id.symbol): if not self.securities[symbol].has_data: continue self.set_holdings(symbol, 1 / len(self.current_underlying_symbols)) if len([x for x in custom_data.keys() if x.underlying == symbol]) == 0: raise ValueError(f"Custom data was not found for symbol {symbol}") def on_end_of_algorithm(self): if len(self._selection_time) != 0: raise ValueError(f"Unexpected selection times, missing {len(self._selection_time)}") def OnSecuritiesChanged(self, changes): for security in changes.AddedSecurities: if security.symbol.security_type == SecurityType.BASE: continue self.current_underlying_symbols.add(security.Symbol) for security in changes.RemovedSecurities: if security.symbol.security_type == SecurityType.BASE: continue self.current_underlying_symbols.remove(security.Symbol) class MyPyCustomData(PythonData): def get_source(self, config, date, is_live_mode): source = f"{Globals.data_folder}/equity/usa/daily/{LeanData.generate_zip_file_name(config.symbol, date, config.resolution, config.tick_type)}" return SubscriptionDataSource(source) def reader(self, config, line, date, is_live_mode): csv = line.split(',') _scaleFactor = 1 / 10000 custom = MyPyCustomData() custom.symbol = config.symbol custom.time = datetime.strptime(csv[0], '%Y%m%d %H:%M') custom.open = float(csv[1]) * _scaleFactor custom.high = float(csv[2]) * _scaleFactor custom.low = float(csv[3]) * _scaleFactor custom.close = float(csv[4]) * _scaleFactor custom.value = float(csv[4]) * _scaleFactor custom.period = Time.ONE_DAY custom.end_time = custom.time + custom.period return custom ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Basic template framework algorithm uses framework components to define the algorithm. Liquid ETF Competition template
```python from AlgorithmImports import * from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel from Execution.ImmediateExecutionModel import ImmediateExecutionModel class LiquidETFUniverseFrameworkAlgorithm(QCAlgorithm): '''Basic template framework algorithm uses framework components to define the algorithm.''' def initialize(self): # Set Start Date so that backtest has 5+ years of data self.set_start_date(2014, 11, 1) # No need to set End Date as the final submission will be tested # up until the review date # Set $1m Strategy Cash to trade significant AUM self.set_cash(1000000) # Add a relevant benchmark, with the default being SPY self.set_benchmark('SPY') # Use the Alpha Streams Brokerage Model, developed in conjunction with # funds to model their actual fees, costs, etc. # Please do not add any additional reality modelling, such as Slippage, Fees, Buying Power, etc. self.set_brokerage_model(AlphaStreamsBrokerageModel()) # Use the LiquidETFUniverse with minute-resolution data self.universe_settings.resolution = Resolution.MINUTE self.set_universe_selection(LiquidETFUniverse()) # Optional self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) self.set_execution(ImmediateExecutionModel()) # List of symbols we want to trade. Set it in OnSecuritiesChanged self._symbols = [] def on_data(self, slice): if all([self.portfolio[x].invested for x in self._symbols]): return # Emit insights insights = [Insight.price(x, timedelta(1), InsightDirection.UP) for x in self._symbols if self.securities[x].price > 0] if len(insights) > 0: self.emit_insights(insights) def on_securities_changed(self, changes): # Set symbols as the Inverse Energy ETFs for security in changes.added_securities: if security.symbol in LiquidETFUniverse.ENERGY.inverse: self._symbols.append(security.symbol) # Print out the information about the groups self.log(f'Energy: {LiquidETFUniverse.ENERGY}') self.log(f'Metals: {LiquidETFUniverse.METALS}') self.log(f'Technology: {LiquidETFUniverse.TECHNOLOGY}') self.log(f'Treasuries: {LiquidETFUniverse.TREASURIES}') self.log(f'Volatility: {LiquidETFUniverse.VOLATILITY}') self.log(f'SP500Sectors: {LiquidETFUniverse.SP_500_SECTORS}') ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Show cases how to use the CompositeRiskManagementModel.
```python from AlgorithmImports import * class CompositeRiskManagementModelFrameworkAlgorithm(QCAlgorithm): '''Show cases how to use the CompositeRiskManagementModel.''' def initialize(self): # Set requested data resolution self.universe_settings.resolution = Resolution.MINUTE self.set_start_date(2013,10,7) #Set Start Date self.set_end_date(2013,10,11) #Set End Date self.set_cash(100000) #Set Strategy Cash # set algorithm framework models self.set_universe_selection(ManualUniverseSelectionModel([Symbol.create("SPY", SecurityType.EQUITY, Market.USA)])) self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None)) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) self.set_execution(ImmediateExecutionModel()) # define risk management model as a composite of several risk management models self.set_risk_management(CompositeRiskManagementModel( MaximumUnrealizedProfitPercentPerSecurity(0.01), MaximumDrawdownPercentPerSecurity(0.01) )) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Framework algorithm that uses the G10CurrencySelectionModel, a Universe Selection Model that inherits from ManualUniverseSelectionModel
```python from AlgorithmImports import * from Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel class G10CurrencySelectionModel(ManualUniverseSelectionModel): '''Provides an implementation of IUniverseSelectionModel that simply subscribes to G10 currencies''' def __init__(self): '''Initializes a new instance of the G10CurrencySelectionModel class using the algorithm's security initializer and universe settings''' super().__init__([Symbol.create(x, SecurityType.FOREX, Market.OANDA) for x in [ "EURUSD", "GBPUSD", "USDJPY", "AUDUSD", "NZDUSD", "USDCAD", "USDCHF", "USDNOK", "USDSEK" ]]) class G10CurrencySelectionModelFrameworkAlgorithm(QCAlgorithm): '''Framework algorithm that uses the G10CurrencySelectionModel, a Universe Selection Model that inherits from ManualUniverseSelectionMode''' def initialize(self): ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' # Set requested data resolution self.universe_settings.resolution = Resolution.MINUTE self.set_start_date(2013,10,7) #Set Start Date self.set_end_date(2013,10,11) #Set End Date self.set_cash(100000) #Set Strategy Cash # set algorithm framework models self.set_universe_selection(G10CurrencySelectionModel()) self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None)) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) self.set_execution(ImmediateExecutionModel()) self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01)) def on_order_event(self, order_event): if order_event.status == OrderStatus.FILLED: self.debug("Purchased Stock: {0}".format(order_event.symbol)) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Example algorithm of using MeanReversionPortfolioConstructionModel
```python from AlgorithmImports import * from Portfolio.MeanReversionPortfolioConstructionModel import * class MeanReversionPortfolioAlgorithm(QCAlgorithm): '''Example algorithm of using MeanReversionPortfolioConstructionModel''' def initialize(self): # Set starting date, cash and ending date of the backtest self.set_start_date(2020, 9, 1) self.set_end_date(2021, 2, 28) self.set_cash(100000) self.set_security_initializer(lambda security: security.set_market_price(self.get_last_known_price(security))) # Subscribe to data of the selected stocks self._symbols = [self.add_equity(ticker, Resolution.DAILY).symbol for ticker in ["SPY", "AAPL"]] self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1))) self.set_portfolio_construction(MeanReversionPortfolioConstructionModel()) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests In The Money (ITM) future option calls across different strike prices. We expect 6 orders from the algorithm, which are: * (1) Initial entry, buy ES Call Option (ES19M20 expiring ITM) * (2) Initial entry, sell ES Call Option at different strike (ES20H20 expiring ITM) * [2] Option assignment, opens a position in the underlying (ES20H20, Qty: -1) * [2] Future contract liquidation, due to impending expiry * [1] Option exercise, receive 1 ES19M20 future contract * [1] Liquidate ES19M20 contract, due to expiry Additionally, we test delistings for future options and assert that our portfolio holdings reflect the orders the algorithm has submitted.
```python from AlgorithmImports import * class FutureOptionBuySellCallIntradayRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2020, 1, 5) self.set_end_date(2020, 6, 30) self.es20h20 = self.add_future_contract( Symbol.create_future( Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 3, 20) ), Resolution.MINUTE).symbol self.es19m20 = self.add_future_contract( Symbol.create_future( Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 6, 19) ), Resolution.MINUTE).symbol # Select a future option expiring ITM, and adds it to the algorithm. self.es_options = [ self.add_future_option_contract(i, Resolution.MINUTE).symbol for i in (list(self.option_chain(self.es19m20)) + list(self.option_chain(self.es20h20))) if i.id.strike_price == 3200.0 and i.id.option_right == OptionRight.CALL ] self.expected_contracts = [ Symbol.create_option(self.es20h20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200.0, datetime(2020, 3, 20)), Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200.0, datetime(2020, 6, 19)) ] for es_option in self.es_options: if es_option not in self.expected_contracts: raise AssertionError(f"Contract {es_option} was not found in the chain") self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.schedule_callback_buy) def schedule_callback_buy(self): self.market_order(self.es_options[0], 1) self.market_order(self.es_options[1], -1) def on_end_of_algorithm(self): if self.portfolio.invested: raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Strategy example using a portfolio of ETF Global Rotation
```python from AlgorithmImports import * class ETFGlobalRotationAlgorithm(QCAlgorithm): def initialize(self): self.set_cash(25000) self.set_start_date(2007,1,1) self.last_rotation_time = datetime.min self.rotation_interval = timedelta(days=30) self.first = True # these are the growth symbols we'll rotate through growth_symbols =["MDY", # US S&P mid cap 400 "IEV", # i_shares S&P europe 350 "EEM", # i_shared MSCI emerging markets "ILF", # i_shares S&P latin america "EPP" ] # i_shared MSCI Pacific ex-Japan # these are the safety symbols we go to when things are looking bad for growth safety_symbols = ["EDV", "SHY"] # "EDV" Vangaurd TSY 25yr, "SHY" Barclays Low Duration TSY # we'll hold some computed data in these guys self.symbol_data = [] for symbol in list(set(growth_symbols) | set(safety_symbols)): self.add_security(SecurityType.EQUITY, symbol, Resolution.MINUTE) self.one_month_performance = self.mom(symbol, 30, Resolution.DAILY) self.three_month_performance = self.mom(symbol, 90, Resolution.DAILY) self.symbol_data.append((symbol, self.one_month_performance, self.three_month_performance)) def on_data(self, data): # the first time we come through here we'll need to do some things such as allocation # and initializing our symbol data if self.first: self.first = False self.last_rotation_time = self.time return delta = self.time - self.last_rotation_time if delta > self.rotation_interval: self.last_rotation_time = self.time ordered_obj_scores = sorted(self.symbol_data, key=lambda x: Score(x[1].current.value,x[2].current.value).objective_score(), reverse=True) for x in ordered_obj_scores: self.log(">>SCORE>>" + x[0] + ">>" + str(Score(x[1].current.value,x[2].current.value).objective_score())) # pick which one is best from growth and safety symbols best_growth = ordered_obj_scores[0] if Score(best_growth[1].current.value,best_growth[2].current.value).objective_score() > 0: if (self.portfolio[best_growth[0]].quantity == 0): self.log("PREBUY>>LIQUIDATE>>") self.liquidate() self.log(">>BUY>>" + str(best_growth[0]) + "@" + str(100 * best_growth[1].current.value)) qty = self.portfolio.margin_remaining / self.securities[best_growth[0]].close self.market_order(best_growth[0], int(qty)) else: # if no one has a good objective score then let's hold cash this month to be safe self.log(">>LIQUIDATE>>CASH") self.liquidate() class Score(object): def __init__(self,one_month_performance_value,three_month_performance_value): self.one_month_performance = one_month_performance_value self.three_month_performance = three_month_performance_value def objective_score(self): weight1 = 100 weight2 = 75 return (weight1 * self.one_month_performance + weight2 * self.three_month_performance) / (weight1 + weight2) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm illustrating the usage of the <see cref="QCAlgorithm.FuturesChain(Symbol, bool)"/> method to get a future chain.
```python from AlgorithmImports import * class FuturesChainFullDataRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 7) future = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE).symbol chain = self.futures_chain(future, flatten=True) # Demonstration using data frame: df = chain.data_frame for index, row in df.iterrows(): if row['bidprice'] == 0 and row['askprice'] == 0 and row['volume'] == 0: raise AssertionError("FuturesChain() returned contract with no data."); # Get contracts expiring within 6 months, with the latest expiration date, and lowest price contracts = df.loc[(df.expiry <= self.time + timedelta(days=180))] contracts = contracts.sort_values(['expiry', 'lastprice'], ascending=[False, True]) self._future_contract = contracts.index[0] self.add_future_contract(self._future_contract) def on_data(self, data): # Do some trading with the selected contract for sample purposes if not self.portfolio.invested: self.set_holdings(self._future_contract, 0.5) else: self.liquidate() ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm to test we can specify a custom brokerage model, and override some of its methods
```python from AlgorithmImports import * class CustomBrokerageModelRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013,10,7) self.set_end_date(2013,10,11) self.set_brokerage_model(CustomBrokerageModel()) self.add_equity("SPY", Resolution.DAILY) self.add_equity("AIG", Resolution.DAILY) self.update_request_submitted = False if self.brokerage_model.default_markets[SecurityType.EQUITY] != Market.USA: raise AssertionError(f"The default market for Equity should be {Market.USA}") if self.brokerage_model.default_markets[SecurityType.CRYPTO] != Market.BINANCE: raise AssertionError(f"The default market for Crypto should be {Market.BINANCE}") def on_data(self, slice): if not self.portfolio.invested: self.market_order("SPY", 100.0) self.aig_ticket = self.market_order("AIG", 100.0) def on_order_event(self, order_event): spy_ticket = self.transactions.get_order_ticket(order_event.order_id) if self.update_request_submitted == False: update_order_fields = UpdateOrderFields() update_order_fields.quantity = spy_ticket.quantity + 10 spy_ticket.update(update_order_fields) self.spy_ticket = spy_ticket self.update_request_submitted = True def on_end_of_algorithm(self): submit_expected_message = "BrokerageModel declared unable to submit order: [2] Information - Code: - Symbol AIG can not be submitted" if self.aig_ticket.submit_request.response.error_message != submit_expected_message: raise AssertionError(f"Order with ID: {self.aig_ticket.order_id} should not have submitted symbol AIG") update_expected_message = "OrderID: 1 Information - Code: - This order can not be updated" if self.spy_ticket.update_requests[0].response.error_message != update_expected_message: raise AssertionError(f"Order with ID: {self.spy_ticket.order_id} should have been updated") class CustomBrokerageModel(DefaultBrokerageModel): default_markets = { SecurityType.EQUITY: Market.USA, SecurityType.CRYPTO : Market.BINANCE } def can_submit_order(self, security: Security, order: Order, message: BrokerageMessageEvent): if security.symbol.value == "AIG": message = BrokerageMessageEvent(BrokerageMessageType.INFORMATION, "", "Symbol AIG can not be submitted") return False, message return True, None def can_update_order(self, security: Security, order: Order, request: UpdateOrderRequest, message: BrokerageMessageEvent): message = BrokerageMessageEvent(BrokerageMessageType.INFORMATION, "", "This order can not be updated") return False, message ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests In The Money (ITM) index option calls across different strike prices. We expect 4* orders from the algorithm, which are: * (1) Initial entry, buy SPX Call Option (SPXF21 expiring ITM) * (2) Initial entry, sell SPX Call Option at different strike (SPXF21 expiring ITM) * [2] Option assignment, settle into cash * [1] Option exercise, settle into cash Additionally, we test delistings for index options and assert that our portfolio holdings reflect the orders the algorithm has submitted. * Assignments are counted as orders
```python from AlgorithmImports import * class IndexOptionBuySellCallIntradayRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2021, 1, 4) self.set_end_date(2021, 1, 31) spx = self.add_index("SPX", Resolution.MINUTE).symbol # Select a index option expiring ITM, and adds it to the algorithm. spx_options = list(sorted([ self.add_index_option_contract(i, Resolution.MINUTE).symbol \ for i in self.option_chain(spx)\ if (i.id.strike_price == 3700 or i.id.strike_price == 3800) and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1], key=lambda x: x.id.strike_price )) expectedContract3700 = Symbol.create_option( spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3700, datetime(2021, 1, 15) ) expectedContract3800 = Symbol.create_option( spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3800, datetime(2021, 1, 15) ) if len(spx_options) != 2: raise AssertionError(f"Expected 2 index options symbols from chain provider, found {spx_options.count}") if spx_options[0] != expectedContract3700: raise AssertionError(f"Contract {expectedContract3700} was not found in the chain, found instead: {spx_options[0]}") if spx_options[1] != expectedContract3800: raise AssertionError(f"Contract {expectedContract3800} was not found in the chain, found instead: {spx_options[1]}") self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(spx, 1), lambda: self.after_market_open_trade(spx_options)) self.schedule.on(self.date_rules.tomorrow, self.time_rules.noon, lambda: self.liquidate()) def after_market_open_trade(self, spx_options): self.market_order(spx_options[0], 1) self.market_order(spx_options[1], -1) ### <summary> ### Ran at the end of the algorithm to ensure the algorithm has no holdings ### </summary> ### <exception cref="Exception">The algorithm has holdings</exception> def on_end_of_algorithm(self): if self.portfolio.invested: raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm demonstrating use of map files with custom data
```python from AlgorithmImports import * class CustomDataUsingMapFileRegressionAlgorithm(QCAlgorithm): def initialize(self): # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. self.set_start_date(2013, 6, 27) self.set_end_date(2013, 7, 2) self.initial_mapping = False self.execution_mapping = False self.foxa = Symbol.create("FOXA", SecurityType.EQUITY, Market.USA) self._symbol = self.add_data(CustomDataUsingMapping, self.foxa).symbol for config in self.subscription_manager.subscription_data_config_service.get_subscription_data_configs(self._symbol): if config.resolution != Resolution.MINUTE: raise ValueError("Expected resolution to be set to Minute") def on_data(self, slice): date = self.time.date() if slice.symbol_changed_events.contains_key(self._symbol): mapping_event = slice.symbol_changed_events[self._symbol] self.log("{0} - Ticker changed from: {1} to {2}".format(str(self.time), mapping_event.old_symbol, mapping_event.new_symbol)) if date == datetime(2013, 6, 27).date(): # we should Not receive the initial mapping event if mapping_event.new_symbol != "NWSA" or mapping_event.old_symbol != "FOXA": raise AssertionError("Unexpected mapping event mapping_event") self.initial_mapping = True if date == datetime(2013, 6, 29).date(): if mapping_event.new_symbol != "FOXA" or mapping_event.old_symbol != "NWSA": raise AssertionError("Unexpected mapping event mapping_event") self.set_holdings(self._symbol, 1) self.execution_mapping = True def on_end_of_algorithm(self): if self.initial_mapping: raise AssertionError("The ticker generated the initial rename event") if not self.execution_mapping: raise AssertionError("The ticker did not rename throughout the course of its life even though it should have") class CustomDataUsingMapping(PythonData): '''Test example custom data showing how to enable the use of mapping. Implemented as a wrapper of existing NWSA->FOXA equity''' def get_source(self, config, date, is_live_mode): return TradeBar().get_source(SubscriptionDataConfig(config, CustomDataUsingMapping, # create a new symbol as equity so we find the existing data files Symbol.create(config.mapped_symbol, SecurityType.EQUITY, config.market)), date, is_live_mode) def reader(self, config, line, date, is_live_mode): return TradeBar.parse_equity(config, line, date) def requires_mapping(self): '''True indicates mapping should be done''' return True def is_sparse_data(self): '''Indicates that the data set is expected to be sparse''' return True def default_resolution(self): '''Gets the default resolution for this data and security type''' return Resolution.MINUTE def supported_resolutions(self): '''Gets the supported resolution for this data and security type''' return [ Resolution.MINUTE ] ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : A demonstration algorithm to check there can be placed an order of a pair not present in the brokerage using the conversion between stablecoins
```python from AlgorithmImports import * class StableCoinsRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2018, 5, 1) self.set_end_date(2018, 5, 2) self.set_cash("USDT", 200000000) self.set_brokerage_model(BrokerageName.BINANCE, AccountType.CASH) self.add_crypto("BTCUSDT", Resolution.HOUR, Market.BINANCE) def on_data(self, data): if not self.portfolio.invested: self.set_holdings("BTCUSDT", 1) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Adds a universe with a custom data type and retrieves historical data while preserving the custom data type.
```python from datetime import timedelta from AlgorithmImports import * class PersistentCustomDataUniverseRegressionAlgorithm(QCAlgorithm): def Initialize(self): self.set_start_date(2018, 6, 1) self.set_end_date(2018, 6, 19) universe = self.add_universe(StockDataSource, "my-stock-data-source", Resolution.DAILY, self.universe_selector) self._universe_symbol = universe.symbol self.retrieve_historical_data() self._data_received = False def universe_selector(self, data): return [x.symbol for x in data] def retrieve_historical_data(self): history = list(self.history[StockDataSource](self._universe_symbol, datetime(2018, 1, 1), datetime(2018, 6, 1), Resolution.DAILY)) if (len(history) == 0): raise AssertionError(f"No historical data received for symbol {self._universe_symbol}.") # Ensure all values are of type StockDataSource for item in history: if not isinstance(item, StockDataSource): raise AssertionError(f"Unexpected data type in history. Expected StockDataSource but received {type(item).__name__}.") def OnData(self, slice: Slice): if self._universe_symbol not in slice: raise AssertionError(f"No data received for the universe symbol: {self._universe_symbol}.") if (not self._data_received): self.retrieve_historical_data() self._data_received = True def OnEndOfAlgorithm(self) -> None: if not self._data_received: raise AssertionError("No data was received after the universe selection.") class StockDataSource(PythonData): def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live: bool) -> SubscriptionDataSource: source = "../../../Tests/TestData/daily-stock-picker-backtest.csv" return SubscriptionDataSource(source) def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live: bool) -> BaseData: if not (line.strip() and line[0].isdigit()): return None stocks = StockDataSource() stocks.symbol = config.symbol try: csv = line.split(',') stocks.time = datetime.strptime(csv[0], "%Y%m%d") stocks.end_time = stocks.time + self.period stocks["Symbols"] = csv[1:] except ValueError: return None return stocks @property def period(self) -> timedelta: return timedelta(days=1) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Algorithm asserting that when setting custom models for canonical securities, a one-time warning is sent informing the user that the contracts models are different (not the custom ones).
```python from AlgorithmImports import * class OptionModelsConsistencyRegressionAlgorithm(QCAlgorithm): def initialize(self) -> None: security = self.initialize_algorithm() self.set_models(security) # Using a custom security initializer derived from BrokerageModelSecurityInitializer # to check that the models are correctly set in the security even when the # security initializer is derived from said class in Python self.set_security_initializer(CustomSecurityInitializer(self.brokerage_model, SecuritySeeder.NULL)) self.set_benchmark(lambda x: 0) def initialize_algorithm(self) -> Security: self.set_start_date(2015, 12, 24) self.set_end_date(2015, 12, 24) equity = self.add_equity("GOOG", leverage=4) option = self.add_option(equity.symbol) option.set_filter(lambda u: u.strikes(-2, +2).expiration(0, 180)) return option def set_models(self, security: Security) -> None: security.set_fill_model(CustomFillModel()) security.set_fee_model(CustomFeeModel()) security.set_buying_power_model(CustomBuyingPowerModel()) security.set_slippage_model(CustomSlippageModel()) security.set_volatility_model(CustomVolatilityModel()) class CustomSecurityInitializer(BrokerageModelSecurityInitializer): def __init__(self, brokerage_model: IBrokerageModel, security_seeder: ISecuritySeeder): super().__init__(brokerage_model, security_seeder) class CustomFillModel(FillModel): pass class CustomFeeModel(FeeModel): pass class CustomBuyingPowerModel(BuyingPowerModel): pass class CustomSlippageModel(ConstantSlippageModel): def __init__(self): super().__init__(0) class CustomVolatilityModel(BaseVolatilityModel): pass ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Basic algorithm demonstrating how to place LimitIfTouched orders.
```python from AlgorithmImports import * from collections import deque class LimitIfTouchedRegressionAlgorithm(QCAlgorithm): asynchronous_orders = False def initialize(self): self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.set_cash(100000) self.add_equity("SPY") self.expected_events = deque([ "Time: 10/10/2013 13:31:00 OrderID: 72 EventID: 399 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: $144.6434 LimitPrice: $144.3551 TriggerPrice: $143.61 OrderFee: 1 USD", "Time: 10/10/2013 15:57:00 OrderID: 73 EventID: 156 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: $145.6636 LimitPrice: $145.6434 TriggerPrice: $144.89 OrderFee: 1 USD", "Time: 10/11/2013 15:37:00 OrderID: 74 EventID: 380 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: $146.7185 LimitPrice: $146.6723 TriggerPrice: $145.92 OrderFee: 1 USD" ]) def on_data(self, data): if data.contains_key("SPY"): if len(self.transactions.get_open_orders()) == 0: self._negative = 1 if self.time.day < 9 else -1 order_request = SubmitOrderRequest(OrderType.LIMIT_IF_TOUCHED, SecurityType.EQUITY, "SPY", self._negative * 10, 0, data["SPY"].price - self._negative, data["SPY"].price - 0.25 * self._negative, self.utc_time, f"LIT - Quantity: {self._negative * 10}", asynchronous=self.asynchronous_orders) self._request = self.transactions.add_order(order_request) return if self._request is not None: if self._request.quantity == 1: self.transactions.cancel_open_orders() self._request = None return new_quantity = int(self._request.quantity - self._negative) self._request.update_quantity(new_quantity, f"LIT - Quantity: {new_quantity}") self._request.update_trigger_price(Extensions.round_to_significant_digits(self._request.get(OrderField.TRIGGER_PRICE), 5)) def on_order_event(self, order_event): if order_event.status == OrderStatus.FILLED: expected = self.expected_events.popleft() if str(order_event) != expected: raise AssertionError(f"order_event {order_event.id} differed from {expected}. Actual {order_event}") def on_end_of_algorithm(self): for ticket in self.transactions.get_order_tickets(): if ticket.submit_request.asynchronous != self.asynchronous_orders: raise AssertionError("Expected all orders to have the same asynchronous flag as the algorithm.") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm is expected to fail and verifies that a training event created in Initialize will get run AND it will cause the algorithm to fail if it exceeds the "algorithm-manager-time-loop-maximum" config value, which the regression test sets to 0.5 minutes.
```python from AlgorithmImports import * from time import sleep class TrainingInitializeRegressionAlgorithm(QCAlgorithm): '''Example algorithm showing how to use QCAlgorithm.train method''' def initialize(self): self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.add_equity("SPY", Resolution.DAILY) # this should cause the algorithm to fail # the regression test sets the time limit to 30 seconds and there's one extra # minute in the bucket, so a two minute sleep should result in RuntimeError self.train(lambda: sleep(150)) # DateRules.tomorrow combined with TimeRules.midnight enforces that this event schedule will # have exactly one time, which will fire between the first data point and the next day at # midnight. So after the first data point, it will run this event and sleep long enough to # exceed the static max algorithm time loop time and begin to consume from the leaky bucket # the regression test sets the "algorithm-manager-time-loop-maximum" value to 30 seconds self.train(self.date_rules.tomorrow, self.time_rules.midnight, lambda: sleep(60)) # this will consume the single 'minute' available in the leaky bucket # and the regression test will confirm that the leaky bucket is empty ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This example demonstrates how to add and trade SPX index weekly options
```python from AlgorithmImports import * class BasicTemplateSPXWeeklyIndexOptionsAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2021, 1, 4) self.set_end_date(2021, 1, 10) self.set_cash(1000000) # regular option SPX contracts self.spx_options = self.add_index_option("SPX") self.spx_options.set_filter(lambda u: (u.strikes(0, 1).expiration(0, 30))) # weekly option SPX contracts spxw = self.add_index_option("SPX", "SPXW") # set our strike/expiry filter for this option chain spxw.set_filter(lambda u: (u.strikes(0, 1) # single week ahead since there are many SPXW contracts and we want to preserve performance .expiration(0, 7) .include_weeklys())) self.spxw_option = spxw.symbol def on_data(self,slice): if self.portfolio.invested: return chain = slice.option_chains.get(self.spxw_option) if not chain: return # we sort the contracts to find at the money (ATM) contract with closest expiration contracts = sorted(sorted(sorted(chain, \ key = lambda x: x.expiry), \ key = lambda x: abs(chain.underlying.price - x.strike)), \ key = lambda x: x.right, reverse=True) # if found, buy until it expires if len(contracts) == 0: return symbol = contracts[0].symbol self.market_order(symbol, 1) def on_order_event(self, order_event): self.debug(str(order_event)) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This example demonstrates how to add options for a given underlying equity security. It also shows how you can prefilter contracts easily based on strikes and expirations, and how you can inspect the option chain to pick a specific option contract to trade.
```python from AlgorithmImports import * class BasicTemplateOptionsDailyAlgorithm(QCAlgorithm): underlying_ticker = "AAPL" def initialize(self): self.set_start_date(2015, 12, 15) self.set_end_date(2016, 2, 1) self.set_cash(100000) self.option_expired = False equity = self.add_equity(self.underlying_ticker, Resolution.DAILY) option = self.add_option(self.underlying_ticker, Resolution.DAILY) self.option_symbol = option.symbol # set our strike/expiry filter for this option chain option.set_filter(lambda u: (u.calls_only().expiration(0, 60))) # use the underlying equity as the benchmark self.set_benchmark(equity.symbol) def on_data(self,slice): if self.portfolio.invested: return chain = slice.option_chains.get(self.option_symbol) if not chain: return # Grab us the contract nearest expiry contracts = sorted(chain, key = lambda x: x.expiry) # if found, trade it if len(contracts) == 0: return symbol = contracts[0].symbol self.market_order(symbol, 1) def on_order_event(self, order_event): self.log(str(order_event)) # Check for our expected OTM option expiry if "OTM" in order_event.message: # Assert it is at midnight 1/16 (5AM UTC) if order_event.utc_time.month != 1 and order_event.utc_time.day != 16 and order_event.utc_time.hour != 5: raise AssertionError(f"Expiry event was not at the correct time, {order_event.utc_time}") self.option_expired = True def on_end_of_algorithm(self): # Assert we had our option expire and fill a liquidation order if not self.option_expired: raise AssertionError("Algorithm did not process the option expiration like expected") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests Out of The Money (OTM) index option expiry for short calls. We expect 2 orders from the algorithm, which are: * Initial entry, sell SPX Call Option (expiring OTM) - Profit the option premium, since the option was not assigned. * Liquidation of SPX call OTM contract on the last trade date Additionally, we test delistings for index options and assert that our portfolio holdings reflect the orders the algorithm has submitted.
```python from AlgorithmImports import * class IndexOptionShortCallOTMExpiryRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2021, 1, 4) self.set_end_date(2021, 1, 31) self.spx = self.add_index("SPX", Resolution.MINUTE).symbol # Select a index option expiring ITM, and adds it to the algorithm. self.spx_options = list(self.option_chain(self.spx)) self.spx_options = [i for i in self.spx_options if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1] self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price, reverse=True))[0] self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.PUT, 3200, datetime(2021, 1, 15)) if self.spx_option != self.expected_contract: raise AssertionError(f"Contract {self.expected_contract} was not found in the chain") self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1)) def on_data(self, data: Slice): # Assert delistings, so that we can make sure that we receive the delisting warnings at # the expected time. These assertions detect bug #4872 for delisting in data.delistings.values(): if delisting.type == DelistingType.WARNING: if delisting.time != datetime(2021, 1, 15): raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}") if delisting.type == DelistingType.DELISTED: if delisting.time != datetime(2021, 1, 16): raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}") def on_order_event(self, order_event: OrderEvent): if order_event.status != OrderStatus.FILLED: # There's lots of noise with OnOrderEvent, but we're only interested in fills. return if order_event.symbol not in self.securities: raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}") security = self.securities[order_event.symbol] if security.symbol == self.spx: raise AssertionError(f"Expected no order events for underlying Symbol {security.symbol}") if security.symbol == self.expected_contract: self.assert_index_option_contract_order(order_event, security) else: raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}") def assert_index_option_contract_order(self, order_event: OrderEvent, option_contract: Security): if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1: raise AssertionError(f"No holdings were created for option contract {option_contract.symbol}") if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0: raise AssertionError("Expected no options holdings after closing position") if order_event.is_assignment: raise AssertionError(f"Assignment was not expected for {order_event.symbol}") ### <summary> ### Ran at the end of the algorithm to ensure the algorithm has no holdings ### </summary> ### <exception cref="Exception">The algorithm has holdings</exception> def on_end_of_algorithm(self): if self.portfolio.invested: raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : def initialize(self) -> None:
```python from AlgorithmImports import * class BasicTemplateIndexAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2021, 1, 4) self.set_end_date(2021, 1, 18) self.set_cash(1000000) # Use indicator for signal; but it cannot be traded self.spx = self.add_index("SPX", Resolution.MINUTE).symbol # Trade on SPX ITM calls self.spx_option = Symbol.create_option( self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3200, datetime(2021, 1, 15) ) self.add_index_option_contract(self.spx_option, Resolution.MINUTE) self.ema_slow = self.ema(self.spx, 80) self.ema_fast = self.ema(self.spx, 200) def on_data(self, data: Slice): if self.spx not in data.bars or self.spx_option not in data.bars: return if not self.ema_slow.is_ready: return if self.ema_fast > self.ema_slow: self.set_holdings(self.spx_option, 1) else: self.liquidate() def on_end_of_algorithm(self) -> None: if self.portfolio[self.spx].total_sale_volume > 0: raise AssertionError("Index is not tradable.") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests In The Money (ITM) index option expiry for calls. We expect 2 orders from the algorithm, which are: * Initial entry, buy SPX Call Option (expiring ITM) * Option exercise, settles into cash Additionally, we test delistings for index options and assert that our portfolio holdings reflect the orders the algorithm has submitted.
```python from AlgorithmImports import * class IndexOptionCallITMExpiryRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2021, 1, 4) self.set_end_date(2021, 1, 31) self.set_cash(100000) self.spx = self.add_index("SPX", Resolution.MINUTE).symbol # Select an index option expiring ITM, and adds it to the algorithm. self.spx_options = list(self.option_chain(self.spx)) self.spx_options = [i for i in self.spx_options if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1] self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price, reverse=True))[0] self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol self.expected_option_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3200, datetime(2021, 1, 15)) if self.spx_option != self.expected_option_contract: raise AssertionError(f"Contract {self.expected_option_contract} was not found in the chain") self.schedule.on( self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, 1) ) def on_data(self, data: Slice): # Assert delistings, so that we can make sure that we receive the delisting warnings at # the expected time. These assertions detect bug #4872 for delisting in data.delistings.values(): if delisting.type == DelistingType.WARNING: if delisting.time != datetime(2021, 1, 15): raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}") if delisting.type == DelistingType.DELISTED: if delisting.time != datetime(2021, 1, 16): raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}") def on_order_event(self, order_event: OrderEvent): if order_event.status != OrderStatus.FILLED: # There's lots of noise with OnOrderEvent, but we're only interested in fills. return if order_event.symbol not in self.securities: raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}") security = self.securities[order_event.symbol] if security.symbol == self.spx: self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_option_contract]) elif security.symbol == self.expected_option_contract: self.assert_index_option_contract_order(order_event, security) else: raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}") self.log(f"{self.time} -- {order_event.symbol} :: Price: {self.securities[order_event.symbol].holdings.price} Qty: {self.securities[order_event.symbol].holdings.quantity} Direction: {order_event.direction} Msg: {order_event.message}") def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security): # No way to detect option exercise orders or any other kind of special orders # other than matching strings, for now. if "Option Exercise" in order_event.message: if order_event.fill_price != 3200: raise AssertionError("Option did not exercise at expected strike price (3200)") if option_contract.holdings.quantity != 0: raise AssertionError(f"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}") def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security): if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1: raise AssertionError(f"No holdings were created for option contract {option.symbol}") if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0: raise AssertionError(f"Holdings were found after a filled option exercise") if "Exercise" in order_event.message and option.holdings.quantity != 0: raise AssertionError(f"Holdings were found after exercising option contract {option.symbol}") ### <summary> ### Ran at the end of the algorithm to ensure the algorithm has no holdings ### </summary> ### <exception cref="Exception">The algorithm has holdings</exception> def on_end_of_algorithm(self): if self.portfolio.invested: raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Basic algorithm using SetAccountCurrency
```python from AlgorithmImports import * class BasicSetAccountCurrencyAlgorithm(QCAlgorithm): def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2018, 4, 4) #Set Start Date self.set_end_date(2018, 4, 4) #Set End Date self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH) self.set_account_currency_and_amount() self._btc_eur = self.add_crypto("BTCEUR").symbol def set_account_currency_and_amount(self): # Before setting any cash or adding a Security call SetAccountCurrency self.set_account_currency("EUR") self.set_cash(100000) #Set Strategy Cash def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' if not self.portfolio.invested: self.set_holdings(self._btc_eur, 1) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Custom data universe selection regression algorithm asserting it's behavior. See GH issue #6396
```python from AlgorithmImports import * class NoUniverseSelectorRegressionAlgorithm(QCAlgorithm): def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2014, 3, 24) self.set_end_date(2014, 3, 31) self.universe_settings.resolution = Resolution.DAILY self.add_universe(CoarseFundamental) self.changes = None def on_data(self, data): # if we have no changes, do nothing if not self.changes: return # liquidate removed securities for security in self.changes.removed_securities: if security.invested: self.liquidate(security.symbol) active_and_with_data_securities = sum(x.value.has_data for x in self.active_securities) # we want 1/N allocation in each security in our universe for security in self.changes.added_securities: if security.has_data: self.set_holdings(security.symbol, 1 / active_and_with_data_securities) self.changes = None def on_securities_changed(self, changes): self.changes = changes ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm asserting we can specify a custom portfolio optimizer with a MeanVarianceOptimizationPortfolioConstructionModel
```python from AlgorithmImports import * from MeanVarianceOptimizationFrameworkAlgorithm import MeanVarianceOptimizationFrameworkAlgorithm class CustomPortfolioOptimizerRegressionAlgorithm(MeanVarianceOptimizationFrameworkAlgorithm): def initialize(self): super().initialize() self.set_portfolio_construction(MeanVarianceOptimizationPortfolioConstructionModel(timedelta(days=1), PortfolioBias.LONG_SHORT, 1, 63, Resolution.DAILY, 0.02, CustomPortfolioOptimizer())) class CustomPortfolioOptimizer: def optimize(self, historical_returns, expected_returns, covariance): return [0.5]*(np.array(historical_returns)).shape[1] ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Basic algorithm demonstrating how to place stop limit orders.
```python from AlgorithmImports import * class StopLimitOrderRegressionAlgorithm(QCAlgorithm): '''Basic algorithm demonstrating how to place stop limit orders.''' tolerance = 0.001 fast_period = 30 slow_period = 60 asynchronous_orders = False def initialize(self): self.set_start_date(2013, 1, 1) self.set_end_date(2017, 1, 1) self.set_cash(100000) self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol self._fast = self.ema(self._symbol, self.fast_period, Resolution.DAILY) self._slow = self.ema(self._symbol, self.slow_period, Resolution.DAILY) self._buy_order_ticket: OrderTicket = None self._sell_order_ticket: OrderTicket = None self._previous_slice: Slice = None def on_data(self, slice: Slice): if not self.is_ready(): return security = self.securities[self._symbol] if self._buy_order_ticket is None and self.trend_is_up(): self._buy_order_ticket = self.stop_limit_order(self._symbol, 100, stop_price=security.high * 1.10, limit_price=security.high * 1.11, asynchronous=self.asynchronous_orders) elif self._buy_order_ticket.status == OrderStatus.FILLED and self._sell_order_ticket is None and self.trend_is_down(): self._sell_order_ticket = self.stop_limit_order(self._symbol, -100, stop_price=security.low * 0.99, limit_price=security.low * 0.98, asynchronous=self.asynchronous_orders) def on_order_event(self, order_event: OrderEvent): if order_event.status == OrderStatus.FILLED: order = self.transactions.get_order_by_id(order_event.order_id) if not order.stop_triggered: raise AssertionError("StopLimitOrder StopTriggered should haven been set if the order filled.") if order_event.direction == OrderDirection.BUY: limit_price = self._buy_order_ticket.get(OrderField.LIMIT_PRICE) if order_event.fill_price > limit_price: raise AssertionError(f"Buy stop limit order should have filled with price less than or equal to the limit price {limit_price}. " f"Fill price: {order_event.fill_price}") else: limit_price = self._sell_order_ticket.get(OrderField.LIMIT_PRICE) if order_event.fill_price < limit_price: raise AssertionError(f"Sell stop limit order should have filled with price greater than or equal to the limit price {limit_price}. " f"Fill price: {order_event.fill_price}") def on_end_of_algorithm(self): for ticket in self.transactions.get_order_tickets(): if ticket.submit_request.asynchronous != self.asynchronous_orders: raise AssertionError("Expected all orders to have the same asynchronous flag as the algorithm.") def is_ready(self): return self._fast.is_ready and self._slow.is_ready def trend_is_up(self): return self.is_ready() and self._fast.current.value > self._slow.current.value * (1 + self.tolerance) def trend_is_down(self): return self.is_ready() and self._fast.current.value < self._slow.current.value * (1 + self.tolerance) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm used to verify that get_data(type) correctly retrieves the latest custom data stored in the security cache.
```python from AlgorithmImports import * from CustomDataRegressionAlgorithm import Bitcoin class CustomDataSecurityCacheGetDataRegressionAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2020,1,5) self.set_end_date(2020,1,10) self.add_data(Bitcoin, "BTC", Resolution.DAILY) seeder = FuncSecuritySeeder(self.get_last_known_prices) self.set_security_initializer(lambda x: seeder.seed_security(x)) def on_data(self, data: Slice) -> None: bitcoin = self.securities['BTC'].cache.get_data(Bitcoin) if bitcoin is None: raise RegressionTestException("Expected Bitcoin data in cache, but none was found") if bitcoin.value == 0: raise RegressionTestException("Expected Bitcoin value to be non-zero") bitcoin_from_slice = list(data.get(Bitcoin).values())[0] if bitcoin_from_slice != bitcoin: raise RegressionTestException("Expected cached Bitcoin to match the one from Slice") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm illustrating the usage of the <see cref="QCAlgorithm.OptionChains(IEnumerable{Symbol})"/> method to get multiple future option chains.
```python from AlgorithmImports import * class FutureOptionChainsMultipleFullDataRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2020, 1, 6) self.set_end_date(2020, 1, 6) es_future_contract = self.add_future_contract( Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 3, 20)), Resolution.MINUTE).symbol gc_future_contract = self.add_future_contract( Symbol.create_future(Futures.Metals.GOLD, Market.COMEX, datetime(2020, 4, 28)), Resolution.MINUTE).symbol chains = self.option_chains([es_future_contract, gc_future_contract], flatten=True) self._es_option_contract = self.get_contract(chains, es_future_contract) self._gc_option_contract = self.get_contract(chains, gc_future_contract) self.add_future_option_contract(self._es_option_contract) self.add_future_option_contract(self._gc_option_contract) def get_contract(self, chains: OptionChains, underlying: Symbol) -> Symbol: df = chains.data_frame # Index by the requested underlying, by getting all data with canonicals which underlying is the requested underlying symbol: canonicals = df.index.get_level_values('canonical') condition = [canonical for canonical in canonicals if canonical.underlying == underlying] contracts = df.loc[condition] # Get contracts expiring within 4 months, with the latest expiration date, highest strike and lowest price contracts = contracts.loc[(df.expiry <= self.time + timedelta(days=120))] contracts = contracts.sort_values(['expiry', 'strike', 'lastprice'], ascending=[False, False, True]) return contracts.index[0][1] def on_data(self, data): # Do some trading with the selected contract for sample purposes if not self.portfolio.invested: self.set_holdings(self._es_option_contract, 0.25) self.set_holdings(self._gc_option_contract, 0.25) else: self.liquidate() ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This algorithm sends a list of portfolio targets to Collective2 API every time the ema indicators crosses between themselves.
```python from AlgorithmImports import * class Collective2SignalExportDemonstrationAlgorithm(QCAlgorithm): def initialize(self): ''' Initialize the date and add all equity symbols present in list _symbols ''' self.set_start_date(2013, 10, 7) #Set Start Date self.set_end_date(2013, 10, 11) #Set End Date self.set_cash(100000) #Set Strategy Cash # Symbols accepted by Collective2. Collective2 accepts stock, future, forex and US stock option symbols self.add_equity("GOOG") self._symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA), Symbol.create("EURUSD", SecurityType.FOREX, Market.OANDA), Symbol.create_future("ES", Market.CME, datetime(2023, 12, 15)), Symbol.create_option("GOOG", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 130, datetime(2023, 9, 1)) ] self.targets = [] # Create a new PortfolioTarget for each symbol, assign it an initial amount of 0.05 and save it in self.targets list for item in self._symbols: symbol = self.add_security(item).symbol if symbol.security_type == SecurityType.EQUITY or symbol.security_type == SecurityType.FOREX: self.targets.append(PortfolioTarget(symbol, 0.05)) else: self.targets.append(PortfolioTarget(symbol, 1)) self.fast = self.ema("SPY", 10) self.slow = self.ema("SPY", 100) # Initialize these flags, to check when the ema indicators crosses between themselves self.ema_fast_is_not_set = True self.ema_fast_was_above = False # Set Collective2 export provider # Collective2 APIv4 KEY: This value is provided by Collective2 in your account section (See https://collective2.com/account-info) # See API documentation at https://trade.collective2.com/c2-api self.collective2_apikey = "YOUR APIV4 KEY" # Collective2 System ID: This value is found beside the system's name (strategy's name) on the main system page self.collective2_system_id = 0 # Disable automatic exports as we manually set them self.signal_export.automatic_export_time_span = None # If using the Collective2 white-label API, you can specify it in the constructor with the optional parameter `use_white_label_api`: # e.g. Collective2SignalExport(self.collective2_apikey, self.collective2_system_id, use_white_label_api=True) # The API url can also be overridden by setting the Destination property: # e.g. Collective2SignalExport(self.collective2_apikey, self.collective2_system_id) { Destination = new Uri("your url") } self.signal_export.add_signal_export_provider(Collective2SignalExport(self.collective2_apikey, self.collective2_system_id)) self.first_call = True self.set_warm_up(100) def on_data(self, data): ''' Reduce the quantity of holdings for one security and increase the holdings to the another one when the EMA's indicators crosses between themselves, then send a signal to Collective2 API ''' if self.is_warming_up: return # Place an order as soon as possible to send a signal. if self.first_call: self.set_holdings("SPY", 0.1) self.targets[0] = PortfolioTarget(self.portfolio["SPY"].symbol, 0.1) self.signal_export.set_target_portfolio(self.targets) self.first_call = False fast = self.fast.current.value slow = self.slow.current.value # Set the value of flag _ema_fast_was_above, to know when the ema indicators crosses between themselves if self.ema_fast_is_not_set == True: if fast > slow *1.001: self.ema_fast_was_above = True else: self.ema_fast_was_above = False self.ema_fast_is_not_set = False # Check whether ema fast and ema slow crosses. If they do, set holdings to SPY # or reduce its holdings, change its value in self.targets list and send signals # to Collective2 API from self.targets if fast > slow * 1.001 and (not self.ema_fast_was_above): self.set_holdings("SPY", 0.1) self.targets[0] = PortfolioTarget(self.portfolio["SPY"].symbol, 0.1) self.signal_export.set_target_portfolio(self.targets) elif fast < slow * 0.999 and (self.ema_fast_was_above): self.set_holdings("SPY", 0.01) self.targets[0] = PortfolioTarget(self.portfolio["SPY"].symbol, 0.01) self.signal_export.set_target_portfolio(self.targets) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm demonstrating how to get order events in custom execution models and asserting that they match the algorithm's order events.
```python from AlgorithmImports import * class ExecutionModelOrderEventsRegressionAlgorithm(QCAlgorithm): def initialize(self): self._order_events = [] self.universe_settings.resolution = Resolution.MINUTE self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.set_cash(100000) self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create("SPY", SecurityType.EQUITY, Market.USA))) self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes=20), 0.025, None)) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY)) self._execution_model = CustomImmediateExecutionModel() self.set_execution(self._execution_model) self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01)) def on_order_event(self, order_event): self._order_events.append(order_event) def on_end_of_algorithm(self): if len(self._execution_model.order_events) != len(self._order_events): raise Exception(f"Order events count mismatch. Execution model: {len(self._execution_model.order_events)}, Algorithm: {len(self._order_events)}") for i, (model_event, algo_event) in enumerate(zip(self._execution_model.order_events, self._order_events)): if (model_event.id != algo_event.id or model_event.order_id != algo_event.order_id or model_event.status != algo_event.status): raise Exception(f"Order event mismatch at index {i}. Execution model: {model_event}, Algorithm: {algo_event}") class CustomImmediateExecutionModel(ExecutionModel): def __init__(self): self._targets_collection = PortfolioTargetCollection() self._order_tickets = {} self.order_events = [] def execute(self, algorithm, targets): self._targets_collection.add_range(targets) if not self._targets_collection.is_empty: for target in self._targets_collection.order_by_margin_impact(algorithm): security = algorithm.securities[target.symbol] # calculate remaining quantity to be ordered quantity = OrderSizing.get_unordered_quantity(algorithm, target, security, True) if (quantity != 0 and BuyingPowerModelExtensions.above_minimum_order_margin_portfolio_percentage(security.buying_power_model, security, quantity, algorithm.portfolio, algorithm.settings.minimum_order_margin_portfolio_percentage)): ticket = algorithm.market_order(security.symbol, quantity, asynchronous=True, tag=target.tag) self._order_tickets[ticket.order_id] = ticket self._targets_collection.clear_fulfilled(algorithm) def on_order_event(self, algorithm, order_event): algorithm.log(f"{algorithm.time} - Order event received: {order_event}") # This method will get events for all orders, but if we save the tickets in Execute we can filter # to process events for orders placed by this model if order_event.order_id in self._order_tickets: ticket = self._order_tickets[order_event.order_id] if order_event.status.is_fill(): algorithm.debug(f"Purchased Stock: {order_event.symbol}") if order_event.status.is_closed(): del self._order_tickets[order_event.order_id] self.order_events.append(order_event) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Basic template algorithm simply initializes the date range and cash. This is a skeleton framework you can use for designing an algorithm.
```python from AlgorithmImports import * class IndicatorSuiteAlgorithm(QCAlgorithm): '''Demonstration algorithm of popular indicators and plotting them.''' def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self._symbol = "SPY" self._symbol2 = "GOOG" self.custom_symbol = "IBM" self.price = 0.0 self.set_start_date(2013, 1, 1) #Set Start Date self.set_end_date(2014, 12, 31) #Set End Date self.set_cash(25000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data self.add_equity(self._symbol, Resolution.DAILY) self.add_equity(self._symbol2, Resolution.DAILY) self.add_data(CustomData, self.custom_symbol, Resolution.DAILY) # Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object) self.indicators = { 'BB' : self.bb(self._symbol, 20, 1, MovingAverageType.SIMPLE, Resolution.DAILY), 'RSI' : self.rsi(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY), 'EMA' : self.ema(self._symbol, 14, Resolution.DAILY), 'SMA' : self.sma(self._symbol, 14, Resolution.DAILY), 'MACD' : self.macd(self._symbol, 12, 26, 9, MovingAverageType.SIMPLE, Resolution.DAILY), 'MOM' : self.mom(self._symbol, 20, Resolution.DAILY), 'MOMP' : self.momp(self._symbol, 20, Resolution.DAILY), 'STD' : self.std(self._symbol, 20, Resolution.DAILY), # by default if the symbol is a tradebar type then it will be the min of the low property 'MIN' : self.min(self._symbol, 14, Resolution.DAILY), # by default if the symbol is a tradebar type then it will be the max of the high property 'MAX' : self.max(self._symbol, 14, Resolution.DAILY), 'ATR' : self.atr(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY), 'AROON' : self.aroon(self._symbol, 20, Resolution.DAILY), 'B' : self.b(self._symbol, self._symbol2, 14) } # Here we're going to define indicators using 'selector' functions. These 'selector' functions will define what data gets sent into the indicator # These functions have a signature like the following: decimal Selector(BaseData base_data), and can be defined like: base_data => base_data.value # We'll define these 'selector' functions to select the Low value # # For more information on 'anonymous functions' see: http:#en.wikipedia.org/wiki/Anonymous_function # https:#msdn.microsoft.com/en-us/library/bb397687.aspx # self.selector_indicators = { 'BB' : self.bb(self._symbol, 20, 1, MovingAverageType.SIMPLE, Resolution.DAILY, Field.LOW), 'RSI' :self.rsi(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY, Field.LOW), 'EMA' :self.ema(self._symbol, 14, Resolution.DAILY, Field.LOW), 'SMA' :self.sma(self._symbol, 14, Resolution.DAILY, Field.LOW), 'MACD' : self.macd(self._symbol, 12, 26, 9, MovingAverageType.SIMPLE, Resolution.DAILY, Field.LOW), 'MOM' : self.mom(self._symbol, 20, Resolution.DAILY, Field.LOW), 'MOMP' : self.momp(self._symbol, 20, Resolution.DAILY, Field.LOW), 'STD' : self.std(self._symbol, 20, Resolution.DAILY, Field.LOW), 'MIN' : self.min(self._symbol, 14, Resolution.DAILY, Field.HIGH), 'MAX' : self.max(self._symbol, 14, Resolution.DAILY, Field.LOW), # ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar # before it gets sent to the ATR/AROON indicator, here we use a function that will multiply the input trade bar by a factor of two 'ATR' : self.atr(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY, self.selector_double__trade_bar), 'AROON' : self.aroon(self._symbol, 20, Resolution.DAILY, self.selector_double__trade_bar) } # Custom Data Indicator: self.rsi_custom = self.rsi(self.custom_symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY) self.min_custom = self.min(self.custom_symbol, 14, Resolution.DAILY) self.max_custom = self.max(self.custom_symbol, 14, Resolution.DAILY) # in addition to defining indicators on a single security, you can all define 'composite' indicators. # these are indicators that require multiple inputs. the most common of which is a ratio. # suppose we seek the ratio of BTC to SPY, we could write the following: spy_close = Identity(self._symbol) ibm_close = Identity(self.custom_symbol) # this will create a new indicator whose value is IBM/SPY self.ratio = IndicatorExtensions.over(ibm_close, spy_close) # we can also easily plot our indicators each time they update using th PlotIndicator function self.plot_indicator("Ratio", self.ratio) # The following methods will add multiple charts to the algorithm output. # Those chatrs names will be used later to plot different series in a particular chart. # For more information on Lean Charting see: https://www.quantconnect.com/docs#Charting Chart('BB') Chart('STD') Chart('ATR') Chart('AROON') Chart('MACD') Chart('Averages') # Here we make use of the Schelude method to update the plots once per day at market close. self.schedule.on(self.date_rules.every_day(), self.time_rules.before_market_close(self._symbol), self.update_plots) def on_data(self, data: Slice): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' if (#not data.bars.contains_key(self._symbol) or not self.indicators['BB'].is_ready or not self.indicators['RSI'].is_ready): return if not data.bars.contains_key(self._symbol): return self.price = data[self._symbol].close if not self.portfolio.hold_stock: quantity = int(self.portfolio.cash / self.price) self.order(self._symbol, quantity) self.debug('Purchased SPY on ' + self.time.strftime('%Y-%m-%d')) def update_plots(self): if not self.indicators['BB'].is_ready or not self.indicators['STD'].is_ready: return # Plots can also be created just with this one line command. self.plot('RSI', self.indicators['RSI']) # Custom data indicator self.plot('RSI-FB', self.rsi_custom) # Here we make use of the chats decalred in the Initialize method, plotting multiple series # in each chart. self.plot('STD', 'STD', self.indicators['STD'].current.value) self.plot('BB', 'Price', self.price) self.plot('BB', 'BollingerUpperBand', self.indicators['BB'].upper_band.current.value) self.plot('BB', 'BollingerMiddleBand', self.indicators['BB'].middle_band.current.value) self.plot('BB', 'BollingerLowerBand', self.indicators['BB'].lower_band.current.value) self.plot('AROON', 'Aroon', self.indicators['AROON'].current.value) self.plot('AROON', 'AroonUp', self.indicators['AROON'].aroon_up.current.value) self.plot('AROON', 'AroonDown', self.indicators['AROON'].aroon_down.current.value) # The following Plot method calls are commented out because of the 10 series limit for backtests #self.plot('ATR', 'ATR', self.indicators['ATR'].current.value) #self.plot('ATR', 'ATRDoubleBar', self.selector_indicators['ATR'].current.value) #self.plot('Averages', 'SMA', self.indicators['SMA'].current.value) #self.plot('Averages', 'EMA', self.indicators['EMA'].current.value) #self.plot('MOM', self.indicators['MOM'].current.value) #self.plot('MOMP', self.indicators['MOMP'].current.value) #self.plot('MACD', 'MACD', self.indicators['MACD'].current.value) #self.plot('MACD', 'MACDSignal', self.indicators['MACD'].signal.current.value) def selector_double__trade_bar(self, bar): trade_bar = TradeBar() trade_bar.close = 2 * bar.close trade_bar.data_type = bar.data_type trade_bar.high = 2 * bar.high trade_bar.low = 2 * bar.low trade_bar.open = 2 * bar.open trade_bar.symbol = bar.symbol trade_bar.time = bar.time trade_bar.value = 2 * bar.value trade_bar.period = bar.period return trade_bar class CustomData(PythonData): def get_source(self, config, date, is_live): zip_file_name = LeanData.generate_zip_file_name(config.Symbol, date, config.Resolution, config.TickType) source = Globals.data_folder + "/equity/usa/daily/" + zip_file_name return SubscriptionDataSource(source) def reader(self, config, line, date, is_live): if line == None: return None custom_data = CustomData() custom_data.symbol = config.symbol csv = line.split(",") custom_data.time = datetime.strptime(csv[0], '%Y%m%d %H:%M') custom_data.end_time = custom_data.time + timedelta(days=1) custom_data.value = float(csv[1]) / 10000.0 return custom_data ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This algorithm demonstrates the various ways to handle History pandas DataFrame
```python from AlgorithmImports import * class PandasDataFrameHistoryAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2014, 6, 9) # Set Start Date self.set_end_date(2014, 6, 9) # Set End Date self.spy = self.add_equity("SPY", Resolution.DAILY).symbol self.eur = self.add_forex("EURUSD", Resolution.DAILY).symbol aapl = self.add_equity("AAPL", Resolution.MINUTE).symbol self.option = Symbol.create_option(aapl, Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 750, datetime(2014, 10, 18)) self.add_option_contract(self.option) sp1 = self.add_data(QuandlFuture,"CHRIS/CME_SP1", Resolution.DAILY) sp1.exchange = EquityExchange() self.sp1 = sp1.symbol self.add_universe(self.coarse_selection) def coarse_selection(self, coarse): if self.portfolio.invested: return Universe.UNCHANGED selected = [x.symbol for x in coarse if x.symbol.value in ["AAA", "AIG", "BAC"]] if len(selected) == 0: return Universe.UNCHANGED universe_history = self.history(selected, 10, Resolution.DAILY) for symbol in selected: self.assert_history_index(universe_history, "close", 10, "", symbol) return selected def on_data(self, data): if self.portfolio.invested: return # we can get history in initialize to set up indicators and such self.spy_daily_sma = SimpleMovingAverage(14) # get the last calendar year's worth of SPY data at the configured resolution (daily) trade_bar_history = self.history(["SPY"], timedelta(365)) self.assert_history_index(trade_bar_history, "close", 251, "SPY", self.spy) # get the last calendar year's worth of EURUSD data at the configured resolution (daily) quote_bar_history = self.history(["EURUSD"], timedelta(298)) self.assert_history_index(quote_bar_history, "bidclose", 251, "EURUSD", self.eur) option_history = self.history([self.option], timedelta(3)) option_history.index = option_history.index.droplevel(level=[0,1,2]) self.assert_history_index(option_history, "bidclose", 390, "", self.option) # get the last calendar year's worth of quandl data at the configured resolution (daily) quandl_history = self.history(QuandlFuture, "CHRIS/CME_SP1", timedelta(365)) self.assert_history_index(quandl_history, "settle", 251, "CHRIS/CME_SP1", self.sp1) # we can loop over the return value from these functions and we get TradeBars # we can use these TradeBars to initialize indicators or perform other math self.spy_daily_sma.reset() for index, trade_bar in trade_bar_history.loc["SPY"].iterrows(): self.spy_daily_sma.update(index, trade_bar["close"]) # we can loop over the return values from these functions and we'll get Quandl data # this can be used in much the same way as the trade_bar_history above self.spy_daily_sma.reset() for index, quandl in quandl_history.loc["CHRIS/CME_SP1"].iterrows(): self.spy_daily_sma.update(index, quandl["settle"]) self.set_holdings(self.eur, 1) def assert_history_index(self, df, column, expected, ticker, symbol): if df.empty: raise AssertionError(f"Empty history data frame for {symbol}") if column not in df: raise AssertionError(f"Could not unstack df. Columns: {', '.join(df.columns)} | {column}") value = df.iat[0,0] df2 = df.xs(df.index.get_level_values('time')[0], level='time') df3 = df[column].unstack(level=0) try: # str(Symbol.ID) self.assert_history_count(f"df.iloc[0]", df.iloc[0], len(df.columns)) self.assert_history_count(f"df.loc[str({symbol.id})]", df.loc[str(symbol.id)], expected) self.assert_history_count(f"df.xs(str({symbol.id}))", df.xs(str(symbol.id)), expected) self.assert_history_count(f"df.at[(str({symbol.id}),), '{column}']", list(df.at[(str(symbol.id),), column]), expected) self.assert_history_count(f"df2.loc[str({symbol.id})]", df2.loc[str(symbol.id)], len(df2.columns)) self.assert_history_count(f"df3[str({symbol.id})]", df3[str(symbol.id)], expected) self.assert_history_count(f"df3.get(str({symbol.id}))", df3.get(str(symbol.id)), expected) # str(Symbol) self.assert_history_count(f"df.loc[str({symbol})]", df.loc[str(symbol)], expected) self.assert_history_count(f"df.xs(str({symbol}))", df.xs(str(symbol)), expected) self.assert_history_count(f"df.at[(str({symbol}),), '{column}']", list(df.at[(str(symbol),), column]), expected) self.assert_history_count(f"df2.loc[str({symbol})]", df2.loc[str(symbol)], len(df2.columns)) self.assert_history_count(f"df3[str({symbol})]", df3[str(symbol)], expected) self.assert_history_count(f"df3.get(str({symbol}))", df3.get(str(symbol)), expected) # str : Symbol.VALUE if len(ticker) == 0: return self.assert_history_count(f"df.loc[{ticker}]", df.loc[ticker], expected) self.assert_history_count(f"df.xs({ticker})", df.xs(ticker), expected) self.assert_history_count(f"df.at[(ticker,), '{column}']", list(df.at[(ticker,), column]), expected) self.assert_history_count(f"df2.loc[{ticker}]", df2.loc[ticker], len(df2.columns)) self.assert_history_count(f"df3[{ticker}]", df3[ticker], expected) self.assert_history_count(f"df3.get({ticker})", df3.get(ticker), expected) except Exception as e: symbols = set(df.index.get_level_values(level='symbol')) raise AssertionError(f"{symbols}, {symbol.id}, {symbol}, {ticker}. {e}") def assert_history_count(self, method_call, trade_bar_history, expected): if isinstance(trade_bar_history, list): count = len(trade_bar_history) else: count = len(trade_bar_history.index) if count != expected: raise AssertionError(f"{method_call} expected {expected}, but received {count}") class QuandlFuture(PythonQuandl): '''Custom quandl data type for setting customized value column name. Value column is used for the primary trading calculations and charting.''' def __init__(self): self.value_column_name = "Settle" ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Related to GH issue 4275, reproduces a failed string to symbol implicit conversion asserting the exception thrown contains the used ticker
```python from AlgorithmImports import * class StringToSymbolImplicitConversionRegressionAlgorithm(QCAlgorithm): def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2013,10, 7) self.set_end_date(2013,10, 8) self.add_equity("SPY", Resolution.MINUTE) def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' try: self.market_order("PEPE", 1) except Exception as exception: if "PEPE was not found" in str(exception) and not self.portfolio.invested: self.set_holdings("SPY", 1) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Algorithm for testing submit/update/cancel for combo orders
```python import itertools from AlgorithmImports import * class ComboOrderTicketDemoAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2015, 12, 24) self.set_end_date(2015, 12, 24) self.set_cash(100000) equity = self.add_equity("GOOG", leverage=4, fill_forward=True) option = self.add_option(equity.symbol, fill_forward=True) self._option_symbol = option.symbol option.set_filter(lambda u: u.strikes(-2, +2).expiration(0, 180)) self._open_market_orders = [] self._open_leg_limit_orders = [] self._open_limit_orders = [] self._order_legs = None def on_data(self, data: Slice) -> None: if self._order_legs is None: if self.is_market_open(self._option_symbol): chain = data.option_chains.get(self._option_symbol) if chain: call_contracts = [contract for contract in chain if contract.right == OptionRight.CALL] call_contracts_by_expiry = [(key, list(group)) for key, group in itertools.groupby(call_contracts, key=lambda x: x.expiry)] call_contracts_by_expiry.sort(key=lambda x: x[0]) call_contracts = call_contracts_by_expiry[0][1] call_contracts.sort(key=lambda x: x.strike) if len(call_contracts) < 3: return quantities = [1, -2, 1] self._order_legs = [] for i, contract in enumerate(call_contracts[:3]): leg = Leg.create(contract.symbol, quantities[i]) self._order_legs.append(leg) else: # COMBO MARKET ORDERS self.combo_market_orders() # COMBO LIMIT ORDERS self.combo_limit_orders() # COMBO LEG LIMIT ORDERS self.combo_leg_limit_orders() def combo_market_orders(self) -> None: if len(self._open_market_orders) != 0 or self._order_legs is None: return self.log("Submitting combo market orders") tickets = self.combo_market_order(self._order_legs, 2, asynchronous=False) self._open_market_orders.extend(tickets) tickets = self.combo_market_order(self._order_legs, 2, asynchronous=True) self._open_market_orders.extend(tickets) for ticket in tickets: response = ticket.cancel("Attempt to cancel combo market order") if response.is_success: raise AssertionError("Combo market orders should fill instantly, they should not be cancelable in backtest mode: " + response.order_id) def combo_limit_orders(self) -> None: if len(self._open_limit_orders) == 0: self.log("Submitting ComboLimitOrder") current_price = sum([leg.quantity * self.securities[leg.symbol].close for leg in self._order_legs]) tickets = self.combo_limit_order(self._order_legs, 2, current_price + 1.5) self._open_limit_orders.extend(tickets) # These won't fill, we will test cancel with this tickets = self.combo_limit_order(self._order_legs, -2, current_price + 3) self._open_limit_orders.extend(tickets) else: combo1 = self._open_limit_orders[:len(self._order_legs)] combo2 = self._open_limit_orders[-len(self._order_legs):] # check if either is filled and cancel the other if self.check_group_orders_for_fills(combo1, combo2): return # if neither order has filled, bring in the limits by a penny ticket = combo1[0] new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + 0.01, 2) self.debug(f"Updating limits - Combo 1 {ticket.order_id}: {new_limit:.2f}") fields = UpdateOrderFields() fields.limit_price = new_limit fields.tag = f"Update #{len(ticket.update_requests) + 1}" ticket.update(fields) ticket = combo2[0] new_limit = round(ticket.get(OrderField.LIMIT_PRICE) - 0.01, 2) self.debug(f"Updating limits - Combo 2 {ticket.order_id}: {new_limit:.2f}") fields.limit_price = new_limit fields.tag = f"Update #{len(ticket.update_requests) + 1}" ticket.update(fields) def combo_leg_limit_orders(self) -> None: if len(self._open_leg_limit_orders) == 0: self.log("Submitting ComboLegLimitOrder") # submit a limit order to buy 2 shares at .1% below the bar's close for leg in self._order_legs: close = self.securities[leg.symbol].close leg.order_price = close * .999 tickets = self.combo_leg_limit_order(self._order_legs, quantity=2) self._open_leg_limit_orders.extend(tickets) # submit another limit order to sell 2 shares at .1% above the bar's close for leg in self._order_legs: close = self.securities[leg.symbol].close leg.order_price = close * 1.001 tickets = self.combo_leg_limit_order(self._order_legs, -2) self._open_leg_limit_orders.extend(tickets) else: combo1 = self._open_leg_limit_orders[:len(self._order_legs)] combo2 = self._open_leg_limit_orders[-len(self._order_legs):] # check if either is filled and cancel the other if self.check_group_orders_for_fills(combo1, combo2): return # if neither order has filled, bring in the limits by a penny for ticket in combo1: new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + (1 if ticket.quantity > 0 else -1) * 0.01, 2) self.debug(f"Updating limits - Combo #1: {new_limit:.2f}") fields = UpdateOrderFields() fields.limit_price = new_limit fields.tag = f"Update #{len(ticket.update_requests) + 1}" ticket.update(fields) for ticket in combo2: new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + (1 if ticket.quantity > 0 else -1) * 0.01, 2) self.debug(f"Updating limits - Combo #2: {new_limit:.2f}") fields.limit_price = new_limit fields.tag = f"Update #{len(ticket.update_requests) + 1}" ticket.update(fields) def on_order_event(self, order_event: OrderEvent) -> None: order = self.transactions.get_order_by_id(order_event.order_id) if order_event.quantity == 0: raise AssertionError("OrderEvent quantity is Not expected to be 0, it should hold the current order Quantity") if order_event.quantity != order.quantity: raise AssertionError("OrderEvent quantity should hold the current order Quantity. " f"Got {order_event.quantity}, expected {order.quantity}") if order.type == OrderType.COMBO_LEG_LIMIT and order_event.limit_price == 0: raise AssertionError("OrderEvent.LIMIT_PRICE is not expected to be 0 for ComboLegLimitOrder") def check_group_orders_for_fills(self, combo1: list[OrderTicket], combo2: list[OrderTicket]) -> bool: if all(x.status == OrderStatus.FILLED for x in combo1): self.log(f"{combo1[0].order_type}: Canceling combo #2, combo #1 is filled.") if any(OrderExtensions.is_open(x.status) for x in combo2): for ticket in combo2: ticket.cancel("Combo #1 filled.") return True if all(x.status == OrderStatus.FILLED for x in combo2): self.log(f"{combo2[0].order_type}: Canceling combo #1, combo #2 is filled.") if any(OrderExtensions.is_open(x.status) for x in combo1): for ticket in combo1: ticket.cancel("Combo #2 filled.") return True return False def on_end_of_algorithm(self) -> None: filled_orders = list(self.transactions.get_orders(lambda x: x.status == OrderStatus.FILLED)) order_tickets = list(self.transactions.get_order_tickets()) open_orders = self.transactions.get_open_orders() open_order_tickets = list(self.transactions.get_open_order_tickets()) remaining_open_orders = self.transactions.get_open_orders_remaining_quantity() # 6 market, 6 limit, 6 leg limit. # Out of the 6 limit orders, 3 are expected to be canceled. expected_orders_count = 18 expected_fills_count = 15 if len(filled_orders) != expected_fills_count or len(order_tickets) != expected_orders_count: raise AssertionError(f"There were expected {expected_fills_count} filled orders and {expected_orders_count} order tickets, but there were {len(filled_orders)} filled orders and {len(order_tickets)} order tickets") filled_combo_market_orders = [x for x in filled_orders if x.type == OrderType.COMBO_MARKET] filled_combo_limit_orders = [x for x in filled_orders if x.type == OrderType.COMBO_LIMIT] filled_combo_leg_limit_orders = [x for x in filled_orders if x.type == OrderType.COMBO_LEG_LIMIT] if len(filled_combo_market_orders) != 6 or len(filled_combo_limit_orders) != 3 or len(filled_combo_leg_limit_orders) != 6: raise AssertionError("There were expected 6 filled market orders, 3 filled combo limit orders and 6 filled combo leg limit orders, " f"but there were {len(filled_combo_market_orders)} filled market orders, {len(filled_combo_limit_orders)} filled " f"combo limit orders and {len(filled_combo_leg_limit_orders)} filled combo leg limit orders") if len(open_orders) != 0 or len(open_order_tickets) != 0: raise AssertionError("No open orders or tickets were expected") if remaining_open_orders != 0: raise AssertionError("No remaining quantity to be filled from open orders was expected") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm to test the OptionChainedUniverseSelectionModel class
```python from AlgorithmImports import * class OptionChainedUniverseSelectionModelRegressionAlgorithm(QCAlgorithm): def initialize(self): self.universe_settings.resolution = Resolution.MINUTE self.set_start_date(2014, 6, 6) self.set_end_date(2014, 6, 6) self.set_cash(100000) universe = self.add_universe("my-minute-universe-name", lambda time: [ "AAPL", "TWX" ]) self.add_universe_selection( OptionChainedUniverseSelectionModel( universe, lambda u: (u.strikes(-2, +2) # Expiration method accepts TimeSpan objects or integer for days. # The following statements yield the same filtering criteria .expiration(0, 180)) ) ) def on_data(self, slice): if self.portfolio.invested or not (self.is_market_open("AAPL") and self.is_market_open("TWX")): return values = list(map(lambda x: x.value, filter(lambda x: x.key == "?AAPL" or x.key == "?TWX", slice.option_chains))) for chain in values: # we sort the contracts to find at the money (ATM) contract with farthest expiration contracts = sorted(sorted(sorted(chain, \ key = lambda x: abs(chain.underlying.price - x.strike)), \ key = lambda x: x.expiry, reverse=True), \ key = lambda x: x.right, reverse=True) # if found, trade it if len(contracts) == 0: return symbol = contracts[0].symbol self.market_order(symbol, 1) self.market_on_close_order(symbol, -1) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Uses daily data and a simple moving average cross to place trades and an ema for stop placement
```python from AlgorithmImports import * class DailyAlgorithm(QCAlgorithm): def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2013,1,1) #Set Start Date self.set_end_date(2014,1,1) #Set End Date self.set_cash(100000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data self.add_equity("SPY", Resolution.DAILY) self.add_equity("IBM", Resolution.HOUR, leverage=1) self._macd = self.macd("SPY", 12, 26, 9, MovingAverageType.WILDERS, Resolution.DAILY, Field.CLOSE) self._ema = self.ema("IBM", 15 * 6, Resolution.HOUR, Field.SEVEN_BAR) self._last_action = self.start_date def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' if not self._macd.is_ready: return bar = data.bars.get("IBM") if not bar: return if self._last_action.date() == self.time.date(): return self._last_action = self.time quantity = self.portfolio["SPY"].quantity if quantity <= 0 and self._macd.current.value > self._macd.signal.current.value and bar.price > self._ema.current.value: self.set_holdings("IBM", 0.25) if quantity >= 0 and self._macd.current.value < self._macd.signal.current.value and bar.price < self._ema.current.value: self.set_holdings("IBM", -0.25) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This example demonstrates how to add options for a given underlying equity security. It also shows how you can prefilter contracts easily based on strikes and expirations, and how you can inspect the option chain to pick a specific option contract to trade.
```python from AlgorithmImports import * class BasicTemplateOptionsHourlyAlgorithm(QCAlgorithm): underlying_ticker = "AAPL" def initialize(self): self.set_start_date(2014, 6, 6) self.set_end_date(2014, 6, 9) self.set_cash(100000) equity = self.add_equity(self.underlying_ticker, Resolution.HOUR) option = self.add_option(self.underlying_ticker, Resolution.HOUR) self.option_symbol = option.symbol # set our strike/expiry filter for this option chain option.set_filter(lambda u: (u.strikes(-2, +2) # Expiration method accepts TimeSpan objects or integer for days. # The following statements yield the same filtering criteria .expiration(0, 180))) #.expiration(TimeSpan.zero, TimeSpan.from_days(180)))) # use the underlying equity as the benchmark self.set_benchmark(equity.symbol) def on_data(self,slice): if self.portfolio.invested or not self.is_market_open(self.option_symbol): return chain = slice.option_chains.get(self.option_symbol) if not chain: return # we sort the contracts to find at the money (ATM) contract with farthest expiration contracts = sorted(sorted(sorted(chain, \ key = lambda x: abs(chain.underlying.price - x.strike)), \ key = lambda x: x.expiry, reverse=True), \ key = lambda x: x.right, reverse=True) # if found, trade it if len(contracts) == 0 or not self.is_market_open(contracts[0].symbol): return symbol = contracts[0].symbol self.market_order(symbol, 1) self.market_on_close_order(symbol, -1) def on_order_event(self, order_event): self.log(str(order_event)) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Provides an example algorithm showcasing the Security.data features
```python from AlgorithmImports import * from QuantConnect.Data.Custom.IconicTypes import * class DynamicSecurityDataRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2015, 10, 22) self.set_end_date(2015, 10, 30) ticker = "GOOGL" self._equity = self.add_equity(ticker, Resolution.DAILY) custom_linked_equity = self.add_data(LinkedData, ticker, Resolution.DAILY) first_linked_data = LinkedData() first_linked_data.count = 100 first_linked_data.symbol = custom_linked_equity.symbol first_linked_data.end_time = self.start_date second_linked_data = LinkedData() second_linked_data.count = 100 second_linked_data.symbol = custom_linked_equity.symbol second_linked_data.end_time = self.start_date # Adding linked data manually to cache for example purposes, since # LinkedData is a type used for testing and doesn't point to any real data. custom_linked_equity_type = list(custom_linked_equity.subscriptions)[0].type custom_linked_data = list[LinkedData]() custom_linked_data.append(first_linked_data) custom_linked_data.append(second_linked_data) self._equity.cache.add_data_list(custom_linked_data, custom_linked_equity_type, False) def on_data(self, data): # The Security object's Data property provides convenient access # to the various types of data related to that security. You can # access not only the security's price data, but also any custom # data that is mapped to the security, such as our SEC reports. # 1. Get the most recent data point of a particular type: # 1.a Using the generic method, Get(T): => T custom_linked_data = self._equity.data.get(LinkedData) self.log(f"{self.time}: LinkedData: {custom_linked_data}") # 2. Get the list of data points of a particular type for the most recent time step: # 2.a Using the generic method, GetAll(T): => IReadOnlyList<T> custom_linked_data_list = self._equity.data.get_all(LinkedData) self.log(f"{self.time}: LinkedData: {len(custom_linked_data_list)}") if not self.portfolio.invested: self.buy(self._equity.symbol, 10) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm asserts that futures have data at extended market hours when this is enabled.
```python from AlgorithmImports import * class FuturesExtendedMarketHoursRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 6) self.set_end_date(2013, 10, 11) self._es = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.HOUR, fill_forward=True, extended_market_hours=True) self._es.set_filter(0, 180) self._gc = self.add_future(Futures.Metals.GOLD, Resolution.HOUR, fill_forward=True, extended_market_hours=False) self._gc.set_filter(0, 180) self._es_ran_on_regular_hours = False self._es_ran_on_extended_hours = False self._gc_ran_on_regular_hours = False self._gc_ran_on_extended_hours = False def on_data(self, slice): slice_symbols = set(slice.keys()) slice_symbols.update(slice.bars.keys()) slice_symbols.update(slice.ticks.keys()) slice_symbols.update(slice.quote_bars.keys()) slice_symbols.update([x.canonical for x in slice_symbols]) es_is_in_regular_hours = self._es.exchange.hours.is_open(self.time, False) es_is_in_extended_hours = not es_is_in_regular_hours and self._es.exchange.hours.is_open(self.time, True) slice_has_e_s_data = self._es.symbol in slice_symbols self._es_ran_on_regular_hours |= es_is_in_regular_hours and slice_has_e_s_data self._es_ran_on_extended_hours |= es_is_in_extended_hours and slice_has_e_s_data gc_is_in_regular_hours = self._gc.exchange.hours.is_open(self.time, False) gc_is_in_extended_hours = not gc_is_in_regular_hours and self._gc.exchange.hours.is_open(self.time, True) slice_has_g_c_data = self._gc.symbol in slice_symbols self._gc_ran_on_regular_hours |= gc_is_in_regular_hours and slice_has_g_c_data self._gc_ran_on_extended_hours |= gc_is_in_extended_hours and slice_has_g_c_data time_of_day = self.time.time() current_time_is_regular_hours = (time_of_day >= time(9, 30, 0) and time_of_day < time(16, 15, 0)) or (time_of_day >= time(16, 30, 0) and time_of_day < time(17, 0, 0)) current_time_is_extended_hours = not current_time_is_regular_hours and (time_of_day < time(9, 30, 0) or time_of_day >= time(18, 0, 0)) if es_is_in_regular_hours != current_time_is_regular_hours or es_is_in_extended_hours != current_time_is_extended_hours: raise AssertionError("At {Time}, {_es.symbol} is either in regular hours but current time is in extended hours, or viceversa") def on_end_of_algorithm(self): if not self._es_ran_on_regular_hours: raise AssertionError(f"Algorithm should have run on regular hours for {self._es.symbol} future, which enabled extended market hours") if not self._es_ran_on_extended_hours: raise AssertionError(f"Algorithm should have run on extended hours for {self._es.symbol} future, which enabled extended market hours") if not self._gc_ran_on_regular_hours: raise AssertionError(f"Algorithm should have run on regular hours for {self._gc.symbol} future, which did not enable extended market hours") if self._gc_ran_on_extended_hours: raise AssertionError(f"Algorithm should have not run on extended hours for {self._gc.symbol} future, which did not enable extended market hours") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests Out of The Money (OTM) future option expiry for puts. We expect 2 orders from the algorithm, which are: * Initial entry, buy ES Put Option (expiring OTM) - contract expires worthless, not exercised, so never opened a position in the underlying * Liquidation of worthless ES Put OTM contract Additionally, we test delistings for future options and assert that our portfolio holdings reflect the orders the algorithm has submitted.
```python from AlgorithmImports import * class FutureOptionPutOTMExpiryRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2020, 1, 5) self.set_end_date(2020, 6, 30) self.es19m20 = self.add_future_contract( Symbol.create_future( Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 6, 19)), Resolution.MINUTE).symbol # Select a future option expiring ITM, and adds it to the algorithm. self.es_option = self.add_future_option_contract( list( sorted( [x for x in self.option_chain(self.es19m20) if x.id.strike_price <= 3150.0 and x.id.option_right == OptionRight.PUT], key=lambda x: x.id.strike_price, reverse=True ) )[0], Resolution.MINUTE).symbol self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3150.0, datetime(2020, 6, 19)) if self.es_option != self.expected_contract: raise AssertionError(f"Contract {self.expected_contract} was not found in the chain") self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order) def scheduled_market_order(self): self.market_order(self.es_option, 1) def on_data(self, data: Slice): # Assert delistings, so that we can make sure that we receive the delisting warnings at # the expected time. These assertions detect bug #4872 for delisting in data.delistings.values(): if delisting.type == DelistingType.WARNING: if delisting.time != datetime(2020, 6, 19): raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}") if delisting.type == DelistingType.DELISTED: if delisting.time != datetime(2020, 6, 20): raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}") def on_order_event(self, order_event: OrderEvent): if order_event.status != OrderStatus.FILLED: # There's lots of noise with OnOrderEvent, but we're only interested in fills. return if not self.securities.contains_key(order_event.symbol): raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}") security = self.securities[order_event.symbol] if security.symbol == self.es19m20: raise AssertionError("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM") # Expected contract is ES19M20 Put Option expiring OTM @ 3200 if (security.symbol == self.expected_contract): self.assert_future_option_contract_order(order_event, security) else: raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}") self.log(f"{order_event}") def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security): if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1: raise AssertionError(f"No holdings were created for option contract {option.symbol}") if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0: raise AssertionError("Holdings were found after a filled option exercise") if order_event.direction == OrderDirection.SELL and "OTM" not in order_event.message: raise AssertionError("Contract did not expire OTM") if "Exercise" in order_event.message: raise AssertionError("Exercised option, even though it expires OTM") def on_end_of_algorithm(self): if self.portfolio.invested: raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Basic template framework algorithm uses framework components to define the algorithm.
```python from AlgorithmImports import * class BasicTemplateIndiaAlgorithm(QCAlgorithm): '''Basic template framework algorithm uses framework components to define the algorithm.''' def initialize(self): '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_account_currency("INR") #Set Account Currency self.set_start_date(2019, 1, 23) #Set Start Date self.set_end_date(2019, 10, 31) #Set End Date self.set_cash(100000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data self.add_equity("YESBANK", Resolution.MINUTE, Market.INDIA) self.debug("numpy test >>> print numpy.pi: " + str(np.pi)) # Set Order Properties as per the requirements for order placement self.default_order_properties = IndiaOrderProperties(Exchange.NSE) def on_data(self, data): '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' if not self.portfolio.invested: self.market_order("YESBANK", 1) def on_order_event(self, order_event): if order_event.status == OrderStatus.FILLED: self.debug("Purchased Stock: {0}".format(order_event.symbol)) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Demonstration of using the ETFConstituentsUniverseSelectionModel
```python from AlgorithmImports import * from Selection.ETFConstituentsUniverseSelectionModel import * class ETFConstituentsFrameworkAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2020, 12, 1) self.set_end_date(2020, 12, 7) self.set_cash(100000) self.universe_settings.resolution = Resolution.DAILY symbol = Symbol.create("SPY", SecurityType.EQUITY, Market.USA) self.add_universe_selection(ETFConstituentsUniverseSelectionModel(symbol, self.universe_settings, self.etf_constituents_filter)) self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(days=1))) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) def etf_constituents_filter(self, constituents: List[ETFConstituentData]) -> List[Symbol]: # Get the 10 securities with the largest weight in the index selected = sorted([c for c in constituents if c.weight], key=lambda c: c.weight, reverse=True)[:8] return [c.symbol for c in selected] ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression test for consistency of hour data over a reverse split event in US equities.
```python from AlgorithmImports import * class HourReverseSplitRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 11, 7) self.set_end_date(2013, 11, 8) self.set_cash(100000) self.set_benchmark(lambda x: 0) self._symbol = self.add_equity("VXX.1", Resolution.HOUR).symbol def on_data(self, slice): if slice.bars.count == 0: return if (not self.portfolio.invested) and self.time.date() == self.end_date.date(): self.buy(self._symbol, 1) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This algorithm shows some of the various helper methods available when defining universes
```python from AlgorithmImports import * class UniverseSelectionDefinitionsAlgorithm(QCAlgorithm): def initialize(self): # subscriptions added via universe selection will have this resolution self.universe_settings.resolution = Resolution.DAILY self.set_start_date(2014,3,24) # Set Start Date self.set_end_date(2014,3,28) # Set End Date self.set_cash(100000) # Set Strategy Cash # add universe for the top 3 stocks by dollar volume self.add_universe(self.universe.top(3)) self.changes = None self.on_securities_changed_was_called = False def on_data(self, data): if self.changes is None: return # liquidate securities that fell out of our universe for security in self.changes.removed_securities: if security.invested: self.liquidate(security.symbol) # invest in securities just added to our universe for security in self.changes.added_securities: if not security.invested: self.market_order(security.symbol, 10) self.changes = None # this event fires whenever we have changes to our universe def on_securities_changed(self, changes): self.changes = changes self.on_securities_changed_was_called = True def on_end_of_algorithm(self): if not self.on_securities_changed_was_called: raise AssertionError("OnSecuritiesChanged() method was never called!") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : In this algorithm, we fetch a list of tickers with corresponding dates from a file on Dropbox. We then create a fine fundamental universe which contains those symbols on their respective dates.###
```python from AlgorithmImports import * class DropboxCoarseFineAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2019, 9, 23) # Set Start Date self.set_end_date(2019, 9, 30) # Set End Date self.set_cash(100000) # Set Strategy Cash self.add_universe(self.select_coarse, self.select_fine) self.universe_data = None self.next_update = datetime(1, 1, 1) # Minimum datetime self.url = "https://www.dropbox.com/s/x2sb9gaiicc6hm3/tickers_with_dates.csv?dl=1" def on_end_of_day(self, symbol: Symbol) -> None: self.debug(f"{self.time.date()} {symbol.value} with Market Cap: ${self.securities[symbol].fundamentals.market_cap}") def select_coarse(self, coarse): return self.get_symbols() def select_fine(self, fine): symbols = self.get_symbols() # Return symbols from our list which have a market capitalization of at least 10B return [f.symbol for f in fine if f.market_cap > 1e10 and f.symbol in symbols] def get_symbols(self): # In live trading update every 12 hours if self.live_mode: if self.time < self.next_update: # Return today's row return self.universe_data[self.time.date()] # When updating set the new reset time. self.next_update = self.time + timedelta(hours=12) self.universe_data = self.parse(self.url) # In backtest load once if not set, then just use the dates. if not self.universe_data: self.universe_data = self.parse(self.url) # Check if contains the row we need if self.time.date() not in self.universe_data: return Universe.UNCHANGED return self.universe_data[self.time.date()] def parse(self, url): # Download file from url as string file = self.download(url).split("\n") # # Remove formatting characters data = [x.replace("\r", "").replace(" ", "") for x in file] # # Split data by date and symbol split_data = [x.split(",") for x in data] # Dictionary to hold list of active symbols for each date, keyed by date symbols_by_date = {} # Parse data into dictionary for arr in split_data: date = datetime.strptime(arr[0], "%Y%m%d").date() symbols = [Symbol.create(ticker, SecurityType.EQUITY, Market.USA) for ticker in arr[1:]] symbols_by_date[date] = symbols return symbols_by_date def on_securities_changed(self, changes): self.log(f"Added Securities: {[security.symbol.value for security in changes.added_securities]}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Algorithm demonstrating and ensuring that Bybit crypto futures brokerage model works as expected
```python from cmath import isclose from AlgorithmImports import * class BybitCryptoFuturesRegressionAlgorithm(QCAlgorithm): def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2022, 12, 13) self.set_end_date(2022, 12, 13) # Set strategy cash (USD) self.set_cash(100000) self.set_brokerage_model(BrokerageName.BYBIT, AccountType.MARGIN) # Translate lines 44-59 to Python: self.add_crypto("BTCUSDT", Resolution.MINUTE) self.btc_usdt = self.add_crypto_future("BTCUSDT", Resolution.MINUTE) self.btc_usd = self.add_crypto_future("BTCUSD", Resolution.MINUTE) # create two moving averages self.fast = self.ema(self.btc_usdt.symbol, 30, Resolution.MINUTE) self.slow = self.ema(self.btc_usdt.symbol, 60, Resolution.MINUTE) self.interest_per_symbol = {} self.interest_per_symbol[self.btc_usd.symbol] = 0 self.interest_per_symbol[self.btc_usdt.symbol] = 0 # the amount of USDT we need to hold to trade 'BTCUSDT' self.btc_usdt.quote_currency.set_amount(200) # the amount of BTC we need to hold to trade 'BTCUSD' self.btc_usd.base_currency.set_amount(0.005) def on_data(self, data): interest_rates = data.get[MarginInterestRate]() for interest_rate in interest_rates: self.interest_per_symbol[interest_rate.key] += 1 cached_interest_rate = self.securities[interest_rate.key].cache.get_data(MarginInterestRate) if cached_interest_rate != interest_rate.value: raise AssertionError(f"Unexpected cached margin interest rate for {interest_rate.key}!") if not self.slow.is_ready: return if self.fast > self.slow: if not self.portfolio.invested and self.transactions.orders_count == 0: ticket = self.buy(self.btc_usd.symbol, 1000) if ticket.status != OrderStatus.INVALID: raise AssertionError(f"Unexpected valid order {ticket}, should fail due to margin not sufficient") self.buy(self.btc_usd.symbol, 100) margin_used = self.portfolio.total_margin_used btc_usd_holdings = self.btc_usd.holdings # Coin futures value is 100 USD holdings_value_btc_usd = 100 if abs(btc_usd_holdings.total_sale_volume - holdings_value_btc_usd) > 1: raise AssertionError(f"Unexpected TotalSaleVolume {btc_usd_holdings.total_sale_volume}") if abs(btc_usd_holdings.absolute_holdings_cost - holdings_value_btc_usd) > 1: raise AssertionError(f"Unexpected holdings cost {btc_usd_holdings.holdings_cost}") # margin used is based on the maintenance rate if (abs(btc_usd_holdings.absolute_holdings_cost * 0.05 - margin_used) > 1 or not isclose(self.btc_usd.buying_power_model.get_maintenance_margin(MaintenanceMarginParameters.for_current_holdings(self.btc_usd)).value, margin_used)): raise AssertionError(f"Unexpected margin used {margin_used}") self.buy(self.btc_usdt.symbol, 0.01) margin_used = self.portfolio.total_margin_used - margin_used btc_usdt_holdings = self.btc_usdt.holdings # USDT futures value is based on it's price holdings_value_usdt = self.btc_usdt.price * self.btc_usdt.symbol_properties.contract_multiplier * 0.01 if abs(btc_usdt_holdings.total_sale_volume - holdings_value_usdt) > 1: raise AssertionError(f"Unexpected TotalSaleVolume {btc_usdt_holdings.total_sale_volume}") if abs(btc_usdt_holdings.absolute_holdings_cost - holdings_value_usdt) > 1: raise AssertionError(f"Unexpected holdings cost {btc_usdt_holdings.holdings_cost}") if (abs(btc_usdt_holdings.absolute_holdings_cost * 0.05 - margin_used) > 1 or not isclose(self.btc_usdt.buying_power_model.get_maintenance_margin(MaintenanceMarginParameters.for_current_holdings(self.btc_usdt)).value, margin_used)): raise AssertionError(f"Unexpected margin used {margin_used}") # position just opened should be just spread here unrealized_profit = self.portfolio.total_unrealized_profit if (5 - abs(unrealized_profit)) < 0: raise AssertionError(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}") if self.portfolio.total_profit != 0: raise AssertionError(f"Unexpected TotalProfit {self.portfolio.total_profit}") # let's revert our position elif self.transactions.orders_count == 3: self.sell(self.btc_usd.symbol, 300) btc_usd_holdings = self.btc_usd.holdings if abs(btc_usd_holdings.absolute_holdings_cost - 100 * 2) > 1: raise AssertionError(f"Unexpected holdings cost {btc_usd_holdings.holdings_cost}") self.sell(self.btc_usdt.symbol, 0.03) # USDT futures value is based on it's price holdings_value_usdt = self.btc_usdt.price * self.btc_usdt.symbol_properties.contract_multiplier * 0.02 if abs(self.btc_usdt.holdings.absolute_holdings_cost - holdings_value_usdt) > 1: raise AssertionError(f"Unexpected holdings cost {self.btc_usdt.holdings.holdings_cost}") # position just opened should be just spread here profit = self.portfolio.total_unrealized_profit if (5 - abs(profit)) < 0: raise AssertionError(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}") # we barely did any difference on the previous trade if (5 - abs(self.portfolio.total_profit)) < 0: raise AssertionError(f"Unexpected TotalProfit {self.portfolio.total_profit}") def on_order_event(self, order_event): self.debug("{} {}".format(self.time, order_event.to_string())) def on_end_of_algorithm(self): self.log(f"{self.time} - TotalPortfolioValue: {self.portfolio.total_portfolio_value}") self.log(f"{self.time} - CashBook: {self.portfolio.cash_book}") if any(x == 0 for x in self.interest_per_symbol.values()): raise AssertionError("Expected interest rate data for all symbols") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Test algorithm using a 'ConstituentsUniverse' with test data
```python from AlgorithmImports import * class ConstituentsUniverseRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 7) #Set Start Date self.set_end_date(2013, 10, 11) #Set End Date self.set_cash(100000) #Set Strategy Cash self._appl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA) self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA) self._qqq = Symbol.create("QQQ", SecurityType.EQUITY, Market.USA) self._fb = Symbol.create("FB", SecurityType.EQUITY, Market.USA) self._step = 0 self.universe_settings.resolution = Resolution.DAILY custom_universe_symbol = Symbol(SecurityIdentifier.generate_constituent_identifier( "constituents-universe-qctest", SecurityType.EQUITY, Market.USA), "constituents-universe-qctest") self.add_universe(ConstituentsUniverse(custom_universe_symbol, self.universe_settings)) def on_data(self, data): self._step = self._step + 1 if self._step == 1: if not data.contains_key(self._qqq) or not data.contains_key(self._appl): raise ValueError("Unexpected symbols found, step: " + str(self._step)) if data.count != 2: raise ValueError("Unexpected data count, step: " + str(self._step)) # AAPL will be deselected by the ConstituentsUniverse # but it shouldn't be removed since we hold it self.set_holdings(self._appl, 0.5) elif self._step == 2: if not data.contains_key(self._appl): raise ValueError("Unexpected symbols found, step: " + str(self._step)) if data.count != 1: raise ValueError("Unexpected data count, step: " + str(self._step)) # AAPL should now be released # note: takes one extra loop because the order is executed on market open self.liquidate() elif self._step == 3: if not data.contains_key(self._fb) or not data.contains_key(self._spy) or not data.contains_key(self._appl): raise ValueError("Unexpected symbols found, step: " + str(self._step)) if data.count != 3: raise ValueError("Unexpected data count, step: " + str(self._step)) elif self._step == 4: if not data.contains_key(self._fb) or not data.contains_key(self._spy): raise ValueError("Unexpected symbols found, step: " + str(self._step)) if data.count != 2: raise ValueError("Unexpected data count, step: " + str(self._step)) def on_end_of_algorithm(self): # First selection is on the midnight of the 8th, start getting data from the 8th to the 11th if self._step != 4: raise ValueError("Unexpected step count: " + str(self._step)) def OnSecuritiesChanged(self, changes): for added in changes.added_securities: self.log(f"{self.time} AddedSecurities " + str(added)) for removed in changes.removed_securities: self.log(f"{self.time} RemovedSecurities " + str(removed) + str(self._step)) # we are currently notifying the removal of AAPl twice, # when deselected and when finally removed (since it stayed pending) if removed.symbol == self._appl and self._step != 1 and self._step != 2 or removed.symbol == self._qqq and self._step != 1: raise ValueError("Unexpected removal step count: " + str(self._step)) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression test to demonstrate setting custom Symbol Properties and Market Hours for a custom data import
```python import json from AlgorithmImports import * class CustomDataPropertiesRegressionAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2020, 1, 5) # Set Start Date self.set_end_date(2020, 1, 10) # Set End Date self.set_cash(100000) # Set Strategy Cash # Define our custom data properties and exchange hours ticker = 'BTC' properties = SymbolProperties("Bitcoin", "USD", 1, 0.01, 0.01, ticker) exchange_hours = SecurityExchangeHours.always_open(TimeZones.NEW_YORK) # Add the custom data to our algorithm with our custom properties and exchange hours self._bitcoin = self.add_data(Bitcoin, ticker, properties, exchange_hours, leverage=1, fill_forward=False) # Verify our symbol properties were changed and loaded into this security if self._bitcoin.symbol_properties != properties : raise AssertionError("Failed to set and retrieve custom SymbolProperties for BTC") # Verify our exchange hours were changed and loaded into this security if self._bitcoin.exchange.hours != exchange_hours : raise AssertionError("Failed to set and retrieve custom ExchangeHours for BTC") # For regression purposes on AddData overloads, this call is simply to ensure Lean can accept this # with default params and is not routed to a breaking function. self.add_data(Bitcoin, "BTCUSD") def on_data(self, data: Slice) -> None: if not self.portfolio.invested: if data['BTC'].close != 0 : self.order('BTC', self.portfolio.margin_remaining/abs(data['BTC'].close + 1)) def on_end_of_algorithm(self) -> None: #Reset our Symbol property value, for testing purposes. self.symbol_properties_database.set_entry(Market.USA, self.market_hours_database.get_database_symbol_key(self._bitcoin.symbol), SecurityType.BASE, SymbolProperties.get_default("USD")) class Bitcoin(PythonData): '''Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data''' def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource: if is_live_mode: return SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.REST) #return "http://my-ftp-server.com/futures-data-" + date.to_string("Ymd") + ".zip" # OR simply return a fixed small data file. Large files will slow down your backtest subscription = SubscriptionDataSource("https://www.quantconnect.com/api/v2/proxy/nasdaq/api/v3/datatables/QDL/BITFINEX.csv?code=BTCUSD&api_key=WyAazVXnq7ATy_fefTqm") subscription.sort = True return subscription def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData: coin = Bitcoin() coin.symbol = config.symbol if is_live_mode: # Example Line Format: # {"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"} try: live_btc = json.loads(line) # If value is zero, return None value = live_btc["last"] if value == 0: return coin coin.time = datetime.now() coin.value = value coin["Open"] = float(live_btc["open"]) coin["High"] = float(live_btc["high"]) coin["Low"] = float(live_btc["low"]) coin["Close"] = float(live_btc["last"]) coin["Ask"] = float(live_btc["ask"]) coin["Bid"] = float(live_btc["bid"]) coin["VolumeBTC"] = float(live_btc["volume"]) coin["WeightedPrice"] = float(live_btc["vwap"]) return coin except ValueError: # Do nothing, possible error in json decoding return coin # Example Line Format: #code date high low mid last bid ask volume #BTCUSD 2024-10-08 63248.0 61940.0 62246.5 62245.0 62246.0 62247.0 5.929230648356 if not (line.strip() and line[7].isdigit()): return coin try: data = line.split(',') coin.time = datetime.strptime(data[1], "%Y-%m-%d") coin.end_time = coin.time + timedelta(1) coin.value = float(data[5]) coin["High"] = float(data[2]) coin["Low"] = float(data[3]) coin["Mid"] = float(data[4]) coin["Close"] = float(data[5]) coin["Bid"] = float(data[6]) coin["Ask"] = float(data[7]) coin["VolumeBTC"] = float(data[8]) return coin except ValueError: # Do nothing, possible error in json decoding return coin ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm asserting that the option chain APIs return consistent values. See QCAlgorithm.OptionChain(Symbol) and QCAlgorithm.OptionChainProvider
```python from datetime import datetime from AlgorithmImports import * class OptionChainApisConsistencyRegressionAlgorithm(QCAlgorithm): def initialize(self) -> None: test_date = self.get_test_date() self.set_start_date(test_date) self.set_end_date(test_date) option = self.get_option() option_chain_from_algorithm_api = [x.symbol for x in self.option_chain(option.symbol).contracts.values()] exchange_time = Extensions.convert_from_utc(self.utc_time, option.exchange.time_zone) option_chain_from_provider_api = list(self.option_chain_provider.get_option_contract_list(option.symbol, exchange_time)) if len(option_chain_from_algorithm_api) == 0: raise AssertionError("No options in chain from algorithm API") if len(option_chain_from_provider_api) == 0: raise AssertionError("No options in chain from provider API") if len(option_chain_from_algorithm_api) != len(option_chain_from_provider_api): raise AssertionError(f"Expected {len(option_chain_from_provider_api)} options in chain from provider API, " f"but got {len(option_chain_from_algorithm_api)}") for i in range(len(option_chain_from_algorithm_api)): symbol1 = option_chain_from_algorithm_api[i] symbol2 = option_chain_from_provider_api[i] if symbol1 != symbol2: raise AssertionError(f"Expected {symbol2} in chain from provider API, but got {symbol1}") def get_test_date(self) -> datetime: return datetime(2015, 12, 25) def get_option(self) -> Option: return self.add_option("GOOG") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Shows how setting to use the SecurityMarginModel.null (or BuyingPowerModel.NULL) to disable the sufficient margin call verification. See also: <see cref="OptionEquityBullCallSpreadRegressionAlgorithm"/>
```python from AlgorithmImports import * class NullBuyingPowerOptionBullCallSpreadAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2015, 12, 24) self.set_end_date(2015, 12, 24) self.set_cash(200000) self.set_security_initializer(lambda security: security.set_margin_model(SecurityMarginModel.NULL)) self.portfolio.set_positions(SecurityPositionGroupModel.NULL) equity = self.add_equity("GOOG") option = self.add_option(equity.symbol) self.option_symbol = option.symbol option.set_filter(-2, 2, 0, 180) def on_data(self, slice): if self.portfolio.invested or not self.is_market_open(self.option_symbol): return chain = slice.option_chains.get(self.option_symbol) if chain: call_contracts = [x for x in chain if x.right == OptionRight.CALL] expiry = min(x.expiry for x in call_contracts) call_contracts = sorted([x for x in call_contracts if x.expiry == expiry], key = lambda x: x.strike) long_call = call_contracts[0] short_call = [x for x in call_contracts if x.strike > long_call.strike][0] quantity = 1000 tickets = [ self.market_order(short_call.symbol, -quantity), self.market_order(long_call.symbol, quantity) ] for ticket in tickets: if ticket.status != OrderStatus.FILLED: raise AssertionError(f"There should be no restriction on buying {ticket.quantity} of {ticket.symbol} with BuyingPowerModel.NULL") def on_end_of_algorithm(self) -> None: if self.portfolio.total_margin_used != 0: raise AssertionError("The TotalMarginUsed should be zero to avoid margin calls.") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests In The Money (ITM) index option expiry for puts. We expect 2 orders from the algorithm, which are: * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1) * Option exercise, receiving cash (sell, qty -1) Additionally, we test delistings for index options and assert that our portfolio holdings reflect the orders the algorithm has submitted.
```python from AlgorithmImports import * class IndexOptionPutITMExpiryRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2021, 1, 4) self.set_end_date(2021, 1, 31) self.spx = self.add_index("SPX", Resolution.MINUTE).symbol # Select a index option expiring ITM, and adds it to the algorithm. self.spx_options = list(self.option_chain(self.spx)) self.spx_options = [i for i in self.spx_options if i.id.strike_price >= 4200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1] self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price))[0] self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.PUT, 4200, datetime(2021, 1, 15)) if self.spx_option != self.expected_contract: raise AssertionError(f"Contract {self.expected_contract} was not found in the chain") self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, 1)) def on_data(self, data: Slice): # Assert delistings, so that we can make sure that we receive the delisting warnings at # the expected time. These assertions detect bug #4872 for delisting in data.delistings.values(): if delisting.type == DelistingType.WARNING: if delisting.time != datetime(2021, 1, 15): raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}") if delisting.type == DelistingType.DELISTED: if delisting.time != datetime(2021, 1, 16): raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}") def on_order_event(self, order_event: OrderEvent): if order_event.status != OrderStatus.FILLED: # There's lots of noise with OnOrderEvent, but we're only interested in fills. return if order_event.symbol not in self.securities: raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}") security = self.securities[order_event.symbol] if security.symbol == self.spx: self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_contract]) elif security.symbol == self.expected_contract: self.assert_index_option_contract_order(order_event, security) else: raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}") def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security): expected_liquidation_time_utc = datetime(2021, 1, 15) if order_event.direction == OrderDirection.BUY and order_event.utc_time != expected_liquidation_time_utc: raise AssertionError(f"Liquidated index option contract, but not at the expected time. Expected: {expected_liquidation_time_utc} - found {order_event.utc_time}") # No way to detect option exercise orders or any other kind of special orders # other than matching strings, for now. if "Option Exercise" in order_event.message: if order_event.fill_price != 3300: raise AssertionError("Option did not exercise at expected strike price (3300)") if option_contract.holdings.quantity != 0: raise AssertionError(f"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}") def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security): if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1: raise AssertionError(f"No holdings were created for option contract {option.symbol}") if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0: raise AssertionError(f"Holdings were found after a filled option exercise") if "Exercise" in order_event.message and option.holdings.quantity != 0: raise AssertionError(f"Holdings were found after exercising option contract {option.symbol}") ### <summary> ### Ran at the end of the algorithm to ensure the algorithm has no holdings ### </summary> ### <exception cref="Exception">The algorithm has holdings</exception> def on_end_of_algorithm(self): if self.portfolio.invested: raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm tests In The Money (ITM) future option expiry for short puts. We expect 3 orders from the algorithm, which are: * Initial entry, sell ES Put Option (expiring ITM) * Option assignment, buy 1 contract of the underlying (ES) * Future contract expiry, liquidation (sell 1 ES future) Additionally, we test delistings for future options and assert that our portfolio holdings reflect the orders the algorithm has submitted.
```python from AlgorithmImports import * class FutureOptionShortPutITMExpiryRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2020, 1, 5) self.set_end_date(2020, 6, 30) self.es19m20 = self.add_future_contract( Symbol.create_future( Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 6, 19)), Resolution.MINUTE).symbol # Select a future option expiring ITM, and adds it to the algorithm. self.es_option = self.add_future_option_contract( list( sorted( [x for x in self.option_chain(self.es19m20) if x.id.strike_price <= 3400.0 and x.id.option_right == OptionRight.PUT], key=lambda x: x.id.strike_price, reverse=True ) )[0], Resolution.MINUTE).symbol self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3400.0, datetime(2020, 6, 19)) if self.es_option != self.expected_contract: raise AssertionError(f"Contract {self.expected_contract} was not found in the chain") self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order) def scheduled_market_order(self): self.market_order(self.es_option, -1) def on_data(self, data: Slice): # Assert delistings, so that we can make sure that we receive the delisting warnings at # the expected time. These assertions detect bug #4872 for delisting in data.delistings.values(): if delisting.type == DelistingType.WARNING: if delisting.time != datetime(2020, 6, 19): raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}") if delisting.type == DelistingType.DELISTED: if delisting.time != datetime(2020, 6, 20): raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}") def on_order_event(self, order_event: OrderEvent): if order_event.status != OrderStatus.FILLED: # There's lots of noise with OnOrderEvent, but we're only interested in fills. return if not self.securities.contains_key(order_event.symbol): raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}") security = self.securities[order_event.symbol] if security.symbol == self.es19m20: self.assert_future_option_order_exercise(order_event, security, self.securities[self.expected_contract]) elif security.symbol == self.expected_contract: self.assert_future_option_contract_order(order_event, security) else: raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}") self.log(f"{order_event}") def assert_future_option_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security): if "Assignment" in order_event.message: if order_event.fill_price != 3400.0: raise AssertionError("Option was not assigned at expected strike price (3400)") if order_event.direction != OrderDirection.BUY or future.holdings.quantity != 1: raise AssertionError(f"Expected Qty: 1 futures holdings for assigned future {future.symbol}, found {future.holdings.quantity}") return if order_event.direction == OrderDirection.SELL and future.holdings.quantity != 0: # We buy back the underlying at expiration, so we expect a neutral position then raise AssertionError(f"Expected no holdings when liquidating future contract {future.symbol}") def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security): if order_event.direction == OrderDirection.SELL and option.holdings.quantity != -1: raise AssertionError(f"No holdings were created for option contract {option.symbol}") if order_event.is_assignment and option.holdings.quantity != 0: raise AssertionError(f"Holdings were found after option contract was assigned: {option.symbol}") def on_end_of_algorithm(self): if self.portfolio.invested: raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Options Open Interest data regression test.
```python from AlgorithmImports import * class OptionOpenInterestRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_cash(1000000) self.set_start_date(2014,6,5) self.set_end_date(2014,6,6) option = self.add_option("TWX") # set our strike/expiry filter for this option chain option.set_filter(-10, 10, timedelta(0), timedelta(365*2)) # use the underlying equity as the benchmark self.set_benchmark("TWX") def on_data(self, slice): if not self.portfolio.invested: for chain in slice.option_chains: for contract in chain.value: if float(contract.symbol.id.strike_price) == 72.5 and \ contract.symbol.id.option_right == OptionRight.CALL and \ contract.symbol.id.date == datetime(2016, 1, 15): history = self.history(OpenInterest, contract.symbol, timedelta(1))["openinterest"] if len(history.index) == 0 or 0 in history.values: raise ValueError("Regression test failed: open interest history request is empty") security = self.securities[contract.symbol] open_interest_cache = security.cache.get_data(OpenInterest) if open_interest_cache == None: raise ValueError("Regression test failed: current open interest isn't in the security cache") if slice.time.date() == datetime(2014, 6, 5).date() and (contract.open_interest != 50 or security.open_interest != 50): raise ValueError("Regression test failed: current open interest was not correctly loaded and is not equal to 50") if slice.time.date() == datetime(2014, 6, 6).date() and (contract.open_interest != 70 or security.open_interest != 70): raise ValueError("Regression test failed: current open interest was not correctly loaded and is not equal to 70") if slice.time.date() == datetime(2014, 6, 6).date(): self.market_order(contract.symbol, 1) self.market_on_close_order(contract.symbol, -1) if all(contract.open_interest == 0 for contract in chain.value): raise ValueError("Regression test failed: open interest is zero for all contracts") def on_order_event(self, order_event): self.log(str(order_event)) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : We add an option contract using 'QCAlgorithm.add_option_contract' and place a trade, the underlying gets deselected from the universe selection but should still be present since we manually added the option contract. Later we call 'QCAlgorithm.remove_option_contract' and expect both option and underlying to be removed.
```python from AlgorithmImports import * class AddOptionContractExpiresRegressionAlgorithm(QCAlgorithm): def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2014, 6, 5) self.set_end_date(2014, 6, 30) self._expiration = datetime(2014, 6, 21) self._option = None self._traded = False self._twx = Symbol.create("TWX", SecurityType.EQUITY, Market.USA) self.add_universe("my-daily-universe-name", self.selector) def selector(self, time): return [ "AAPL" ] def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' if self._option == None: chain = self.option_chain(self._twx) options = sorted(chain, key=lambda x: x.id.symbol) option = next((option for option in options if option.id.date == self._expiration and option.id.option_right == OptionRight.CALL and option.id.option_style == OptionStyle.AMERICAN), None) if option != None: self._option = self.add_option_contract(option).symbol if self._option != None and self.securities[self._option].price != 0 and not self._traded: self._traded = True self.buy(self._option, 1) if self.time > self._expiration and self.securities[self._twx].invested: # we liquidate the option exercised position self.liquidate(self._twx) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm demonstrating the use of custom data sourced from multiple "files" in the object store
```python from AlgorithmImports import * class CustomDataMultiFileObjectStoreRegressionAlgorithm(QCAlgorithm): custom_data = "2017-08-18 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-18 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-18 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-18 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-18 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-18 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-18 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-18 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-18 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-18 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-18 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-18 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-18 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-18 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-18 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-18 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57\n2017-08-19 01:00:00,5771.75,5792.9,5738.6,5760.2,140394424,5894.04\n2017-08-19 02:00:00,5709.35,5729.85,5683.1,5699.1,142041404,5462.45\n2017-08-19 03:00:00,5748.95,5819.4,5739.4,5808.4,124410018,5121.33\n2017-08-19 04:00:00,5820.4,5854.9,5770.25,5850.05,107160887,4560.84\n2017-08-19 05:00:00,5841.9,5863.4,5804.3,5813.6,117541145,4591.91\n2017-08-19 06:00:00,5805.75,5828.4,5777.9,5822.25,115539008,4643.17\n2017-08-19 07:00:00,5754.15,5755,5645.65,5655.9,198400131,7148\n2017-08-19 08:00:00,5639.9,5686.15,5616.85,5667.65,182410583,6697.18\n2017-08-19 09:00:00,5638.05,5640,5566.25,5590.25,193488581,6308.88\n2017-08-19 10:00:00,5606.95,5666.25,5570.25,5609.1,196571543,6792.49\n2017-08-19 11:00:00,5627.95,5635.25,5579.35,5588.7,160095940,5939.3\n2017-08-19 12:00:00,5647.95,5699.35,5630.95,5682.35,239029425,9184.29\n2017-08-19 13:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-19 14:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-19 15:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-19 16:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-19 17:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-19 18:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-19 19:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-19 20:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-19 21:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-19 22:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-19 23:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-21 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-21 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-21 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-21 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-21 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-21 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-21 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-21 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-21 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-21 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-21 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-21 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-21 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-21 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-21 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57" def initialize(self): self.set_start_date(2017, 8, 18) self.set_end_date(2017, 8, 21) self.set_cash(100000) self.set_benchmark(lambda x: 0) self.custom_symbol = self.add_data(ExampleCustomData, "ExampleCustomData", Resolution.HOUR).symbol # Saving data here for demonstration and regression testing purposes. # In real scenarios, data has to be saved to the object store before the algorithm starts. # Note: The data is stored in separate files for each date. data = {} for line in self.custom_data.split('\n'): csv = line.split(',') time = datetime.strptime(csv[0], '%Y-%m-%d %H:%M:%S').date() if time not in data: data[time] = line else: data[time] += '\n' + line for date, date_data in data.items(): self.object_store.save(self.get_custom_data_key(date), date_data) self.received_data = [] def on_data(self, slice: Slice): if slice.contains_key(self.custom_symbol): custom_data = slice.get(ExampleCustomData, self.custom_symbol) if custom_data.price == 0: raise AssertionError("Custom data price was not expected to be zero") self.received_data.append(custom_data) def on_end_of_algorithm(self): if not self.received_data: raise AssertionError("Custom data was not fetched") custom_security = self.securities[self.custom_symbol] if custom_security is None or custom_security.price == 0: raise AssertionError("Expected the custom security to be added to the algorithm securities and to have a price that is not zero") # Make sure history requests work as expected history = self.history(ExampleCustomData, self.custom_symbol, self.start_date, self.end_date, Resolution.HOUR) if history.shape[0] != len(self.received_data): raise AssertionError("History request returned more or less data than expected") for i in range(len(self.received_data)): received_data = self.received_data[i] if (history.index[i][0] != received_data.symbol or history.index[i][1] != received_data.time or history[["value"]].values[i][0] != received_data.value or history[["open"]].values[i][0] != received_data.open or history[["high"]].values[i][0] != received_data.high or history[["low"]].values[i][0] != received_data.low or history[["close"]].values[i][0] != received_data.close): raise AssertionError("History request returned different data than expected") @staticmethod def get_custom_data_key(date: date) -> str: return f"CustomData/ExampleCustomData{date.strftime('%Y%m%d')}" class ExampleCustomData(PythonData): CustomDataKey = "" def get_source(self, config, date, is_live): return SubscriptionDataSource(CustomDataMultiFileObjectStoreRegressionAlgorithm.get_custom_data_key(date.date()), SubscriptionTransportMedium.OBJECT_STORE, FileFormat.CSV) def reader(self, config, line, date, is_live): data = line.split(',') obj_data = ExampleCustomData() obj_data.symbol = config.symbol obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S') obj_data.value = float(data[4]) obj_data["Open"] = float(data[1]) obj_data["High"] = float(data[2]) obj_data["Low"] = float(data[3]) obj_data["Close"] = float(data[4]) return obj_data ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This algorithm sends a list of current portfolio targets to Numerai API before each trading day See (https://docs.numer.ai/numerai-signals/signals-overview) for more information about accepted symbols, signals, etc.
```python from AlgorithmImports import * class NumeraiSignalExportDemonstrationAlgorithm(QCAlgorithm): _securities = [] def initialize(self) -> None: ''' Initialize the date and add all equity symbols present in list _symbols ''' self.set_start_date(2020, 10, 7) #Set Start Date self.set_end_date(2020, 10, 12) #Set End Date self.set_cash(100000) #Set Strategy Cash self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices))) # Add the CRSP US Total Market Index constituents, which represents approximately 100% of the investable US Equity market self.etf_symbol = self.add_equity("VTI").symbol self.add_universe(self.universe.etf(self.etf_symbol)) # Create a Scheduled Event to submit signals every trading day at 13:00 UTC self.schedule.on(self.date_rules.every_day(self.etf_symbol), self.time_rules.at(13, 0, TimeZones.UTC), self.submit_signals) # Set Numerai signal export provider # Numerai Public ID: This value is provided by Numerai Signals in their main webpage once you've logged in # and created a API key. See (https://signals.numer.ai/account) numerai_public_id = "" # Numerai Secret ID: This value is provided by Numerai Signals in their main webpage once you've logged in # and created a API key. See (https://signals.numer.ai/account) numerai_secret_id = "" # Numerai Model ID: This value is provided by Numerai Signals in their main webpage once you've logged in # and created a model. See (https://signals.numer.ai/models) numerai_model_id = "" numerai_filename = "" # (Optional) Replace this value with your submission filename # Disable automatic exports as we manually set them self.signal_export.automatic_export_time_span = None # Set Numerai signal export provider self.signal_export.add_signal_export_provider(NumeraiSignalExport(numerai_public_id, numerai_secret_id, numerai_model_id, numerai_filename)) def submit_signals(self) -> None: # Select the subset of ETF constituents we can trade symbols = sorted([security.symbol for security in self._securities if security.has_data]) if len(symbols) == 0: return # Get historical data # close_prices = self.history(symbols, 22, Resolution.DAILY).close.unstack(0) # Create portfolio targets # Numerai requires that at least one of the signals have a unique weight # To ensure they are all unique, this demo gives a linear allocation to each symbol (ie. 1/55, 2/55, ..., 10/55) denominator = len(symbols) * (len(symbols) + 1) / 2 # sum of 1, 2, ..., len(symbols) targets = [PortfolioTarget(symbol, (i+1) / denominator) for i, symbol in enumerate(symbols)] # (Optional) Place trades self.set_holdings(targets) # Send signals to Numerai success = self.signal_export.set_target_portfolio(targets) if not success: self.debug(f"Couldn't send targets at {self.time}") def on_securities_changed(self, changes: SecurityChanges) -> None: for security in changes.removed_securities: if security in self._securities: self._securities.remove(security) self._securities.extend([security for security in changes.added_securities if security.symbol != self.etf_symbol]) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This example demonstrates how to add options for a given underlying equity security. It also shows how you can prefilter contracts easily based on strikes and expirations, and how you can inspect the option chain to pick a specific option contract to trade.
```python from AlgorithmImports import * class BasicTemplateOptionsAlgorithm(QCAlgorithm): underlying_ticker = "GOOG" def initialize(self): self.set_start_date(2015, 12, 24) self.set_end_date(2015, 12, 24) self.set_cash(100000) equity = self.add_equity(self.underlying_ticker) option = self.add_option(self.underlying_ticker) self.option_symbol = option.symbol # set our strike/expiry filter for this option chain option.set_filter(lambda u: (u.strikes(-2, +2) # Expiration method accepts TimeSpan objects or integer for days. # The following statements yield the same filtering criteria .expiration(0, 180))) #.expiration(TimeSpan.zero, TimeSpan.from_days(180)))) # use the underlying equity as the benchmark self.set_benchmark(equity.symbol) def on_data(self, slice): if self.portfolio.invested or not self.is_market_open(self.option_symbol): return chain = slice.option_chains.get(self.option_symbol) if not chain: return # we sort the contracts to find at the money (ATM) contract with farthest expiration contracts = sorted(sorted(sorted(chain, \ key = lambda x: abs(chain.underlying.price - x.strike)), \ key = lambda x: x.expiry, reverse=True), \ key = lambda x: x.right, reverse=True) # if found, trade it if len(contracts) == 0: return symbol = contracts[0].symbol self.market_order(symbol, 1) self.market_on_close_order(symbol, -1) def on_order_event(self, order_event): self.log(str(order_event)) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm asserting that historical data can be requested with tick resolution without requiring a tick resolution subscription
```python from datetime import timedelta from AlgorithmImports import * class TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 8) self.set_end_date(2013, 10, 8) # Subscribing SPY and IBM with daily and hour resolution instead of tick resolution spy = self.add_equity("SPY", Resolution.DAILY).symbol ibm = self.add_equity("IBM", Resolution.HOUR).symbol # Requesting history for SPY and IBM (separately) with tick resolution spy_history = self.history[Tick](spy, timedelta(days=1), Resolution.TICK) if not any(spy_history): raise AssertionError("SPY tick history is empty") ibm_history = self.history[Tick](ibm, timedelta(days=1), Resolution.TICK) if not any(ibm_history): raise AssertionError("IBM tick history is empty") # Requesting history for SPY and IBM (together) with tick resolution spy_ibm_history = self.history[Tick]([spy, ibm], timedelta(days=1), Resolution.TICK) if not any(spy_ibm_history): raise AssertionError("Compound SPY and IBM tick history is empty") self.quit() ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Basic algorithm demonstrating how to place trailing stop orders.
```python from AlgorithmImports import * class TrailingStopOrderRegressionAlgorithm(QCAlgorithm): '''Basic algorithm demonstrating how to place trailing stop orders.''' buy_trailing_amount = 2 sell_trailing_amount = 0.5 asynchronous_orders = False def initialize(self): self.set_start_date(2013,10, 7) self.set_end_date(2013,10,11) self.set_cash(100000) self._symbol = self.add_equity("SPY").symbol self._buy_order_ticket: OrderTicket = None self._sell_order_ticket: OrderTicket = None self._previous_slice: Slice = None def on_data(self, slice: Slice): if not slice.contains_key(self._symbol): return if self._buy_order_ticket is None: self._buy_order_ticket = self.trailing_stop_order(self._symbol, 100, trailing_amount=self.buy_trailing_amount, trailing_as_percentage=False, asynchronous=self.asynchronous_orders) elif self._buy_order_ticket.status != OrderStatus.FILLED: stop_price = self._buy_order_ticket.get(OrderField.STOP_PRICE) # Get the previous bar to compare to the stop price, # because stop price update attempt with the current slice data happens after OnData. low = self._previous_slice.quote_bars[self._symbol].ask.low if self._previous_slice.quote_bars.contains_key(self._symbol) \ else self._previous_slice.bars[self._symbol].low stop_price_to_market_price_distance = stop_price - low if stop_price_to_market_price_distance > self.buy_trailing_amount: raise AssertionError(f"StopPrice {stop_price} should be within {self.buy_trailing_amount} of the previous low price {low} at all times.") if self._sell_order_ticket is None: if self.portfolio.invested: self._sell_order_ticket = self.trailing_stop_order(self._symbol, -100, trailing_amount=self.sell_trailing_amount, trailing_as_percentage=False, asynchronous=self.asynchronous_orders) elif self._sell_order_ticket.status != OrderStatus.FILLED: stop_price = self._sell_order_ticket.get(OrderField.STOP_PRICE) # Get the previous bar to compare to the stop price, # because stop price update attempt with the current slice data happens after OnData. high = self._previous_slice.quote_bars[self._symbol].bid.high if self._previous_slice.quote_bars.contains_key(self._symbol) \ else self._previous_slice.bars[self._symbol].high stop_price_to_market_price_distance = high - stop_price if stop_price_to_market_price_distance > self.sell_trailing_amount: raise AssertionError(f"StopPrice {stop_price} should be within {self.sell_trailing_amount} of the previous high price {high} at all times.") self._previous_slice = slice def on_order_event(self, orderEvent: OrderEvent): if orderEvent.status == OrderStatus.FILLED: if orderEvent.direction == OrderDirection.BUY: stop_price = self._buy_order_ticket.get(OrderField.STOP_PRICE) if orderEvent.fill_price < stop_price: raise AssertionError(f"Buy trailing stop order should have filled with price greater than or equal to the stop price {stop_price}. " f"Fill price: {orderEvent.fill_price}") else: stop_price = self._sell_order_ticket.get(OrderField.STOP_PRICE) if orderEvent.fill_price > stop_price: raise AssertionError(f"Sell trailing stop order should have filled with price less than or equal to the stop price {stop_price}. " f"Fill price: {orderEvent.fill_price}") def on_end_of_algorithm(self): for ticket in self.transactions.get_order_tickets(): if ticket.submit_request.asynchronous != self.asynchronous_orders: raise AssertionError("Expected all orders to have the same asynchronous flag as the algorithm.") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm asserting the behavior of different callback commands call
```python from AlgorithmImports import * class InvalidCommand(): variable = 10 class VoidCommand(): quantity = 0 target = [] parameters = {} targettime = None def run(self, algo: IAlgorithm) -> bool: if not self.targettime or self.targettime != algo.time: return False tag = self.parameters["tag"] algo.order(self.target[0], self.get_quantity(), tag=tag) return True def get_quantity(self): return self.quantity class BoolCommand(Command): something_else = {} array_test = [] result = False def run(self, algo) -> bool: trade_ibm = self.my_custom_method() if trade_ibm: algo.debug(f"BoolCommand.run: {str(self)}") algo.buy("IBM", 1) return trade_ibm def my_custom_method(self): return self.result class CallbackCommandRegressionAlgorithm(QCAlgorithm): def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.add_equity("SPY") self.add_equity("IBM") self.add_equity("BAC") self.add_command(VoidCommand) self.add_command(BoolCommand) threw_exception = False try: self.add_command(InvalidCommand) except: threw_exception = True if not threw_exception: raise ValueError('InvalidCommand did not throw!') bool_command = BoolCommand() bool_command.result = True bool_command.something_else = { "Property": 10 } bool_command.array_test = [ "SPY", "BTCUSD" ] link = self.link(bool_command) if "&command%5barray_test%5d%5b0%5d=SPY&command%5barray_test%5d%5b1%5d=BTCUSD&command%5bresult%5d=True&command%5bsomething_else%5d%5bProperty%5d=10&command%5b%24type%5d=BoolCommand" not in link: raise ValueError(f'Invalid link was generated! {link}') potential_command = VoidCommand() potential_command.target = [ "BAC" ] potential_command.quantity = 10 potential_command.parameters = { "tag": "Signal X" } command_link = self.link(potential_command) if "&command%5btarget%5d%5b0%5d=BAC&command%5bquantity%5d=10&command%5bparameters%5d%5btag%5d=Signal+X&command%5b%24type%5d=VoidCommand" not in command_link: raise ValueError(f'Invalid link was generated! {command_link}') self.notify.email("email@address", "Trade Command Event", f"Signal X trade\nFollow link to trigger: {command_link}") untyped_command_link = self.link({ "symbol": "SPY", "parameters": { "quantity": 10 } }) if "&command%5bsymbol%5d=SPY&command%5bparameters%5d%5bquantity%5d=10" not in untyped_command_link: raise ValueError(f'Invalid link was generated! {untyped_command_link}') self.notify.email("email@address", "Untyped Command Event", f"Signal Y trade\nFollow link to trigger: {untyped_command_link}") # We need to create a project on QuantConnect to test the broadcast_command method # and use the project_id in the broadcast_command call self.project_id = 21805137 # All live deployments receive the broadcasts below broadcast_result = self.broadcast_command(potential_command) broadcast_result2 = self.broadcast_command({ "symbol": "SPY", "parameters": { "quantity": 10 } }) def on_command(self, data: object) -> bool: self.debug(f"on_command: {str(data)}") self.buy(data.symbol, data.parameters["quantity"]) return True # False, None ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Algorithm demonstrating custom charting support in QuantConnect. The entire charting system of quantconnect is adaptable. You can adjust it to draw whatever you'd like. Charts can be stacked, or overlayed on each other. Series can be candles, lines or scatter plots. Even the default behaviours of QuantConnect can be overridden.
```python from AlgorithmImports import * class CustomChartingAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2016,1,1) self.set_end_date(2017,1,1) self.set_cash(100000) spy = self.add_equity("SPY", Resolution.DAILY).symbol # In your initialize method: # Chart - Master Container for the Chart: stock_plot = Chart("Trade Plot") # On the Trade Plotter Chart we want 3 series: trades and price: stock_plot.add_series(Series("Buy", SeriesType.SCATTER, 0)) stock_plot.add_series(Series("Sell", SeriesType.SCATTER, 0)) stock_plot.add_series(Series("Price", SeriesType.LINE, 0)) self.add_chart(stock_plot) # On the Average Cross Chart we want 2 series, slow MA and fast MA avg_cross = Chart("Average Cross") avg_cross.add_series(Series("FastMA", SeriesType.LINE, 0)) avg_cross.add_series(Series("SlowMA", SeriesType.LINE, 0)) self.add_chart(avg_cross) # There's support for candlestick charts built-in: weekly_spy_plot = Chart("Weekly SPY") spy_candlesticks = CandlestickSeries("SPY") weekly_spy_plot.add_series(spy_candlesticks) self.add_chart(weekly_spy_plot) self.consolidate(spy, Calendar.WEEKLY, lambda bar: self.plot("Weekly SPY", "SPY", bar)) self.fast_ma = 0 self.slow_ma = 0 self.last_price = 0 self.resample = datetime.min self.resample_period = (self.end_date - self.start_date) / 2000 def on_data(self, slice): if slice["SPY"] is None: return self.last_price = slice["SPY"].close if self.fast_ma == 0: self.fast_ma = self.last_price if self.slow_ma == 0: self.slow_ma = self.last_price self.fast_ma = (0.01 * self.last_price) + (0.99 * self.fast_ma) self.slow_ma = (0.001 * self.last_price) + (0.999 * self.slow_ma) if self.time > self.resample: self.resample = self.time + self.resample_period self.plot("Average Cross", "FastMA", self.fast_ma) self.plot("Average Cross", "SlowMA", self.slow_ma) # On the 5th days when not invested buy: if not self.portfolio.invested and self.time.day % 13 == 0: self.order("SPY", (int)(self.portfolio.margin_remaining / self.last_price)) self.plot("Trade Plot", "Buy", self.last_price) elif self.time.day % 21 == 0 and self.portfolio.invested: self.plot("Trade Plot", "Sell", self.last_price) self.liquidate() def on_end_of_day(self, symbol): #Log the end of day prices: self.plot("Trade Plot", "Price", self.last_price) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : def initialize(self):
```python from AlgorithmImports import * class CustomDataTypeHistoryAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2017, 8, 20) self.set_end_date(2017, 8, 20) self._symbol = self.add_data(CustomDataType, "CustomDataType", Resolution.HOUR).symbol history = list(self.history[CustomDataType](self._symbol, 48, Resolution.HOUR)) if len(history) == 0: raise AssertionError("History request returned no data") self._assert_history_data(history) history2 = list(self.history[CustomDataType]([self._symbol], 48, Resolution.HOUR)) if len(history2) != len(history): raise AssertionError("History requests returned different data") self._assert_history_data([y.values()[0] for y in history2]) def _assert_history_data(self, history: List[PythonData]) -> None: expected_keys = ['open', 'close', 'high', 'low', 'some_property'] if any(any(not x[key] for key in expected_keys) or x["some_property"] != "some property value" for x in history): raise AssertionError("History request returned data without the expected properties") class CustomDataType(PythonData): def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live: bool) -> SubscriptionDataSource: source = "https://www.dl.dropboxusercontent.com/s/d83xvd7mm9fzpk0/path_to_my_csv_data.csv?dl=0" return SubscriptionDataSource(source, SubscriptionTransportMedium.REMOTE_FILE) def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live: bool) -> BaseData: if not (line.strip()): return None data = line.split(',') obj_data = CustomDataType() obj_data.symbol = config.symbol try: obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S') + timedelta(hours=20) obj_data["open"] = float(data[1]) obj_data["high"] = float(data[2]) obj_data["low"] = float(data[3]) obj_data["close"] = float(data[4]) obj_data.value = obj_data["close"] # property for asserting the correct data is fetched obj_data["some_property"] = "some property value" except ValueError: return None return obj_data ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Basic template algorithm simply initializes the date range and cash
```python from AlgorithmImports import * class BasicTemplateFillForwardAlgorithm(QCAlgorithm): '''Basic template algorithm simply initializes the date range and cash''' def initialize(self): '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2013,10,7) #Set Start Date self.set_end_date(2013,11,30) #Set End Date self.set_cash(100000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data self.add_security(SecurityType.EQUITY, "ASUR", Resolution.SECOND) def on_data(self, data): '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' if not self.portfolio.invested: self.set_holdings("ASUR", 1) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : We add an option contract using 'QCAlgorithm.add_option_contract' and place a trade, the underlying gets deselected from the universe selection but should still be present since we manually added the option contract. Later we call 'QCAlgorithm.remove_option_contract' and expect both option and underlying to be removed.
```python from AlgorithmImports import * class AddOptionContractFromUniverseRegressionAlgorithm(QCAlgorithm): def initialize(self): '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' self.set_start_date(2014, 6, 5) self.set_end_date(2014, 6, 9) self._expiration = datetime(2014, 6, 21) self._security_changes = None self._option = None self._traded = False self._twx = Symbol.create("TWX", SecurityType.EQUITY, Market.USA) self._aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA) self.universe_settings.resolution = Resolution.MINUTE self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW self.add_universe(self.selector, self.selector) def selector(self, fundamental): if self.time <= datetime(2014, 6, 5): return [ self._twx ] return [ self._aapl ] def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. Arguments: data: Slice object keyed by symbol containing the stock data ''' if self._option != None and self.securities[self._option].price != 0 and not self._traded: self._traded = True self.buy(self._option, 1) if self.time == datetime(2014, 6, 6, 14, 0, 0): # liquidate & remove the option self.remove_option_contract(self._option) def on_securities_changed(self, changes): # keep track of all removed and added securities if self._security_changes == None: self._security_changes = changes else: self._security_changes += changes if any(security.symbol.security_type == SecurityType.OPTION for security in changes.added_securities): return for addedSecurity in changes.added_securities: option_chain = self.option_chain(addedSecurity.symbol) options = sorted(option_chain, key=lambda x: x.id.symbol) option = next((option for option in options if option.id.date == self._expiration and option.id.option_right == OptionRight.CALL and option.id.option_style == OptionStyle.AMERICAN), None) self.add_option_contract(option) # just keep the first we got if self._option == None: self._option = option ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Example algorithm of how to use RangeConsolidator
```python from AlgorithmImports import * class RangeConsolidatorAlgorithm(QCAlgorithm): def get_resolution(self) -> Resolution: return Resolution.DAILY def get_range(self) -> int: return 100 def initialize(self) -> None: self.set_start_and_end_dates() self.add_equity("SPY", self.get_resolution()) range_consolidator = self.create_range_consolidator() range_consolidator.data_consolidated += self.on_data_consolidated self._first_data_consolidated = None self.subscription_manager.add_consolidator("SPY", range_consolidator) def set_start_and_end_dates(self) -> None: self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) def on_end_of_algorithm(self) -> None: if not self._first_data_consolidated: raise AssertionError("The consolidator should have consolidated at least one RangeBar, but it did not consolidated any one") def create_range_consolidator(self) -> RangeConsolidator: return RangeConsolidator(self.get_range()) def on_data_consolidated(self, sender: object, range_bar: RangeBar) -> None: if not self._first_data_consolidated: self._first_data_consolidated = range_bar if round(range_bar.high - range_bar.low, 2) != self.get_range() * 0.01: # The minimum price change for SPY is 0.01, therefore the range size of each bar equals Range * 0.01 raise AssertionError(f"The difference between the High and Low for all RangeBar's should be {self.get_range() * 0.01}, but for this RangeBar was {round(range_bar.low - range_bar.high, 2)}") ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Alpha model for ETF constituents, where we generate insights based on the weighting of the ETF constituent
```python from AlgorithmImports import * constituent_data = [] class ETFConstituentAlphaModel(AlphaModel): def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None: pass ### <summary> ### Creates new insights based on constituent data and their weighting ### in their respective ETF ### </summary> def update(self, algorithm: QCAlgorithm, data: Slice) -> list[Insight]: global constituent_data insights = [] for constituent in constituent_data: if constituent.symbol not in data.bars and \ constituent.symbol not in data.quote_bars: continue insight_direction = InsightDirection.UP if constituent.weight is not None and constituent.weight >= 0.01 else InsightDirection.DOWN insights.append(Insight( algorithm.utc_time, constituent.symbol, timedelta(days=1), InsightType.PRICE, insight_direction, float(1 * int(insight_direction)), 1.0, weight=float(0 if constituent.weight is None else constituent.weight) )) return insights class ETFConstituentPortfolioModel(PortfolioConstructionModel): def __init__(self) -> None: self.has_added = False ### <summary> ### Securities changed, detects if we've got new additions to the universe ### so that we don't try to trade every loop ### </summary> def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None: self.has_added = len(changes.added_securities) != 0 ### <summary> ### Creates portfolio targets based on the insights provided to us by the alpha model. ### Emits portfolio targets setting the quantity to the weight of the constituent ### in its respective ETF. ### </summary> def create_targets(self, algorithm: QCAlgorithm, insights: list[Insight]) -> list[PortfolioTarget]: if not self.has_added: return [] final_insights = [] for insight in insights: final_insights.append(PortfolioTarget(insight.symbol, float(0 if insight.weight is None else insight.weight))) self.has_added = False return final_insights class ETFConstituentExecutionModel(ExecutionModel): ### <summary> ### Liquidates if constituents have been removed from the universe ### </summary> def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None: for change in changes.removed_securities: algorithm.liquidate(change.symbol) ### <summary> ### Creates orders for constituents that attempts to add ### the weighting of the constituent in our portfolio. The ### resulting algorithm portfolio weight might not be equal ### to the leverage of the ETF (1x, 2x, 3x, etc.) ### </summary> def execute(self, algorithm: QCAlgorithm, targets: list[IPortfolioTarget]) -> None: for target in targets: algorithm.set_holdings(target.symbol, target.quantity) class ETFConstituentUniverseFrameworkRegressionAlgorithm(QCAlgorithm): ### <summary> ### Initializes the algorithm, setting up the framework classes and ETF constituent universe settings ### </summary> def initialize(self) -> None: self.set_start_date(2020, 12, 1) self.set_end_date(2021, 1, 31) self.set_cash(100000) self.set_alpha(ETFConstituentAlphaModel()) self.set_portfolio_construction(ETFConstituentPortfolioModel()) self.set_execution(ETFConstituentExecutionModel()) self.universe_settings.resolution = Resolution.HOUR universe = self.add_universe(self.universe.etf("SPY", self.universe_settings, self.filter_etf_constituents)) historical_data = self.history(universe, 1, flatten=True) if len(historical_data) < 200: raise ValueError(f"Unexpected universe DataCollection count {len(historical_data)}! Expected > 200") ### <summary> ### Filters ETF constituents ### </summary> ### <param name="constituents">ETF constituents</param> ### <returns>ETF constituent Symbols that we want to include in the algorithm</returns> def filter_etf_constituents(self, constituents: list[ETFConstituentUniverse]) -> list[Symbol]: global constituent_data constituent_data_local = [i for i in constituents if i.weight and i.weight >= 0.001] constituent_data = list(constituent_data_local) return [i.symbol for i in constituent_data_local] ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : This regression algorithm verifies automatic option contract assignment behavior.
```python from AlgorithmImports import * class OptionAssignmentRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2015, 12, 23) self.set_end_date(2015, 12, 28) self.set_cash(100000) self.stock = self.add_equity("GOOG", Resolution.MINUTE) contracts = list(self.option_chain(self.stock.symbol)) self.put_option_symbol = sorted( [c for c in contracts if c.id.option_right == OptionRight.PUT and c.id.strike_price == 800], key=lambda c: c.id.date )[0] self.call_option_symbol = sorted( [c for c in contracts if c.id.option_right == OptionRight.CALL and c.id.strike_price == 600], key=lambda c: c.id.date )[0] self.put_option = self.add_option_contract(self.put_option_symbol) self.call_option = self.add_option_contract(self.call_option_symbol) def on_data(self, data): if not self.portfolio.invested and self.stock.price != 0 and self.put_option.price != 0 and self.call_option.price != 0: #this gets executed on start and after each auto-assignment, finally ending with expiration assignment if self.time < self.put_option_symbol.id.date: self.market_order(self.put_option_symbol, -1) if self.time < self.call_option_symbol.id.date: self.market_order(self.call_option_symbol, -1) ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : Regression algorithm for fractional forex pair
```python from AlgorithmImports import * class FractionalQuantityRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2015, 11, 12) self.set_end_date(2016, 4, 1) self.set_cash(100000) self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH) self.set_time_zone(TimeZones.UTC) security = self.add_security(SecurityType.CRYPTO, "BTCUSD", Resolution.DAILY, Market.GDAX, False, 1, True) ### The default buying power model for the Crypto security type is now CashBuyingPowerModel. ### Since this test algorithm uses leverage we need to set a buying power model with margin. security.set_buying_power_model(SecurityMarginModel(3.3)) con = TradeBarConsolidator(1) self.subscription_manager.add_consolidator("BTCUSD", con) con.data_consolidated += self.data_consolidated self.set_benchmark(security.symbol) def data_consolidated(self, sender, bar): quantity = math.floor((self.portfolio.cash + self.portfolio.total_fees) / abs(bar.value + 1)) btc_qnty = float(self.portfolio["BTCUSD"].quantity) if not self.portfolio.invested: self.order("BTCUSD", quantity) elif btc_qnty == quantity: self.order("BTCUSD", 0.1) elif btc_qnty == quantity + 0.1: self.order("BTCUSD", 0.01) elif btc_qnty == quantity + 0.11: self.order("BTCUSD", -0.02) elif btc_qnty == quantity + 0.09: # should fail (below minimum order quantity) self.order("BTCUSD", 0.00001) self.set_holdings("BTCUSD", -2.0) self.set_holdings("BTCUSD", 2.0) self.quit() ```
You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.
Generate a LEAN Algorithm that can be described like this : CapmAlphaRankingFrameworkAlgorithm: example of custom scheduled universe selection model Universe Selection inspired by https://www.quantconnect.com/tutorials/strategy-library/capm-alpha-ranking-strategy-on-dow-30-companies
```python from AlgorithmImports import * class CapmAlphaRankingFrameworkAlgorithm(QCAlgorithm): '''CapmAlphaRankingFrameworkAlgorithm: example of custom scheduled universe selection model''' def initialize(self): ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.''' # Set requested data resolution self.universe_settings.resolution = Resolution.MINUTE self.set_start_date(2016, 1, 1) #Set Start Date self.set_end_date(2017, 1, 1) #Set End Date self.set_cash(100000) #Set Strategy Cash # set algorithm framework models self.set_universe_selection(CapmAlphaRankingUniverseSelectionModel()) self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1), 0.025, None)) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) self.set_execution(ImmediateExecutionModel()) self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01)) class CapmAlphaRankingUniverseSelectionModel(UniverseSelectionModel): '''This universe selection model picks stocks with the highest alpha: interception of the linear regression against a benchmark.''' period = 21 benchmark = "SPY" # Symbols of Dow 30 companies. _symbols = [Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in ["AAPL", "AXP", "BA", "CAT", "CSCO", "CVX", "DD", "DIS", "GE", "GS", "HD", "IBM", "INTC", "JPM", "KO", "MCD", "MMM", "MRK", "MSFT", "NKE","PFE", "PG", "TRV", "UNH", "UTX", "V", "VZ", "WMT", "XOM"]] def create_universes(self, algorithm): # Adds the benchmark to the user defined universe benchmark = algorithm.add_equity(self.benchmark, Resolution.DAILY) # Defines a schedule universe that fires after market open when the month starts return [ ScheduledUniverse( benchmark.exchange.time_zone, algorithm.date_rules.month_start(self.benchmark), algorithm.time_rules.after_market_open(self.benchmark), lambda datetime: self.select_pair(algorithm, datetime), algorithm.universe_settings)] def select_pair(self, algorithm, date): '''Selects the pair (two stocks) with the highest alpha''' dictionary = dict() benchmark = self._get_returns(algorithm, self.benchmark) ones = np.ones(len(benchmark)) for symbol in self._symbols: prices = self._get_returns(algorithm, symbol) if prices is None: continue A = np.vstack([prices, ones]).T # Calculate the Least-Square fitting to the returns of a given symbol and the benchmark ols = np.linalg.lstsq(A, benchmark)[0] dictionary[symbol] = ols[1] # Returns the top 2 highest alphas ordered_dictionary = sorted(dictionary.items(), key= lambda x: x[1], reverse=True) return [x[0] for x in ordered_dictionary[:2]] def _get_returns(self, algorithm, symbol): history = algorithm.history([symbol], self.period, Resolution.DAILY) if history.empty: return None window = RollingWindow(self.period) rate_of_change = RateOfChange(1) def roc_updated(s, item): window.add(item.value) rate_of_change.updated += roc_updated history = history.close.reset_index(level=0, drop=True).items() for time, value in history: rate_of_change.update(time, value) return [ x for x in window] ```