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 : Algorithm illustrating how to manually set market hours and symbol properties database entries to be picked up by the algorithm's securities. This specific case illustrates how to do it for CFDs to match InteractiveBrokers brokerage, which has different market hours depending on the CFD underlying asset.
```python from AlgorithmImports import * import Newtonsoft.Json as json class ManuallySetMarketHoursAndSymbolPropertiesDatabaseEntriesAlgorithm(QCAlgorithm): ''' Algorithm illustrating how to manually set market hours and symbol properties database entries to be picked up by the algorithm's securities. This specific case illustrates how to do it for CFDs to match InteractiveBrokers brokerage, which has different market hours depending on the CFD underlying asset. ''' def initialize(self): self.set_start_date(2013,10, 7) self.set_end_date(2013,10,11) self.set_cash(100000) self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE) # Some brokerages like InteractiveBrokers make a difference on CFDs depending on the underlying (equity, index, metal, forex). # Depending on this, the market hours can be different. In order to be more specific with the market hours, # we can set the MarketHoursDatabase entry for the CFDs. # Equity CFDs are usually traded the same hours as the equity market. equity_market_hours_entry = self.market_hours_database.get_entry(Market.USA, Symbol.EMPTY, SecurityType.EQUITY) self.market_hours_database.set_entry(Market.INTERACTIVE_BROKERS, "", SecurityType.CFD, equity_market_hours_entry.exchange_hours, equity_market_hours_entry.data_time_zone) # The same can be done for the symbol properties, in case they are different depending on the underlying equity_symbol_properties = self.symbol_properties_database.get_symbol_properties(Market.USA, Symbol.EMPTY, SecurityType.EQUITY, Currencies.USD) self.symbol_properties_database.set_entry(Market.INTERACTIVE_BROKERS, "", SecurityType.CFD, equity_symbol_properties) spy_cfd = self.add_cfd("SPY", market=Market.INTERACTIVE_BROKERS) if json.JsonConvert.serialize_object(spy_cfd.exchange.hours) != json.JsonConvert.serialize_object(equity_market_hours_entry.exchange_hours): raise AssertionError("Expected the SPY CFD market hours to be the same as the underlying equity market hours.") if json.JsonConvert.serialize_object(spy_cfd.symbol_properties) != json.JsonConvert.serialize_object(equity_symbol_properties): raise AssertionError("Expected the SPY CFD symbol properties to be the same as the underlying equity symbol properties.") # We can also do it for a specific ticker aud_usd_forex_market_hours_entry = self.market_hours_database.get_entry(Market.OANDA, Symbol.EMPTY, SecurityType.FOREX) self.market_hours_database.set_entry(Market.INTERACTIVE_BROKERS, "AUDUSD", SecurityType.CFD, aud_usd_forex_market_hours_entry.exchange_hours, aud_usd_forex_market_hours_entry.data_time_zone) aud_usd_forex_symbol_properties = self.symbol_properties_database.get_symbol_properties(Market.OANDA, "AUDUSD", SecurityType.FOREX, Currencies.USD) self.symbol_properties_database.set_entry(Market.INTERACTIVE_BROKERS, "AUDUSD", SecurityType.CFD, aud_usd_forex_symbol_properties) aud_usd_cfd = self.add_cfd("AUDUSD", market=Market.INTERACTIVE_BROKERS) if json.JsonConvert.serialize_object(aud_usd_cfd.exchange.hours) != json.JsonConvert.serialize_object(aud_usd_forex_market_hours_entry.exchange_hours): raise AssertionError("Expected the AUDUSD CFD market hours to be the same as the underlying forex market hours.") if json.JsonConvert.serialize_object(aud_usd_cfd.symbol_properties) != json.JsonConvert.serialize_object(aud_usd_forex_symbol_properties): raise AssertionError("Expected the AUDUSD CFD symbol properties to be the same as the underlying forex symbol properties.") ```
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 is a regression test for issue #2018 and PR #2038.
```python from AlgorithmImports import * class OptionDataNullReferenceRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2016, 12, 1) self.set_end_date(2017, 1, 1) self.set_cash(500000) self.add_equity("DUST") option = self.add_option("DUST") option.set_filter(self.universe_func) def universe_func(self, universe): return universe.include_weeklys().strikes(-1, +1).expiration(timedelta(25), timedelta(100)) ```
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 using the history provider to retrieve data to warm up indicators before data is received.
```python from AlgorithmImports import * class WarmupHistoryAlgorithm(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,5,2) #Set Start Date self.set_end_date(2014,5,2) #Set End Date self.set_cash(100000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data forex = self.add_forex("EURUSD", Resolution.SECOND) forex = self.add_forex("NZDUSD", Resolution.SECOND) fast_period = 60 slow_period = 3600 self.fast = self.ema("EURUSD", fast_period) self.slow = self.ema("EURUSD", slow_period) # "slow_period + 1" because rolling window waits for one to fall off the back to be considered ready # History method returns a dict with a pandas.data_frame history = self.history(["EURUSD", "NZDUSD"], slow_period + 1) # prints out the tail of the dataframe self.log(str(history.loc["EURUSD"].tail())) self.log(str(history.loc["NZDUSD"].tail())) for index, row in history.loc["EURUSD"].iterrows(): self.fast.update(index, row["close"]) self.slow.update(index, row["close"]) self.log("FAST {0} READY. Samples: {1}".format("IS" if self.fast.is_ready else "IS NOT", self.fast.samples)) self.log("SLOW {0} READY. Samples: {1}".format("IS" if self.slow.is_ready else "IS NOT", self.slow.samples)) def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' if self.fast.current.value > self.slow.current.value: self.set_holdings("EURUSD", 1) else: self.set_holdings("EURUSD", -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 : The demonstration algorithm shows some of the most common order methods when working with FutureOption assets.
```python from AlgorithmImports import * class BasicTemplateFutureOptionAlgorithm(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, 1, 1) self.set_end_date(2022, 2, 1) self.set_cash(100000) gold_futures = self.add_future(Futures.Metals.GOLD, Resolution.MINUTE) gold_futures.set_filter(0, 180) self._symbol = gold_futures.symbol self.add_future_option(self._symbol, lambda universe: universe.strikes(-5, +5) .calls_only() .back_month() .only_apply_filter_at_market_open()) # Historical Data history = self.history(self._symbol, 60, Resolution.DAILY) self.log(f"Received {len(history)} bars from {self._symbol} FutureOption historical data call.") 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: slice: Slice object keyed by symbol containing the stock data ''' # Access Data for kvp in data.option_chains: underlying_future_contract = kvp.key.underlying chain = kvp.value if not chain: continue for contract in chain: self.log(f"""Canonical Symbol: {kvp.key}; Contract: {contract}; Right: {contract.right}; Expiry: {contract.expiry}; Bid price: {contract.bid_price}; Ask price: {contract.ask_price}; Implied Volatility: {contract.implied_volatility}""") if not self.portfolio.invested: atm_strike = sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike))[0].strike selected_contract = sorted([contract for contract in chain if contract.strike == atm_strike], \ key = lambda x: x.expiry, reverse=True)[0] self.market_order(selected_contract.symbol, 1) def on_order_event(self, order_event): self.debug("{} {}".format(self.time, order_event.to_string())) ```
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 execute a Call Butterfly option equity strategy It adds options for a given underlying equity security, and shows how you can prefilter contracts easily based on strikes and expirations
```python from AlgorithmImports import * class BasicTemplateOptionEquityStrategyAlgorithm(QCAlgorithm): underlying_ticker = "GOOG" def initialize(self) -> None: self.set_start_date(2015, 12, 24) self.set_end_date(2015, 12, 24) 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))) def on_data(self, slice: Slice) -> None: 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 grouped_by_expiry = dict() for contract in [contract for contract in chain if contract.right == OptionRight.CALL]: grouped_by_expiry.setdefault(int(contract.expiry.timestamp()), []).append(contract) first_expiry = list(sorted(grouped_by_expiry))[0] call_contracts = sorted(grouped_by_expiry[first_expiry], key = lambda x: x.strike) expiry = call_contracts[0].expiry lower_strike = call_contracts[0].strike middle_strike = call_contracts[1].strike higher_strike = call_contracts[2].strike option_strategy = OptionStrategies.call_butterfly(self._option_symbol, higher_strike, middle_strike, lower_strike, expiry) self.order(option_strategy, 10) def on_order_event(self, order_event: OrderEvent) -> None: 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 : Example of custom fill model for security to only fill bars of data obtained after the order was placed. This is to encourage more pessimistic fill models and eliminate the possibility to fill on old market data that may not be relevant.
```python from AlgorithmImports import * class ForwardDataOnlyFillModelAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013,10,1) self.set_end_date(2013,10,31) self.security = self.add_equity("SPY", Resolution.HOUR) self.security.set_fill_model(ForwardDataOnlyFillModel()) self.schedule.on(self.date_rules.week_start(), self.time_rules.after_market_open(self.security.symbol), self.trade) def trade(self): if not self.portfolio.invested: if self.time.hour != 9 or self.time.minute != 30: raise AssertionError(f"Unexpected event time {self.time}") ticket = self.buy("SPY", 1) if ticket.status != OrderStatus.SUBMITTED: raise AssertionError(f"Unexpected order status {ticket.status}") def on_order_event(self, order_event: OrderEvent): self.debug(f"OnOrderEvent:: {order_event}") if order_event.status == OrderStatus.FILLED and (self.time.hour != 10 or self.time.minute != 0): raise AssertionError(f"Unexpected fill time {self.time}") class ForwardDataOnlyFillModel(EquityFillModel): def fill(self, parameters: FillModelParameters): order_local_time = Extensions.convert_from_utc(parameters.order.time, parameters.security.exchange.time_zone) for data_type in [ QuoteBar, TradeBar, Tick ]: data = parameters.security.cache.get_data(data_type) if not data is None and order_local_time <= data.end_time: return super().fill(parameters) return Fill([]) ```
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 on how to access order tickets right after placing an order.
```python from datetime import timedelta from AlgorithmImports import * class OrderTicketAssignmentDemoAlgorithm(QCAlgorithm): '''Demonstration on how to access order tickets right after placing an order.''' 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.trade_count = 0 self.consolidate(self._symbol, timedelta(hours=1), self.hour_consolidator) def hour_consolidator(self, bar: TradeBar): # Reset self.ticket to None on each new bar self.ticket = None self.ticket = self.market_order(self._symbol, 1, asynchronous=True) self.debug(f"{self.time}: Buy: Price {bar.price}, order_id: {self.ticket.order_id}") self.trade_count += 1 def on_order_event(self, order_event: OrderEvent): # We cannot access self.ticket directly because it is assigned asynchronously: # this order event could be triggered before self.ticket is assigned. ticket = order_event.ticket if ticket is None: raise AssertionError("Expected order ticket in order event to not be null") if order_event.status == OrderStatus.SUBMITTED and self.ticket is not None: raise AssertionError("Field self.ticket not expected no be assigned on the first order event") self.debug(ticket.to_string()) def on_end_of_algorithm(self): # Just checking that orders were placed if not self.portfolio.invested or self.trade_count != self.transactions.orders_count: raise AssertionError(f"Expected the portfolio to have holdings and to have {self.trade_count} trades, but had {self.transactions.orders_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 : Demonstration of using custom fee, slippage, fill, and buying power models for modeling transactions in backtesting. QuantConnect allows you to model all orders as deeply and accurately as you need. This example illustrates how Lean exports its API to Python conforming to PEP8 style guide.
```python from AlgorithmImports import * import random class CustomModelsPEP8Algorithm(QCAlgorithm): '''Demonstration of using custom fee, slippage, fill, and buying power models for modeling transactions in backtesting. QuantConnect allows you to model all orders as deeply and accurately as you need.''' def initialize(self): self.set_start_date(2013,10,1) # Set Start Date self.set_end_date(2013,10,31) # Set End Date self.security = self.add_equity("SPY", Resolution.HOUR) self.spy = self.security.symbol # set our models self.security.set_fee_model(CustomFeeModelPEP8(self)) self.security.set_fill_model(CustomFillModelPEP8(self)) self.security.set_slippage_model(CustomSlippageModelPEP8(self)) self.security.set_buying_power_model(CustomBuyingPowerModelPEP8(self)) def on_data(self, data): open_orders = self.transactions.get_open_orders(self.spy) if len(open_orders) != 0: return if self.time.day > 10 and self.security.holdings.quantity <= 0: quantity = self.calculate_order_quantity(self.spy, .5) self.log(f"MarketOrder: {quantity}") self.market_order(self.spy, quantity, True) # async needed for partial fill market orders elif self.time.day > 20 and self.security.holdings.quantity >= 0: quantity = self.calculate_order_quantity(self.spy, -.5) self.log(f"MarketOrder: {quantity}") self.market_order(self.spy, quantity, True) # async needed for partial fill market orders class CustomFillModelPEP8(ImmediateFillModel): def __init__(self, algorithm): super().__init__() self.algorithm = algorithm self.absolute_remaining_by_order_id = {} self.random = Random(387510346) def market_fill(self, asset, order): absolute_remaining = order.absolute_quantity if order.id in self.absolute_remaining_by_order_id.keys(): absolute_remaining = self.absolute_remaining_by_order_id[order.id] fill = super().market_fill(asset, order) absolute_fill_quantity = int(min(absolute_remaining, self.random.next(0, 2*int(order.absolute_quantity)))) fill.fill_quantity = np.sign(order.quantity) * absolute_fill_quantity if absolute_remaining == absolute_fill_quantity: fill.status = OrderStatus.FILLED if self.absolute_remaining_by_order_id.get(order.id): self.absolute_remaining_by_order_id.pop(order.id) else: absolute_remaining = absolute_remaining - absolute_fill_quantity self.absolute_remaining_by_order_id[order.id] = absolute_remaining fill.status = OrderStatus.PARTIALLY_FILLED self.algorithm.log(f"CustomFillModel: {fill}") return fill class CustomFeeModelPEP8(FeeModel): def __init__(self, algorithm): super().__init__() self.algorithm = algorithm def get_order_fee(self, parameters): # custom fee math fee = max(1, parameters.security.price * parameters.order.absolute_quantity * 0.00001) self.algorithm.log(f"CustomFeeModel: {fee}") return OrderFee(CashAmount(fee, "USD")) class CustomSlippageModelPEP8: def __init__(self, algorithm): self.algorithm = algorithm def get_slippage_approximation(self, asset, order): # custom slippage math slippage = asset.price * 0.0001 * np.log10(2*float(order.absolute_quantity)) self.algorithm.log(f"CustomSlippageModel: {slippage}") return slippage class CustomBuyingPowerModelPEP8(BuyingPowerModel): def __init__(self, algorithm): super().__init__() self.algorithm = algorithm def has_sufficient_buying_power_for_order(self, parameters): # custom behavior: this model will assume that there is always enough buying power has_sufficient_buying_power_for_order_result = HasSufficientBuyingPowerForOrderResult(True) self.algorithm.log(f"CustomBuyingPowerModel: {has_sufficient_buying_power_for_order_result.is_sufficient}") return has_sufficient_buying_power_for_order_result class SimpleCustomFillModelPEP8(FillModel): def __init__(self): super().__init__() def _create_order_event(self, asset, order): utc_time = Extensions.convert_to_utc(asset.local_time, asset.exchange.time_zone) return OrderEvent(order, utc_time, OrderFee.ZERO) def _set_order_event_to_filled(self, fill, fill_price, fill_quantity): fill.status = OrderStatus.FILLED fill.fill_quantity = fill_quantity fill.fill_price = fill_price return fill def _get_trade_bar(self, asset, order_direction): trade_bar = asset.cache.get_data(TradeBar) if trade_bar: return trade_bar price = asset.price return TradeBar(asset.local_time, asset.symbol, price, price, price, price, 0) def market_fill(self, asset, order): fill = self._create_order_event(asset, order) if order.status == OrderStatus.CANCELED: return fill fill_price = asset.cache.ask_price if order.direction == OrderDirection.BUY else asset.cache.bid_price return self._set_order_event_to_filled(fill, fill_price, order.quantity) def stop_market_fill(self, asset, order): fill = self._create_order_event(asset, order) if order.status == OrderStatus.CANCELED: return fill stop_price = order.stop_price trade_bar = self._get_trade_bar(asset, order.direction) if order.direction == OrderDirection.SELL and trade_bar.low < stop_price: return self._set_order_event_to_filled(fill, stop_price, order.quantity) if order.direction == OrderDirection.BUY and trade_bar.high > stop_price: return self._set_order_event_to_filled(fill, stop_price, order.quantity) return fill def limit_fill(self, asset, order): fill = self._create_order_event(asset, order) if order.status == OrderStatus.CANCELED: return fill limit_price = order.limit_price trade_bar = self._get_trade_bar(asset, order.direction) if order.direction == OrderDirection.SELL and trade_bar.high > limit_price: return self._set_order_event_to_filled(fill, limit_price, order.quantity) if order.direction == OrderDirection.BUY and trade_bar.low < limit_price: return self._set_order_event_to_filled(fill, limit_price, order.quantity) return fill ```
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 as a combination of use the coarse fundamental data and fine fundamental data
```python from AlgorithmImports import * class CoarseFineFundamentalRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2014,3,24) #Set Start Date self.set_end_date(2014,4,7) #Set End Date self.set_cash(50000) #Set Strategy Cash self.universe_settings.resolution = Resolution.DAILY # this add universe method accepts two parameters: # - coarse selection function: accepts an List[CoarseFundamental] and returns an List[Symbol] # - fine selection function: accepts an List[FineFundamental] and returns an List[Symbol] self.add_universe(self.coarse_selection_function, self.fine_selection_function) self.changes = None self.number_of_symbols_fine = 2 # return a list of three fixed symbol objects def coarse_selection_function(self, coarse): tickers = [ "GOOG", "BAC", "SPY" ] if self.time.date() < date(2014, 4, 1): tickers = [ "AAPL", "AIG", "IBM" ] return [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers ] # sort the data by market capitalization and take the top 'number_of_symbols_fine' def fine_selection_function(self, fine): # sort descending by market capitalization sorted_by_market_cap = sorted(fine, key=lambda x: x.market_cap, reverse=True) # take the top entries from our sorted collection return [ x.symbol for x in sorted_by_market_cap[:self.number_of_symbols_fine] ] 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: if (security.fundamentals.earning_ratios.equity_per_share_growth.one_year > 0.25): self.set_holdings(security.symbol, 0.5) self.debug("Purchased Stock: " + str(security.symbol.value)) 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 algorithm tests the functionality of the CompositeIndicator using either a lambda expression or a method reference.
```python from AlgorithmImports import * class CompositeIndicatorWorksAsExpectedRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 4) self.set_end_date(2013, 10, 5) self.add_equity("SPY", Resolution.MINUTE) close = self.identity("SPY", Resolution.MINUTE, Field.CLOSE) low = self.min("SPY", 420, Resolution.MINUTE, Field.LOW) self.composite_min_direct = CompositeIndicator("CompositeMinDirect", close, low, lambda l, r: IndicatorResult(min(l.current.value, r.current.value))) self.composite_min_method = CompositeIndicator("CompositeMinMethod", close, low, self.composer) self.data_received = False def composer(self, l, r): return IndicatorResult(min(l.current.value, r.current.value)) def on_data(self, data): self.data_received = True if self.composite_min_direct.current.value != self.composite_min_method.current.value: raise AssertionError(f"Values of indicators differ: {self.composite_min_direct.current.value} | {self.composite_min_method.current.value}") def on_end_of_algorithm(self): if not self.data_received: raise AssertionError("No data was processed during the 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 : Example algorithm giving an introduction into using IDataConsolidators. This is an advanced QC concept and requires a certain level of comfort using C# and its event system. What is an IDataConsolidator? IDataConsolidator is a plugin point that can be used to transform your data more easily. In this example we show one of the simplest consolidators, the TradeBarConsolidator. This type is capable of taking a timespan to indicate how long each bar should be, or an integer to indicate how many bars should be aggregated into one. When a new 'consolidated' piece of data is produced by the IDataConsolidator, an event is fired with the argument of the new data.
```python from AlgorithmImports import * class DataConsolidationAlgorithm(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) #Set Start Date self.set_end_date(2013, 12, 7) #Set End Date # Find more symbols here: http://quantconnect.com/data self.add_equity("SPY") self.add_forex("EURUSD", Resolution.HOUR) # define our 30 minute trade bar consolidator. we can # access the 30 minute bar from the DataConsolidated events thirty_minute_consolidator = TradeBarConsolidator(timedelta(minutes=30)) # attach our event handler. the event handler is a function that will # be called each time we produce a new consolidated piece of data. thirty_minute_consolidator.data_consolidated += self.thirty_minute_bar_handler # this call adds our 30 minute consolidator to # the manager to receive updates from the engine self.subscription_manager.add_consolidator("SPY", thirty_minute_consolidator) # here we'll define a slightly more complex consolidator. what we're trying to produce is # a 3 day bar. Now we could just use a single TradeBarConsolidator like above and pass in # TimeSpan.from_days(3), but in reality that's not what we want. For time spans of longer than # a day we'll get incorrect results around weekends and such. What we really want are tradeable # days. So we'll create a daily consolidator, and then wrap it with a 3 count consolidator. # first define a one day trade bar -- this produces a consolidated piece of data after a day has passed one_day_consolidator = TradeBarConsolidator(timedelta(1)) # next define our 3 count trade bar -- this produces a consolidated piece of data after it sees 3 pieces of data three_count_consolidator = TradeBarConsolidator(3) # here we combine them to make a new, 3 day trade bar. The SequentialConsolidator allows composition of # consolidators. It takes the consolidated output of one consolidator (in this case, the one_day_consolidator) # and pipes it through to the three_count_consolidator. His output will be a 3 day bar. three_one_day_bar = SequentialConsolidator(one_day_consolidator, three_count_consolidator) # attach our handler three_one_day_bar.data_consolidated += self.three_day_bar_consolidated_handler # this call adds our 3 day to the manager to receive updates from the engine self.subscription_manager.add_consolidator("SPY", three_one_day_bar) # Custom monthly consolidator custom_monthly_consolidator = TradeBarConsolidator(self.custom_monthly) custom_monthly_consolidator.data_consolidated += self.custom_monthly_handler self.subscription_manager.add_consolidator("SPY", custom_monthly_consolidator) # API convenience method for easily receiving consolidated data self.consolidate("SPY", timedelta(minutes=45), self.forty_five_minute_bar_handler) self.consolidate("SPY", Resolution.HOUR, self.hour_bar_handler) self.consolidate("EURUSD", Resolution.DAILY, self.daily_eur_usd_bar_handler) # API convenience method for easily receiving weekly-consolidated data self.consolidate("SPY", Calendar.WEEKLY, self.calendar_trade_bar_handler) self.consolidate("EURUSD", Calendar.WEEKLY, self.calendar_quote_bar_handler) # API convenience method for easily receiving monthly-consolidated data self.consolidate("SPY", Calendar.MONTHLY, self.calendar_trade_bar_handler) self.consolidate("EURUSD", Calendar.MONTHLY, self.calendar_quote_bar_handler) # API convenience method for easily receiving quarterly-consolidated data self.consolidate("SPY", Calendar.QUARTERLY, self.calendar_trade_bar_handler) self.consolidate("EURUSD", Calendar.QUARTERLY, self.calendar_quote_bar_handler) # API convenience method for easily receiving yearly-consolidated data self.consolidate("SPY", Calendar.YEARLY, self.calendar_trade_bar_handler) self.consolidate("EURUSD", Calendar.YEARLY, self.calendar_quote_bar_handler) # some securities may have trade and quote data available, so we can choose it based on TickType: #self.consolidate("BTCUSD", Resolution.HOUR, TickType.TRADE, self.hour_bar_handler) # to get TradeBar #self.consolidate("BTCUSD", Resolution.HOUR, TickType.QUOTE, self.hour_bar_handler) # to get QuoteBar (default) self.consolidated_hour = False self.consolidated45_minute = False self.__last = None def on_data(self, data): '''We need to declare this method''' pass def on_end_of_day(self, symbol): # close up shop each day and reset our 'last' value so we start tomorrow fresh self.liquidate("SPY") self.__last = None def thirty_minute_bar_handler(self, sender, consolidated): '''This is our event handler for our 30 minute trade bar defined above in Initialize(). So each time the consolidator produces a new 30 minute bar, this function will be called automatically. The 'sender' parameter will be the instance of the IDataConsolidator that invoked the event, but you'll almost never need that!''' if self.__last is not None and consolidated.close > self.__last.close: self.log(f"{consolidated.time} >> SPY >> LONG >> 100 >> {self.portfolio['SPY'].quantity}") self.order("SPY", 100) elif self.__last is not None and consolidated.close < self.__last.close: self.log(f"{consolidated.time} >> SPY >> SHORT >> 100 >> {self.portfolio['SPY'].quantity}") self.order("SPY", -100) self.__last = consolidated def three_day_bar_consolidated_handler(self, sender, consolidated): ''' This is our event handler for our 3 day trade bar defined above in Initialize(). So each time the consolidator produces a new 3 day bar, this function will be called automatically. The 'sender' parameter will be the instance of the IDataConsolidator that invoked the event, but you'll almost never need that!''' self.log(f"{consolidated.time} >> Plotting!") self.plot(consolidated.symbol.value, "3HourBar", consolidated.close) def forty_five_minute_bar_handler(self, consolidated): ''' This is our event handler for our 45 minute consolidated defined using the Consolidate method''' self.consolidated45_minute = True self.log(f"{consolidated.end_time} >> FortyFiveMinuteBarHandler >> {consolidated.close}") def hour_bar_handler(self, consolidated): '''This is our event handler for our one hour consolidated defined using the Consolidate method''' self.consolidated_hour = True self.log(f"{consolidated.end_time} >> FortyFiveMinuteBarHandler >> {consolidated.close}") def daily_eur_usd_bar_handler(self, consolidated): '''This is our event handler for our daily consolidated defined using the Consolidate method''' self.log(f"{consolidated.end_time} EURUSD Daily consolidated.") def calendar_trade_bar_handler(self, trade_bar): self.log(f'{self.time} :: {trade_bar.time} {trade_bar.close}') def calendar_quote_bar_handler(self, quote_bar): self.log(f'{self.time} :: {quote_bar.time} {quote_bar.close}') def custom_monthly(self, dt): '''Custom Monthly Func''' start = dt.replace(day=1).date() end = dt.replace(day=28) + timedelta(4) end = (end - timedelta(end.day-1)).date() return CalendarInfo(start, end - start) def custom_monthly_handler(self, sender, consolidated): '''This is our event handler Custom Monthly function''' self.log(f"{consolidated.time} >> CustomMonthlyHandler >> {consolidated.close}") def on_end_of_algorithm(self): if not self.consolidated_hour: raise AssertionError("Expected hourly consolidator to be fired.") if not self.consolidated45_minute: raise AssertionError("Expected 45-minute consolidator to be fired.") ```
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.OptionChain(Symbol)"/> method to get a future option chain.
```python from AlgorithmImports import * class FutureOptionChainFullDataRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2020, 1, 6) self.set_end_date(2020, 1, 6) future_contract = self.add_future_contract( Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 3, 20)), Resolution.MINUTE).symbol option_chain = self.option_chain(future_contract, flatten=True) # Demonstration using data frame: df = option_chain.data_frame # Get contracts expiring within 4 months, with the latest expiration date, highest strike and lowest price contracts = df.loc[(df.expiry <= self.time + timedelta(days=120))] contracts = contracts.sort_values(['expiry', 'strike', 'lastprice'], ascending=[False, False, True]) self._option_contract = contracts.index[0] self.add_future_option_contract(self._option_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._option_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 : The regression algorithm showcases the utilization of a custom data source with the Sort flag set to true. This means that the source initially provides data in descending order, which is then organized into ascending order and returned in the 'on_data' function.
```python from AlgorithmImports import * class DescendingCustomDataObjectStoreRegressionAlgorithm(QCAlgorithm): descending_custom_data = [ "2024-10-03 19:00:00,173.5,176.0,172.0,175.2,120195681,4882.29", "2024-10-02 18:00:00,174.0,177.0,173.0,175.8,116275729,4641.97", "2024-10-01 17:00:00,175.0,178.0,172.5,174.5,127707078,6591.27", "2024-09-30 11:00:00,174.8,176.5,172.8,175.0,127707078,6591.27", "2024-09-27 10:00:00,172.5,175.0,171.5,173.5,120195681,4882.29", "2024-09-26 09:00:00,171.0,172.5,170.0,171.8,117516350,4820.53", "2024-09-25 08:00:00,169.5,172.0,169.0,171.0,110427867,4661.55", "2024-09-24 07:00:00,170.0,171.0,168.0,169.5,127624733,4823.52", "2024-09-23 06:00:00,172.0,173.5,169.5,171.5,123586417,4303.93", "2024-09-20 05:00:00,168.0,171.0,167.5,170.5,151929179,5429.87", "2024-09-19 04:00:00,170.5,171.5,166.0,167.0,160523863,5219.24", "2024-09-18 03:00:00,173.0,174.0,169.0,172.0,145721790,5163.09", "2024-09-17 02:00:00,171.0,173.5,170.0,172.5,144794030,5405.72", "2024-09-16 01:00:00,168.0,171.0,167.0,170.0,214402430,8753.33", "2024-09-13 16:00:00,173.5,176.0,172.0,175.2,120195681,4882.29", "2024-09-12 15:00:00,174.5,177.5,173.5,176.5,171728134,7774.83", "2024-09-11 14:00:00,175.0,178.0,174.0,175.5,191516153,8349.59", "2024-09-10 13:00:00,174.5,176.0,173.0,174.0,151162819,5915.8", "2024-09-09 12:00:00,176.0,178.0,175.0,177.0,116275729,4641.97" ] def initialize(self) -> None: self.set_start_date(2024, 9, 9) self.set_end_date(2024, 10, 3) self.set_cash(100000) self.set_benchmark(lambda x: 0) SortCustomData.custom_data_key = self.get_custom_data_key() self._custom_symbol = self.add_data(SortCustomData, "SortCustomData", Resolution.DAILY).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. self.object_store.save(self.get_custom_data_key(), "\n".join(self.descending_custom_data)) self.received_data = [] def on_data(self, slice: Slice) -> None: if slice.contains_key(self._custom_symbol): custom_data = slice.get(SortCustomData, self._custom_symbol) if custom_data.open == 0 or custom_data.high == 0 or custom_data.low == 0 or custom_data.close == 0 or custom_data.price == 0: raise AssertionError("One or more custom data fields (open, high, low, close, price) are zero.") self.received_data.append(custom_data) def on_end_of_algorithm(self) -> None: if not self.received_data: raise AssertionError("Custom data was not fetched") # Make sure history requests work as expected history = self.history(SortCustomData, self._custom_symbol, self.start_date, self.end_date, Resolution.DAILY) if history.shape[0] != len(self.received_data): raise AssertionError("History request returned more or less data than expected") # Iterate through the history collection, checking if the time is in ascending order. for i in range(len(history) - 1): # [1] - time if history.index[i][1] > history.index[i + 1][1]: raise AssertionError( f"Order failure: {history.index[i][1]} > {history.index[i + 1][1]} at index {i}.") def get_custom_data_key(self) -> str: return "CustomData/SortCustomData" class SortCustomData(PythonData): custom_data_key = "" def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource: subscription = SubscriptionDataSource(self.custom_data_key, SubscriptionTransportMedium.OBJECT_STORE, FileFormat.CSV) # Indicate that the data from the subscription will be returned in descending order. subscription.sort = True return subscription def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData: data = line.split(',') obj_data = SortCustomData() 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 : Basic Continuous Futures Template Algorithm
```python from AlgorithmImports import * class BasicTemplateContinuousFutureAlgorithm(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, 7, 1) self.set_end_date(2014, 1, 1) self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI, data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO, data_mapping_mode = DataMappingMode.LAST_TRADING_DAY, contract_depth_offset = 0) self._fast = self.sma(self._continuous_contract.symbol, 4, Resolution.DAILY) self._slow = self.sma(self._continuous_contract.symbol, 10, Resolution.DAILY) self._current_contract = None 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 ''' for changed_event in data.symbol_changed_events.values(): if changed_event.symbol == self._continuous_contract.symbol: self.log(f"SymbolChanged event: {changed_event}") if not self.portfolio.invested: if self._fast.current.value > self._slow.current.value: self._current_contract = self.securities[self._continuous_contract.mapped] self.buy(self._current_contract.symbol, 1) elif self._fast.current.value < self._slow.current.value: self.liquidate() # We check exchange hours because the contract mapping can call OnData outside of regular hours. if self._current_contract is not None and self._current_contract.symbol != self._continuous_contract.mapped and self._continuous_contract.exchange.exchange_open: self.log(f"{self.time} - rolling position from {self._current_contract.symbol} to {self._continuous_contract.mapped}") current_position_size = self._current_contract.holdings.quantity self.liquidate(self._current_contract.symbol) self.buy(self._continuous_contract.mapped, current_position_size) self._current_contract = self.securities[self._continuous_contract.mapped] def on_order_event(self, order_event): self.debug("Purchased Stock: {0}".format(order_event.symbol)) def on_securities_changed(self, changes): self.debug(f"{self.time}-{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 algorithm sends portfolio targets to CrunchDAO API once a week.
```python from AlgorithmImports import * class CrunchDAOSignalExportDemonstrationAlgorithm(QCAlgorithm): crunch_universe = [] def initialize(self) -> None: self.set_start_date(2023, 5, 22) self.set_end_date(2023, 5, 26) self.set_cash(1_000_000) # Disable automatic exports as we manually set them self.signal_export.automatic_export_time_span = None # Connect to CrunchDAO api_key = "" # Your CrunchDAO API key model = "" # The Id of your CrunchDAO model submission_name = "" # A name for the submission to distinguish it from your other submissions comment = "" # A comment for the submission self.signal_export.add_signal_export_provider(CrunchDAOSignalExport(api_key, model, submission_name, comment)) self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices))) # Add a custom data universe to read the CrunchDAO skeleton self.add_universe(CrunchDaoSkeleton, "CrunchDaoSkeleton", Resolution.DAILY, self.select_symbols) # Create a Scheduled Event to submit signals every monday before the market opens self._week = -1 self.schedule.on( self.date_rules.every([DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY]), self.time_rules.at(13, 15, TimeZones.UTC), self.submit_signals) self.settings.minimum_order_margin_portfolio_percentage = 0 self.set_warm_up(timedelta(45)) def select_symbols(self, data: list[CrunchDaoSkeleton]) -> list[Symbol]: return [x.symbol for x in data] def on_securities_changed(self, changes: SecurityChanges) -> None: for security in changes.removed_securities: if security in self.crunch_universe: self.crunch_universe.remove(security) self.crunch_universe.extend(changes.added_securities) def submit_signals(self) -> None: if self.is_warming_up: return # Submit signals once per week week_num = self.time.isocalendar()[1] if self._week == week_num: return self._week = week_num symbols = [security.symbol for security in self.crunch_universe if security.price > 0] # Get historical price data # close_prices = self.history(symbols, 22, Resolution.DAILY).close.unstack(0) # Create portfolio targets weight_by_symbol = {symbol: 1/len(symbols) for symbol in symbols} # Add your logic here targets = [PortfolioTarget(symbol, weight) for symbol, weight in weight_by_symbol.items()] # (Optional) Place trades self.set_holdings(targets) # Send signals to CrunchDAO success = self.signal_export.set_target_portfolio(targets) if not success: self.debug(f"Couldn't send targets at {self.time}") class CrunchDaoSkeleton(PythonData): def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource: return SubscriptionDataSource("https://tournament.crunchdao.com/data/skeleton.csv", SubscriptionTransportMedium.REMOTE_FILE) def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData: if not line[0].isdigit(): return None skeleton = CrunchDaoSkeleton() skeleton.symbol = config.symbol try: csv = line.split(',') skeleton.end_time = datetime.strptime(csv[0], "%Y-%m-%d") skeleton.symbol = Symbol(SecurityIdentifier.generate_equity(csv[1], Market.USA, mapping_resolve_date=skeleton.time), csv[1]) skeleton["Ticker"] = csv[1] except ValueError: # Do nothing return None return skeleton ```
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 and regression algorithm asserting the behavior of registering and unregistering an indicator from the engine
```python from AlgorithmImports import * class UnregisterIndicatorRegressionAlgorithm(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) spy = self.add_equity("SPY") ibm = self.add_equity("IBM") self._symbols = [ spy.symbol, ibm.symbol ] self._trin = self.trin(self._symbols, Resolution.MINUTE) self._trin2 = None 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._trin.is_ready: self._trin.reset() self.unregister_indicator(self._trin) # let's create a new one with a differente resolution self._trin2 = self.trin(self._symbols, Resolution.HOUR) if not self._trin2 is None and self._trin2.is_ready: if self._trin.is_ready: raise ValueError("Indicator should of stop getting updates!") if not self.portfolio.invested: self.set_holdings(self._symbols[0], 0.5) self.set_holdings(self._symbols[1], 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 : Regression algorithm testing GH feature 3790, using SetHoldings with a collection of targets which will be ordered by margin impact before being executed, with the objective of avoiding any margin errors
```python from AlgorithmImports import * class SetHoldingsMultipleTargetsRegressionAlgorithm(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) # use leverage 1 so we test the margin impact ordering self._spy = self.add_equity("SPY", Resolution.MINUTE, Market.USA, False, 1).symbol self._ibm = self.add_equity("IBM", Resolution.MINUTE, Market.USA, False, 1).symbol # 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 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([PortfolioTarget(self._spy, 0.8), PortfolioTarget(self._ibm, 0.2)]) else: self.set_holdings([PortfolioTarget(self._ibm, 0.8), PortfolioTarget(self._spy, 0.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 : Algorithm demonstrating the portfolio target tags usage
```python from AlgorithmImports import * class PortfolioTargetTagsRegressionAlgorithm(QCAlgorithm): '''Algorithm demonstrating the portfolio target tags usage''' 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.universe_settings.resolution = Resolution.MINUTE symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ] # set algorithm framework models self.set_universe_selection(ManualUniverseSelectionModel(symbols)) self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None)) self.set_portfolio_construction(CustomPortfolioConstructionModel()) self.set_risk_management(CustomRiskManagementModel()) self.set_execution(CustomExecutionModel(self.set_target_tags_checked)) self.target_tags_checked = False def set_target_tags_checked(self): self.target_tags_checked = True def on_end_of_algorithm(self): if not self.target_tags_checked: raise AssertionError("The portfolio targets tag were not checked") class CustomPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel): def __init__(self): super().__init__(Resolution.DAILY) def create_targets(self, algorithm: QCAlgorithm, insights: List[Insight]) -> List[IPortfolioTarget]: targets = super().create_targets(algorithm, insights) return CustomPortfolioConstructionModel.add_p_portfolio_targets_tags(targets) @staticmethod def generate_portfolio_target_tag(target: IPortfolioTarget) -> str: return f"Portfolio target tag: {target.symbol} - {target.quantity:g}" @staticmethod def add_p_portfolio_targets_tags(targets: Iterable[IPortfolioTarget]) -> List[IPortfolioTarget]: return [PortfolioTarget(target.symbol, target.quantity, CustomPortfolioConstructionModel.generate_portfolio_target_tag(target)) for target in targets] class CustomRiskManagementModel(MaximumDrawdownPercentPerSecurity): def __init__(self): super().__init__(0.01) def manage_risk(self, algorithm: QCAlgorithm, targets: List[IPortfolioTarget]) -> List[IPortfolioTarget]: risk_managed_targets = super().manage_risk(algorithm, targets) return CustomPortfolioConstructionModel.add_p_portfolio_targets_tags(risk_managed_targets) class CustomExecutionModel(ImmediateExecutionModel): def __init__(self, targets_tag_checked_callback: Callable) -> None: super().__init__() self.targets_tag_checked_callback = targets_tag_checked_callback def execute(self, algorithm: QCAlgorithm, targets: List[IPortfolioTarget]) -> None: if len(targets) > 0: self.targets_tag_checked_callback() for target in targets: expected_tag = CustomPortfolioConstructionModel.generate_portfolio_target_tag(target) if target.tag != expected_tag: raise AssertionError(f"Unexpected portfolio target tag: {target.tag} - Expected: {expected_tag}") super().execute(algorithm, 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 : Demonstration of using the Delisting event in your algorithm. Assets are delisted on their last day of trading, or when their contract expires. This data is not included in the open source project.
```python from AlgorithmImports import * class DelistingEventsAlgorithm(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(2007, 5, 15) #Set Start Date self.set_end_date(2007, 5, 25) #Set End Date self.set_cash(100000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data self.add_equity("AAA.1", Resolution.DAILY) self.add_equity("SPY", Resolution.DAILY) 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 self.transactions.orders_count == 0: self.set_holdings("AAA.1", 1) self.debug("Purchased stock") for kvp in data.bars: symbol = kvp.key value = kvp.value self.log("OnData(Slice): {0}: {1}: {2}".format(self.time, symbol, value.close)) # the slice can also contain delisting data: data.delistings in a dictionary string->Delisting aaa = self.securities["AAA.1"] if aaa.is_delisted and aaa.is_tradable: raise AssertionError("Delisted security must NOT be tradable") if not aaa.is_delisted and not aaa.is_tradable: raise AssertionError("Securities must be marked as tradable until they're delisted or removed from the universe") for kvp in data.delistings: symbol = kvp.key value = kvp.value if value.type == DelistingType.WARNING: self.log("OnData(Delistings): {0}: {1} will be delisted at end of day today.".format(self.time, symbol)) # liquidate on delisting warning self.set_holdings(symbol, 0) if value.type == DelistingType.DELISTED: self.log("OnData(Delistings): {0}: {1} has been delisted.".format(self.time, symbol)) # fails because the security has already been delisted and is no longer tradable self.set_holdings(symbol, 1) def on_order_event(self, order_event): self.log("OnOrderEvent(OrderEvent): {0}: {1}".format(self.time, 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 algorithm showing how to easily convert an old algorithm into the framework. 1. When making orders, also create insights for the correct direction (up/down/flat), can also set insight prediction period/magnitude/direction 2. Emit insights before placing any trades 3. Profit :)
```python from AlgorithmImports import * class ConvertToFrameworkAlgorithm(QCAlgorithm): '''Demonstration algorithm showing how to easily convert an old algorithm into the framework.''' fast_ema_period = 12 slow_ema_period = 26 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(2004, 1, 1) self.set_end_date(2015, 1, 1) self._symbol = self.add_security(SecurityType.EQUITY, 'SPY', Resolution.DAILY).symbol # define our daily macd(12,26) with a 9 day signal self._macd = self.macd(self._symbol, self.fast_ema_period, self.slow_ema_period, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY) 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. Args: data: Slice object with your stock data''' # wait for our indicator to be ready if not self._macd.is_ready or not data.contains_key(self._symbol) or data[self._symbol] is None: return holding = self.portfolio[self._symbol] signal_delta_percent = float(self._macd.current.value - self._macd.signal.current.value) / float(self._macd.fast.current.value) tolerance = 0.0025 # if our macd is greater than our signal, then let's go long if holding.quantity <= 0 and signal_delta_percent > tolerance: # 1. Call emit_insights with insights created in correct direction, here we're going long # The emit_insights method can accept multiple insights separated by commas self.emit_insights( # Creates an insight for our symbol, predicting that it will move up within the fast ema period number of days Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.UP) ) # longterm says buy as well self.set_holdings(self._symbol, 1) # if our macd is less than our signal, then let's go short elif holding.quantity >= 0 and signal_delta_percent < -tolerance: # 1. Call emit_insights with insights created in correct direction, here we're going short # The emit_insights method can accept multiple insights separated by commas self.emit_insights( # Creates an insight for our symbol, predicting that it will move down within the fast ema period number of days Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.DOWN) ) self.set_holdings(self._symbol, -1) # if we wanted to liquidate our positions ## 1. Call emit_insights with insights create in the correct direction -- Flat #self.emit_insights( # Creates an insight for our symbol, predicting that it will move down or up within the fast ema period number of days, depending on our current position # Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.FLAT) #) # self.liquidate() # plot both lines self.plot("MACD", self._macd, self._macd.signal) self.plot(self._symbol.value, self._macd.fast, self._macd.slow) self.plot(self._symbol.value, "Open", data[self._symbol].open) ```
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 consolidated bars are of type `QuoteBar` when `QCAlgorithm.consolidate()` is called with `tick_type=TickType.QUOTE`
```python from AlgorithmImports import * class CorrectConsolidatedBarTypeForTickTypesAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 7) symbol = self.add_equity("SPY", Resolution.TICK).symbol self.consolidate(symbol, timedelta(minutes=1), TickType.QUOTE, self.quote_tick_consolidation_handler) self.consolidate(symbol, timedelta(minutes=1), TickType.TRADE, self.trade_tick_consolidation_handler) self.quote_tick_consolidation_handler_called = False self.trade_tick_consolidation_handler_called = False def on_data(self, slice: Slice) -> None: if self.time.hour > 9: self.quit("Early quit to save time") def on_end_of_algorithm(self): if not self.quote_tick_consolidation_handler_called: raise AssertionError("quote_tick_consolidation_handler was not called") if not self.trade_tick_consolidation_handler_called: raise AssertionError("trade_tick_consolidation_handler was not called") def quote_tick_consolidation_handler(self, consolidated_bar: QuoteBar) -> None: if type(consolidated_bar) != QuoteBar: raise AssertionError(f"Expected the consolidated bar to be of type {QuoteBar} but was {type(consolidated_bar)}") self.quote_tick_consolidation_handler_called = True def trade_tick_consolidation_handler(self, consolidated_bar: TradeBar) -> None: if type(consolidated_bar) != TradeBar: raise AssertionError(f"Expected the consolidated bar to be of type {TradeBar} but was {type(consolidated_bar)}") self.trade_tick_consolidation_handler_called = 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 : Demonstration of the Scheduled Events features available in QuantConnect.
```python from AlgorithmImports import * class ScheduledEventsAlgorithm(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) #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") # events are scheduled using date and time rules # date rules specify on what dates and event will fire # time rules specify at what time on thos dates the event will fire # schedule an event to fire at a specific date/time self.schedule.on(self.date_rules.on(2013, 10, 7), self.time_rules.at(13, 0), self.specific_time) # schedule an event to fire every trading day for a security the # time rule here tells it to fire 10 minutes after SPY's market open self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.after_market_open("SPY", 10), self.every_day_after_market_open) # schedule an event to fire every trading day for a security the # time rule here tells it to fire 10 minutes before SPY's market close self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.before_market_close("SPY", 10), self.every_day_after_market_close) # schedule an event to fire on a single day of the week self.schedule.on(self.date_rules.every(DayOfWeek.WEDNESDAY), self.time_rules.at(12, 0), self.every_wed_at_noon) # schedule an event to fire on certain days of the week self.schedule.on(self.date_rules.every(DayOfWeek.MONDAY, DayOfWeek.FRIDAY), self.time_rules.at(12, 0), self.every_mon_fri_at_noon) # the scheduling methods return the ScheduledEvent object which can be used for other things here I set # the event up to check the portfolio value every 10 minutes, and liquidate if we have too many losses self.schedule.on(self.date_rules.every_day(), self.time_rules.every(timedelta(minutes=10)), self.liquidate_unrealized_losses) # schedule an event to fire at the beginning of the month, the symbol is optional # if specified, it will fire the first trading day for that symbol of the month, # if not specified it will fire on the first day of the month self.schedule.on(self.date_rules.month_start("SPY"), self.time_rules.after_market_open("SPY"), self.rebalancing_code) def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' if not self.portfolio.invested: self.set_holdings("SPY", 1) def specific_time(self): self.log(f"SpecificTime: Fired at : {self.time}") def every_day_after_market_open(self): self.log(f"EveryDay.SPY 10 min after open: Fired at: {self.time}") def every_day_after_market_close(self): self.log(f"EveryDay.SPY 10 min before close: Fired at: {self.time}") def every_wed_at_noon(self): self.log(f"Wed at 12pm: Fired at: {self.time}") def every_mon_fri_at_noon(self): self.log(f"Mon/Fri at 12pm: Fired at: {self.time}") def liquidate_unrealized_losses(self): ''' if we have over 1000 dollars in unrealized losses, liquidate''' if self.portfolio.total_unrealized_profit < -1000: self.log(f"Liquidated due to unrealized losses at: {self.time}") self.liquidate() def rebalancing_code(self): ''' Good spot for rebalancing code?''' 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 : Show example of how to use the TrailingStopRiskManagementModel
```python from AlgorithmImports import * from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm from Risk.TrailingStopRiskManagementModel import TrailingStopRiskManagementModel class TrailingStopRiskFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm): '''Show example of how to use the TrailingStopRiskManagementModel''' def initialize(self): super().initialize() self.set_universe_selection(ManualUniverseSelectionModel([Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)])) self.set_risk_management(TrailingStopRiskManagementModel(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 : Example algorithm showing how to use QCAlgorithm.train method
```python from AlgorithmImports import * from time import sleep class TrainingExampleAlgorithm(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, 14) self.add_equity("SPY", Resolution.DAILY) # Set TrainingMethod to be executed immediately self.train(self.training_method) # Set TrainingMethod to be executed at 8:00 am every Sunday self.train(self.date_rules.every(DayOfWeek.SUNDAY), self.time_rules.at(8 , 0), self.training_method) def training_method(self): self.log(f'Start training at {self.time}') # Use the historical data to train the machine learning model history = self.history(["SPY"], 200, Resolution.DAILY) # ML code: 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 : Regression algorithm asserting that the option chain APIs return consistent values for index options. See QCAlgorithm.OptionChain(Symbol) and QCAlgorithm.OptionChainProvider
```python from datetime import datetime from AlgorithmImports import * from OptionChainApisConsistencyRegressionAlgorithm import OptionChainApisConsistencyRegressionAlgorithm class IndexOptionChainApisConsistencyRegressionAlgorithm(OptionChainApisConsistencyRegressionAlgorithm): def get_test_date(self) -> datetime: return datetime(2021, 1, 4) def get_option(self) -> Option: return self.add_index_option("SPX") ```
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 option chains, which contains additional data besides the symbols, including prices, implied volatility and greeks. It also shows how this data can be used to filter the contracts based on certain criteria.
```python from AlgorithmImports import * from datetime import timedelta class OptionChainsMultipleFullDataRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2015, 12, 24) self.set_end_date(2015, 12, 24) self.set_cash(100000) goog = self.add_equity("GOOG").symbol spx = self.add_index("SPX").symbol chains = self.option_chains([goog, spx], flatten=True) self._goog_option_contract = self.get_contract(chains, goog, timedelta(days=10)) self._spx_option_contract = self.get_contract(chains, spx, timedelta(days=60)) self.add_option_contract(self._goog_option_contract) self.add_index_option_contract(self._spx_option_contract) def get_contract(self, chains: OptionChains, underlying: Symbol, expiry_span: timedelta) -> 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] df = df.loc[condition] # Get contracts expiring in the next 10 days with an implied volatility greater than 0.5 and a delta less than 0.5 contracts = df.loc[(df.expiry <= self.time + expiry_span) & (df.impliedvolatility > 0.5) & (df.delta < 0.5)] # Select the contract with the latest expiry date contracts.sort_values(by='expiry', ascending=False, inplace=True) # Get the symbol: the resulting series name is a tuple (canonical symbol, contract symbol) return contracts.iloc[0].name[1] def on_data(self, data): # Do some trading with the selected contract for sample purposes if not self.portfolio.invested: self.market_order(self._goog_option_contract, 1) 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 : In this algorithm we demonstrate how to use the UniverseSettings to define the data normalization mode (raw)
```python from AlgorithmImports import * class RawPricesUniverseRegressionAlgorithm(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.''' # what resolution should the data *added* to the universe be? self.universe_settings.resolution = Resolution.DAILY # Use raw prices self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW self.set_start_date(2014,3,24) #Set Start Date self.set_end_date(2014,4,7) #Set End Date self.set_cash(50000) #Set Strategy Cash # Set the security initializer with zero fees and price initial seed securitySeeder = FuncSecuritySeeder(self.get_last_known_prices) self.set_security_initializer(CompositeSecurityInitializer( FuncSecurityInitializer(lambda x: x.set_fee_model(ConstantFeeModel(0))), FuncSecurityInitializer(lambda security: securitySeeder.seed_security(security)))) self.add_universe("MyUniverse", Resolution.DAILY, self.selection_function) def selection_function(self, date_time): if date_time.day % 2 == 0: return ["SPY", "IWM", "QQQ"] else: return ["AIG", "BAC", "IBM"] # 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.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 : Algorithm asserting that closed orders can be updated with a new tag
```python from AlgorithmImports import * class CompleteOrderTagUpdateAlgorithm(QCAlgorithm): _tag_after_fill = "This is the tag set after order was filled." _tag_after_canceled = "This is the tag set after order was canceled." def initialize(self) -> None: self.set_start_date(2013,10, 7) self.set_end_date(2013,10,11) self.set_cash(100000) self._spy = self.add_equity("SPY", Resolution.MINUTE).symbol self._market_order_ticket = None self._limit_order_ticket = None self._quantity = 100 def on_data(self, data: Slice) -> None: if not self.portfolio.invested: if self._limit_order_ticket is None: # a limit order to test the tag update after order was canceled. # low price, we don't want it to fill since we are canceling it self._limit_order_ticket = self.limit_order(self._spy, 100, self.securities[self._spy].price * 0.1) self._limit_order_ticket.cancel() else: # a market order to test the tag update after order was filled. self.buy(self._spy, self._quantity) def on_order_event(self, order_event: OrderEvent) -> None: if order_event.status == OrderStatus.CANCELED: if not self._limit_order_ticket or order_event.order_id != self._limit_order_ticket.order_id: raise AssertionError("The only canceled order should have been the limit order.") # update canceled order tag self.update_order_tag(self._limit_order_ticket, self._tag_after_canceled, "Error updating order tag after canceled") elif order_event.status == OrderStatus.FILLED: self._market_order_ticket = list(self.transactions.get_order_tickets(lambda x: x.order_type == OrderType.MARKET))[0] if not self._market_order_ticket or order_event.order_id != self._market_order_ticket.order_id: raise AssertionError("The only filled order should have been the market order.") # update filled order tag self.update_order_tag(self._market_order_ticket, self._tag_after_fill, "Error updating order tag after fill") def on_end_of_algorithm(self) -> None: # check the filled order self.assert_order_tag_update(self._market_order_ticket, self._tag_after_fill, "filled") if self._market_order_ticket.quantity != self._quantity or self._market_order_ticket.quantity_filled != self._quantity: raise AssertionError("The market order quantity should not have been updated.") # check the canceled order self.assert_order_tag_update(self._limit_order_ticket, self._tag_after_canceled, "canceled") def assert_order_tag_update(self, ticket: OrderTicket, expected_tag: str, order_action: str) -> None: if ticket is None: raise AssertionError(f"The order ticket was not set for the {order_action} order") if ticket.tag != expected_tag: raise AssertionError(f"Order ticket tag was not updated after order was {order_action}") order = self.transactions.get_order_by_id(ticket.order_id) if order.tag != expected_tag: raise AssertionError(f"Order tag was not updated after order was {order_action}") def update_order_tag(self, ticket: OrderTicket, tag: str, error_message_prefix: str) -> None: update_fields = UpdateOrderFields() update_fields.tag = tag response = ticket.update(update_fields) if response.is_error: raise AssertionError(f"{error_message_prefix}: {response.error_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 : Regression algorithm for the StandardDeviationExecutionModel. This algorithm shows how the execution model works to split up orders and submit them only when the price is 2 standard deviations from the 60min mean (default model settings).
```python from AlgorithmImports import * from Alphas.RsiAlphaModel import RsiAlphaModel from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel from Execution.StandardDeviationExecutionModel import StandardDeviationExecutionModel class StandardDeviationExecutionModelRegressionAlgorithm(QCAlgorithm): '''Regression algorithm for the StandardDeviationExecutionModel. This algorithm shows how the execution model works to split up orders and submit them only when the price is 2 standard deviations from the 60min mean (default model settings).''' 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) self.set_end_date(2013,10,11) self.set_cash(1000000) self.set_universe_selection(ManualUniverseSelectionModel([ Symbol.create('AIG', SecurityType.EQUITY, Market.USA), Symbol.create('BAC', SecurityType.EQUITY, Market.USA), Symbol.create('IBM', SecurityType.EQUITY, Market.USA), Symbol.create('SPY', SecurityType.EQUITY, Market.USA) ])) self.set_alpha(RsiAlphaModel(14, Resolution.HOUR)) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) self.set_execution(StandardDeviationExecutionModel()) def on_order_event(self, order_event): self.log(f"{self.time}: {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 : Example algorithm of the Identity indicator with the filtering enhancement. Filtering is used to check the output of the indicator before returning it.
```python from AlgorithmImports import * class FilteredIdentityAlgorithm(QCAlgorithm): ''' Example algorithm of the Identity indicator with the filtering enhancement ''' def initialize(self): self.set_start_date(2014,5,2) # Set Start Date self.set_end_date(self.start_date) # Set End Date self.set_cash(100000) # Set Stratgy Cash # Find more symbols here: http://quantconnect.com/data security = self.add_forex("EURUSD", Resolution.TICK) self._symbol = security.symbol self._identity = self.filtered_identity(self._symbol, filter=self.filter) def filter(self, data): '''Filter function: True if data is not an instance of Tick. If it is, true if TickType is Trade data -- Data for applying the filter''' if isinstance(data, Tick): return data.tick_type == TickType.TRADE return True def on_data(self, data): # Since we are only accepting TickType.TRADE, # this indicator will never be ready if not self._identity.is_ready: return if not self.portfolio.invested: self.set_holdings(self._symbol, 1) self.debug("Purchased Stock") ```
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 asserts we can consolidate Tick data with different tick types
```python from AlgorithmImports import * class ConsolidateDifferentTickTypesRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 6) self.set_end_date(2013, 10, 7) self.set_cash(1000000) equity = self.add_equity("SPY", Resolution.TICK, Market.USA) quote_consolidator = self.consolidate(equity.symbol, Resolution.TICK, TickType.QUOTE, lambda tick : self.on_quote_tick(tick)) self.there_is_at_least_one_quote_tick = False trade_consolidator = self.consolidate(equity.symbol, Resolution.TICK, TickType.TRADE, lambda tick : self.on_trade_tick(tick)) self.there_is_at_least_one_trade_tick = False # Tick consolidators with max count self.consolidate(TradeBar, equity.symbol, 10, TickType.TRADE, lambda trade_bar: self.on_trade_tick_max_count(trade_bar)) self._there_is_at_least_one_trade_bar = False self.consolidate(QuoteBar, equity.symbol, 10, TickType.QUOTE, lambda quote_bar: self.on_quote_tick_max_count(quote_bar)) self._there_is_at_least_one_quote_bar = False self._consolidation_count = 0 def on_trade_tick_max_count(self, trade_bar): self._there_is_at_least_one_trade_bar = True if type(trade_bar) != TradeBar: raise AssertionError(f"The type of the bar should be Trade, but was {type(trade_bar)}") def on_quote_tick_max_count(self, quote_bar): self._there_is_at_least_one_quote_bar = True if type(quote_bar) != QuoteBar: raise AssertionError(f"The type of the bar should be Quote, but was {type(quote_bar)}") self._consolidation_count += 1 # Let's shortcut to reduce regression test duration: algorithms using tick data are too long if self._consolidation_count >= 1000: self.quit() def on_quote_tick(self, tick): self.there_is_at_least_one_quote_tick = True if tick.tick_type != TickType.QUOTE: raise AssertionError(f"The type of the tick should be Quote, but was {tick.tick_type}") def on_trade_tick(self, tick): self.there_is_at_least_one_trade_tick = True if tick.tick_type != TickType.TRADE: raise AssertionError(f"The type of the tick should be Trade, but was {tick.tick_type}") def on_end_of_algorithm(self): if not self.there_is_at_least_one_quote_tick: raise AssertionError(f"There should have been at least one tick in OnQuoteTick() method, but there wasn't") if not self.there_is_at_least_one_trade_tick: raise AssertionError(f"There should have been at least one tick in OnTradeTick() method, but there wasn't") if not self._there_is_at_least_one_trade_bar: raise AssertionError("There should have been at least one bar in OnTradeTickMaxCount() method, but there wasn't") if not self._there_is_at_least_one_quote_bar: raise AssertionError("There should have been at least one bar in OnQuoteTickMaxCount() method, but there wasn't") ```
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 option universe filter by greeks and other options data feature
```python from AlgorithmImports import * class OptionUniverseFilterGreeksRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2015, 12, 24) self.set_end_date(2015, 12, 24) self.set_cash(100000) underlying_ticker = "GOOG" self.add_equity(underlying_ticker) option = self.add_option(underlying_ticker) self.option_symbol = option.symbol self._min_delta = 0.5 self._max_delta = 1.5 self._min_gamma = 0.0001 self._max_gamma = 0.0006 self._min_vega = 0.01 self._max_vega = 1.5 self._min_theta = -2.0 self._max_theta = -0.5 self._min_rho = 0.5 self._max_rho = 3.0 self._min_iv = 1.0 self._max_iv = 3.0 self._min_open_interest = 100 self._max_open_interest = 500 option.set_filter(self.main_filter) self.option_chain_received = False def main_filter(self, universe: OptionFilterUniverse) -> OptionFilterUniverse: total_contracts = len(list(universe)) filtered_universe = self.option_filter(universe) filtered_contracts = len(list(filtered_universe)) if filtered_contracts == total_contracts: raise AssertionError(f"Expected filtered universe to have less contracts than original universe. " f"Filtered contracts count ({filtered_contracts}) is equal to total contracts count ({total_contracts})") return filtered_universe def option_filter(self, universe: OptionFilterUniverse) -> OptionFilterUniverse: # Contracts can be filtered by greeks, implied volatility, open interest: return universe \ .delta(self._min_delta, self._max_delta) \ .gamma(self._min_gamma, self._max_gamma) \ .vega(self._min_vega, self._max_vega) \ .theta(self._min_theta, self._max_theta) \ .rho(self._min_rho, self._max_rho) \ .implied_volatility(self._min_iv, self._max_iv) \ .open_interest(self._min_open_interest, self._max_open_interest) # Note: there are also shortcuts for these filter methods: ''' return universe \ .d(self._min_delta, self._max_delta) \ .g(self._min_gamma, self._max_gamma) \ .v(self._min_vega, self._max_vega) \ .t(self._min_theta, self._max_theta) \ .r(self._min_rho, self._max_rho) \ .iv(self._min_iv, self._max_iv) \ .oi(self._min_open_interest, self._max_open_interest) ''' def on_data(self, slice: Slice) -> None: chain = slice.option_chains.get(self.option_symbol) if chain and len(chain.contracts) > 0: self.option_chain_received = True def on_end_of_algorithm(self) -> None: if not self.option_chain_received: raise AssertionError("Option chain was not received.") ```
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 the consolidated US equity daily bars from the hour bars exactly matches the daily bars returned from the database
```python from AlgorithmImports import * class ConsolidateHourBarsIntoDailyBarsRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2020, 5, 1) self.set_end_date(2020, 6, 5) self.spy = self.add_equity("SPY", Resolution.HOUR).symbol # We will use these two indicators to compare the daily consolidated bars equals # the ones returned from the database. We use this specific type of indicator as # it depends on its previous values. Thus, if at some point the bars received by # the indicators differ, so will their final values self._rsi = RelativeStrengthIndex("First", 15, MovingAverageType.WILDERS) self.register_indicator(self.spy, self._rsi, Resolution.DAILY, selector= lambda bar: (bar.close + bar.open) / 2) # We won't register this indicator as we will update it manually at the end of the # month, so that we can compare the values of the indicator that received consolidated # bars and the values of this one self._rsi_timedelta = RelativeStrengthIndex("Second", 15, MovingAverageType.WILDERS) self._values = {} self.count = 0 self._indicators_compared = False def on_data(self, data: Slice): if self.is_warming_up: return if data.contains_key(self.spy) and data[self.spy] != None: if self.time.month == self.end_date.month: history = self.history[TradeBar](self.spy, self.count, Resolution.DAILY) for bar in history: time = bar.end_time.strftime('%Y-%m-%d') average = (bar.close + bar.open) / 2 self._rsi_timedelta.update(bar.end_time, average) if self._rsi_timedelta.current.value != self._values[time]: raise AssertionError(f"Both {self._rsi.name} and {self._rsi_timedelta.name} should have the same values, but they differ. {self._rsi.name}: {self._values[time]} | {self._rsi_timedelta.name}: {self._rsi_timedelta.current.value}") self._indicators_compared = True self.quit() else: time = self.time.strftime('%Y-%m-%d') self._values[time] = self._rsi.current.value # Since the symbol resolution is hour and the symbol is equity, we know the last bar received in a day will # be at the market close, this is 16h. We need to count how many daily bars were consolidated in order to know # how many we need to request from the history if self.time.hour == 16: self.count += 1 def on_end_of_algorithm(self): if not self._indicators_compared: raise AssertionError(f"Indicators {self._rsi.name} and {self._rsi_timedelta.name} should have been compared, but they were not. Please make sure the indicators are getting SPY 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 : Regression algorithm testing the SetHolding trading API precision
```python from AlgorithmImports import * class SetHoldingsRegressionAlgorithm(QCAlgorithm): '''Basic template algorithm simply initializes the date range and cash''' asynchronous_orders = False 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 ''' if not self.portfolio.invested: self.set_holdings("SPY", 0.1, asynchronous=self.asynchronous_orders) self.set_holdings("SPY", float(0.20), asynchronous=self.asynchronous_orders) self.set_holdings("SPY", np.float64(0.30), asynchronous=self.asynchronous_orders) self.set_holdings("SPY", 1, asynchronous=self.asynchronous_orders) 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 algorithm shows how to grab symbols from an external api each day and load data using the universe selection feature. In this example we define a custom data type for the NYSE top gainers and then short the top 2 gainers each day
```python from AlgorithmImports import * class CustomDataUniverseAlgorithm(QCAlgorithm): def initialize(self): # Data ADDED via universe selection is added with Daily resolution. self.universe_settings.resolution = Resolution.DAILY self.set_start_date(2015,1,5) self.set_end_date(2015,7,1) self.set_cash(100000) self.add_equity("SPY", Resolution.DAILY) self.set_benchmark("SPY") # add a custom universe data source (defaults to usa-equity) self.add_universe(NyseTopGainers, "universe-nyse-top-gainers", Resolution.DAILY, self.nyse_top_gainers) def nyse_top_gainers(self, data): return [ x.symbol for x in data if x["TopGainersRank"] <= 2 ] def on_data(self, slice): pass def on_securities_changed(self, changes): self._changes = changes for security in changes.removed_securities: # liquidate securities that have been removed if security.invested: self.liquidate(security.symbol) self.log("Exit {0} at {1}".format(security.symbol, security.close)) for security in changes.added_securities: # enter short positions on new securities if not security.invested and security.close != 0: qty = self.calculate_order_quantity(security.symbol, -0.25) self.market_on_open_order(security.symbol, qty) self.log("Enter {0} at {1}".format(security.symbol, security.close)) class NyseTopGainers(PythonData): def __init__(self): self.count = 0 self.last_date = datetime.min def get_source(self, config, date, is_live_mode): url = "http://www.wsj.com/mdc/public/page/2_3021-gainnyse-gainer.html" if is_live_mode else \ "https://www.dropbox.com/s/vrn3p38qberw3df/nyse-gainers.csv?dl=1" return SubscriptionDataSource(url, SubscriptionTransportMedium.REMOTE_FILE) def reader(self, config, line, date, is_live_mode): if not is_live_mode: # backtest gets data from csv file in dropbox if not (line.strip() and line[0].isdigit()): return None csv = line.split(',') nyse = NyseTopGainers() nyse.time = datetime.strptime(csv[0], "%Y%m%d") nyse.end_time = nyse.time + timedelta(1) nyse.symbol = Symbol.create(csv[1], SecurityType.EQUITY, Market.USA) nyse["TopGainersRank"] = int(csv[2]) return nyse if self.last_date != date: # reset our counter for the new day self.last_date = date self.count = 0 # parse the html into a symbol if not line.startswith('<a href=\"/public/quotes/main.html?symbol='): # we're only looking for lines that contain the symbols return None last_close_paren = line.rfind(')') last_open_paren = line.rfind('(') if last_open_paren == -1 or last_close_paren == -1: return None symbol_string = line[last_open_paren + 1:last_close_paren] nyse = NyseTopGainers() nyse.time = date nyse.end_time = nyse.time + timedelta(1) nyse.symbol = Symbol.create(symbol_string, SecurityType.EQUITY, Market.USA) nyse["TopGainersRank"] = self.count self.count = self.count + 1 return nyse ```
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 used for regression tests purposes
```python from AlgorithmImports import * class RegressionAlgorithm(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) #Set Start Date self.set_end_date(2013,10,8) #Set End Date self.set_cash(10000000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data self.add_equity("SPY", Resolution.TICK) self.add_equity("BAC", Resolution.MINUTE) self.add_equity("AIG", Resolution.HOUR) self.add_equity("IBM", Resolution.DAILY) self.__last_trade_ticks = self.start_date self.__last_trade_trade_bars = self.__last_trade_ticks self.__trade_every = timedelta(minutes=1) def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' if self.time - self.__last_trade_trade_bars < self.__trade_every: return self.__last_trade_trade_bars = self.time for kvp in data.bars: bar = kvp.Value if bar.is_fill_forward: continue symbol = kvp.key holdings = self.portfolio[symbol] if not holdings.invested: self.market_order(symbol, 10) else: self.market_order(symbol, -holdings.quantity) ```
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 test to make sure that index options have greeks enabled, same as equity options.
```python from AlgorithmImports import * class IndexOptionCallITMGreeksExpiryRegressionAlgorithm(QCAlgorithm): def initialize(self): self.on_data_calls = 0 self.invested = False self.set_start_date(2021, 1, 4) self.set_end_date(2021, 1, 31) spx = self.add_index("SPX", Resolution.MINUTE) spx.volatility_model = StandardDeviationOfReturnsVolatilityModel(60, Resolution.MINUTE, timedelta(minutes=1)) self.spx = spx.symbol # Select a index option call 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) self.spx_option.price_model = OptionPriceModels.black_scholes() self.expected_option_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3200, datetime(2021, 1, 15)) if self.spx_option.symbol != self.expected_option_contract: raise AssertionError(f"Contract {self.expected_option_contract} was not found in the chain") def on_data(self, data: Slice): # Let the algo warmup, but without using SetWarmup. Otherwise, we get # no contracts in the option chain if self.invested or self.on_data_calls < 40: self.on_data_calls += 1 return self.on_data_calls += 1 if data.option_chains.count == 0: return if all([any([c.symbol not in data for c in o.contracts.values()]) for o in data.option_chains.values()]): return if len(list(list(data.option_chains.values())[0].contracts.values())) == 0: raise AssertionError(f"No contracts found in the option {list(data.option_chains.keys())[0]}") deltas = [i.greeks.delta for i in self.sort_by_max_volume(data)] gammas = [i.greeks.gamma for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.gamma).to_list() lambda_ = [i.greeks.lambda_ for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.lambda).to_list() rho = [i.greeks.rho for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.rho).to_list() theta = [i.greeks.theta for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.theta).to_list() vega = [i.greeks.vega for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.vega).to_list() # The commented out test cases all return zero. # This is because of failure to evaluate the greeks in the option pricing model, most likely # due to us not clearing the default 30 day requirement for the volatility model to start being updated. if any([i for i in deltas if i == 0]): raise AssertionError("Option contract Delta was equal to zero") # Delta is 1, therefore we expect a gamma of 0 if any([i for i in gammas if i == 0]): raise AssertionError("Option contract Gamma was equal to zero") if any([i for i in lambda_ if lambda_ == 0]): raise AssertionError("Option contract Lambda was equal to zero") if any([i for i in rho if i == 0]): raise AssertionError("Option contract Rho was equal to zero") if any([i for i in theta if i == 0]): raise AssertionError("Option contract Theta was equal to zero") # The strike is far away from the underlying asset's price, and we're very close to expiry. # Zero is an expected value here. if any([i for i in vega if vega == 0]): raise AggregateException("Option contract Vega was equal to zero") if not self.invested: self.set_holdings(list(list(data.option_chains.values())[0].contracts.values())[0].symbol, 1) self.invested = True ### <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())}") if not self.invested: raise AssertionError(f"Never checked greeks, maybe we have no option data?") def sort_by_max_volume(self, data: Slice): chain = [i for i in sorted(list(data.option_chains.values()), key=lambda x: sum([j.volume for j in x.contracts.values()]), reverse=True)][0] return chain.contracts.values() ```
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 illustrating how history from custom data sources can be requested. The <see cref="QCAlgorithm.history"/> method used in this example also allows to specify other parameters than just the resolution, such as the data normalization mode, the data mapping mode, etc.
```python from AlgorithmImports import * class HistoryWithCustomDataSourceRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2014, 6, 5) self.set_end_date(2014, 6, 6) self.aapl = self.add_data(CustomData, "AAPL", Resolution.MINUTE).symbol self.spy = self.add_data(CustomData, "SPY", Resolution.MINUTE).symbol def on_end_of_algorithm(self): aapl_history = self.history(CustomData, self.aapl, self.start_date, self.end_date, Resolution.MINUTE, fill_forward=False, extended_market_hours=False, data_normalization_mode=DataNormalizationMode.RAW).droplevel(0, axis=0) spy_history = self.history(CustomData, self.spy, self.start_date, self.end_date, Resolution.MINUTE, fill_forward=False, extended_market_hours=False, data_normalization_mode=DataNormalizationMode.RAW).droplevel(0, axis=0) if aapl_history.size == 0 or spy_history.size == 0: raise AssertionError("At least one of the history results is empty") # Check that both resutls contain the same data, since CustomData fetches APPL data regardless of the symbol if not aapl_history.equals(spy_history): raise AssertionError("Histories are not equal") class CustomData(PythonData): '''Custom data source for the regression test algorithm, which returns AAPL equity data regardless of the symbol requested.''' def get_source(self, config, date, is_live_mode): return TradeBar().get_source( SubscriptionDataConfig( config, CustomData, # Create a new symbol as equity so we find the existing data files # Symbol.create(config.mapped_symbol, SecurityType.EQUITY, config.market)), Symbol.create("AAPL", SecurityType.EQUITY, config.market)), date, is_live_mode) def reader(self, config, line, date, is_live_mode): trade_bar = TradeBar.parse_equity(config, line, date) data = CustomData() data.time = trade_bar.time data.value = trade_bar.value data.close = trade_bar.close data.open = trade_bar.open data.high = trade_bar.high data.low = trade_bar.low data.volume = trade_bar.volume return 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 : Regression algorithm which tests that a two leg currency conversion happens correctly
```python from AlgorithmImports import * class TwoLegCurrencyConversionRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2018, 4, 4) self.set_end_date(2018, 4, 4) self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH) # GDAX doesn't have LTCETH or ETHLTC, but they do have ETHUSD and LTCUSD to form a path between ETH and LTC self.set_account_currency("ETH") self.set_cash("ETH", 100000) self.set_cash("LTC", 100000) self.set_cash("USD", 100000) self._eth_usd_symbol = self.add_crypto("ETHUSD", Resolution.MINUTE).symbol self._ltc_usd_symbol = self.add_crypto("LTCUSD", Resolution.MINUTE).symbol def on_data(self, data): if not self.portfolio.invested: self.market_order(self._ltc_usd_symbol, 1) def on_end_of_algorithm(self): ltc_cash = self.portfolio.cash_book["LTC"] conversion_symbols = [x.symbol for x in ltc_cash.currency_conversion.conversion_rate_securities] if len(conversion_symbols) != 2: raise ValueError( f"Expected two conversion rate securities for LTC to ETH, is {len(conversion_symbols)}") if conversion_symbols[0] != self._ltc_usd_symbol: raise ValueError( f"Expected first conversion rate security from LTC to ETH to be {self._ltc_usd_symbol}, is {conversion_symbols[0]}") if conversion_symbols[1] != self._eth_usd_symbol: raise ValueError( f"Expected second conversion rate security from LTC to ETH to be {self._eth_usd_symbol}, is {conversion_symbols[1]}") ltc_usd_value = self.securities[self._ltc_usd_symbol].get_last_data().value eth_usd_value = self.securities[self._eth_usd_symbol].get_last_data().value expected_conversion_rate = ltc_usd_value / eth_usd_value actual_conversion_rate = ltc_cash.conversion_rate if actual_conversion_rate != expected_conversion_rate: raise ValueError( f"Expected conversion rate from LTC to ETH to be {expected_conversion_rate}, is {actual_conversion_rate}") ```
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 verifying OnEndOfDay callbacks are called as expected. See GH issue 2865.
```python from AlgorithmImports import * class OnEndOfDayRegressionAlgorithm(QCAlgorithm): '''Test algorithm verifying OnEndOfDay callbacks are called as expected. See GH issue 2865.''' 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.set_cash(100000) self._spy_symbol = Symbol.create("SPY", SecurityType.EQUITY, Market.USA) self._bac_symbol = Symbol.create("BAC", SecurityType.EQUITY, Market.USA) self._ibm_symbol = Symbol.create("IBM", SecurityType.EQUITY, Market.USA) self._on_end_of_day_spy_call_count = 0 self._on_end_of_day_bac_call_count = 0 self._on_end_of_day_ibm_call_count = 0 self.add_universe('my_universe_name', self.selection) def selection(self, time): if time.day == 8: return [self._spy_symbol.value, self._ibm_symbol.value] return [self._spy_symbol.value] def on_end_of_day(self, symbol): '''We expect it to be called on each day after the first selection process happens and the algorithm has a security in it ''' if symbol == self._spy_symbol: if self._on_end_of_day_spy_call_count == 0: # just the first time self.set_holdings(self._spy_symbol, 0.5) self.add_equity("BAC") self._on_end_of_day_spy_call_count += 1 if symbol == self._bac_symbol: if self._on_end_of_day_bac_call_count == 0: # just the first time self.set_holdings(self._bac_symbol, 0.5) self._on_end_of_day_bac_call_count += 1 if symbol == self._ibm_symbol: self._on_end_of_day_ibm_call_count += 1 self.log("OnEndOfDay() called: " + str(self.utc_time) + ". SPY count " + str(self._on_end_of_day_spy_call_count) + ". BAC count " + str(self._on_end_of_day_bac_call_count) + ". IBM count " + str(self._on_end_of_day_ibm_call_count)) def on_end_of_algorithm(self): '''Assert expected behavior''' if self._on_end_of_day_spy_call_count != 5: raise ValueError("OnEndOfDay(SPY) unexpected count call " + str(self._on_end_of_day_spy_call_count)) if self._on_end_of_day_bac_call_count != 4: raise ValueError("OnEndOfDay(BAC) unexpected count call " + str(self._on_end_of_day_bac_call_count)) if self._on_end_of_day_ibm_call_count != 1: raise ValueError("OnEndOfDay(IBM) unexpected count call " + str(self._on_end_of_day_ibm_call_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 : Regression algorithm illustrating how to request history data for different data normalization modes.
```python from AlgorithmImports import * class HistoryWithDifferentDataNormalizationModeRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 7) self.set_end_date(2014, 1, 1) self.aapl_equity_symbol = self.add_equity("AAPL", Resolution.DAILY).symbol self.es_future_symbol = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.DAILY).symbol def on_end_of_algorithm(self): equity_data_normalization_modes = [ DataNormalizationMode.RAW, DataNormalizationMode.ADJUSTED, DataNormalizationMode.SPLIT_ADJUSTED ] self.check_history_results_for_data_normalization_modes(self.aapl_equity_symbol, self.start_date, self.end_date, Resolution.DAILY, equity_data_normalization_modes) future_data_normalization_modes = [ DataNormalizationMode.RAW, DataNormalizationMode.BACKWARDS_RATIO, DataNormalizationMode.BACKWARDS_PANAMA_CANAL, DataNormalizationMode.FORWARD_PANAMA_CANAL ] self.check_history_results_for_data_normalization_modes(self.es_future_symbol, self.start_date, self.end_date, Resolution.DAILY, future_data_normalization_modes) def check_history_results_for_data_normalization_modes(self, symbol, start, end, resolution, data_normalization_modes): history_results = [self.history([symbol], start, end, resolution, data_normalization_mode=x) for x in data_normalization_modes] history_results = [x.droplevel(0, axis=0) for x in history_results] if len(history_results[0].index.levels) == 3 else history_results history_results = [x.loc[symbol].close for x in history_results] if any(x.size == 0 or x.size != history_results[0].size for x in history_results): raise AssertionError(f"History results for {symbol} have different number of bars") # Check that, for each history result, close prices at each time are different for these securities (AAPL and ES) for j in range(history_results[0].size): close_prices = set(history_results[i][j] for i in range(len(history_results))) if len(close_prices) != len(data_normalization_modes): raise AssertionError(f"History results for {symbol} have different close prices at the same time") ```
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 delistings for Futures and Futures Options to ensure that they are delisted at the expected times.
```python from AlgorithmImports import * class FuturesAndFutures_optionsExpiryTimeAndLiquidationRegressionAlgorithm(QCAlgorithm): def initialize(self): self.invested = False self.liquidated = 0 self.delistings_received = 0 self.expected_expiry_warning_time = datetime(2020, 6, 19) self.expected_expiry_delisting_time = datetime(2020, 6, 20) self.expected_liquidation_time = datetime(2020, 6, 20) self.set_start_date(2020, 1, 5) self.set_end_date(2020, 12, 1) self.set_cash(100000) es = Symbol.create_future( "ES", Market.CME, datetime(2020, 6, 19) ) es_option = Symbol.create_option( es, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3400.0, datetime(2020, 6, 19) ) self.es_future = self.add_future_contract(es, Resolution.MINUTE).symbol self.es_future_option = self.add_future_option_contract(es_option, Resolution.MINUTE).symbol def on_data(self, data: Slice): for delisting in data.delistings.values(): self.delistings_received += 1 if delisting.type == DelistingType.WARNING and delisting.time != self.expected_expiry_warning_time: raise AssertionError(f"Expiry warning with time {delisting.time} but is expected to be {self.expected_expiry_warning_time}") if delisting.type == DelistingType.WARNING and delisting.time != datetime(self.time.year, self.time.month, self.time.day): raise AssertionError(f"Delisting warning received at an unexpected date: {self.time} - expected {delisting.time}") if delisting.type == DelistingType.DELISTED and delisting.time != self.expected_expiry_delisting_time: raise AssertionError(f"Delisting occurred at unexpected time: {delisting.time} - expected: {self.expected_expiry_delisting_time}") if delisting.type == DelistingType.DELISTED and delisting.time != datetime(self.time.year, self.time.month, self.time.day): raise AssertionError(f"Delisting notice received at an unexpected date: {self.time} - expected {delisting.time}") if not self.invested and \ (self.es_future in data.bars or self.es_future in data.quote_bars) and \ (self.es_future_option in data.bars or self.es_future_option in data.quote_bars): self.invested = True self.market_order(self.es_future, 1) self.market_order(self.es_future_option, 1) def on_order_event(self, order_event: OrderEvent): if order_event.direction != OrderDirection.SELL or order_event.status != OrderStatus.FILLED: return # * Future Liquidation # * Future Option Exercise # * We expect NO Underlying Future Liquidation because we already hold a Long future position so the FOP Put selling leaves us breakeven self.liquidated += 1 if order_event.symbol.security_type == SecurityType.FUTURE_OPTION and self.expected_liquidation_time != self.time: raise AssertionError(f"Expected to liquidate option {order_event.symbol} at {self.expected_liquidation_time}, instead liquidated at {self.time}") if order_event.symbol.security_type == SecurityType.FUTURE and \ (self.expected_liquidation_time - timedelta(minutes=1)) != self.time and \ self.expected_liquidation_time != self.time: raise AssertionError(f"Expected to liquidate future {order_event.symbol} at {self.expected_liquidation_time} (+1 minute), instead liquidated at {self.time}") def on_end_of_algorithm(self): if not self.invested: raise AssertionError("Never invested in ES futures and FOPs") if self.delistings_received != 4: raise AssertionError(f"Expected 4 delisting events received, found: {self.delistings_received}") if self.liquidated != 2: raise AssertionError(f"Expected 3 liquidation events, found {self.liquidated}") ```
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 a default symbol is created using equity market when scheduling if none found
```python from AlgorithmImports import * class DefaultSchedulingSymbolRegressionAlgorithm(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) # implicitly figured usa equity self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open("AAPL"), self._implicit_check) # picked up from cache self.add_index("SPX") self.schedule.on(self.date_rules.tomorrow, self.time_rules.before_market_close("SPX", extended_market_close = True), self._explicit_check) def _implicit_check(self): self._implicitChecked = True if self.time.time() != time(9, 30, 0): raise RegressionTestException(f"Unexpected time of day {self.time.time()}") def _explicit_check(self): self._explicitChecked = True if self.time.time() != time(16, 15, 0): raise RegressionTestException(f"Unexpected time of day {self.time.time()}") def on_end_of_algorithm(self): if not self._explicitChecked or not self._implicitChecked: raise RegressionTestException("Failed to run expected checks!") ```
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="MaximumDrawdownPercentPerSecurity"/>.
```python from AlgorithmImports import * from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm from Risk.MaximumDrawdownPercentPerSecurity import MaximumDrawdownPercentPerSecurity class MaximumDrawdownPercentPerSecurityFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm): def initialize(self): super().initialize() self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create("AAPL", SecurityType.EQUITY, Market.USA))) self.set_risk_management(MaximumDrawdownPercentPerSecurity(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) future option expiry for calls. We expect 3 orders from the algorithm, which are: * Initial entry, buy ES Call Option (expiring ITM) * Option exercise, receiving ES future contracts * Future contract liquidation, due to impending 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 FutureOptionCallITMExpiryRegressionAlgorithm(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 <= 3200.0 and x.id.option_right == OptionRight.CALL], 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.CALL, 3200.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.schedule_callback) def schedule_callback(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}") elif 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: # Expected contract is ES19H21 Call Option expiring ITM @ 3250 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"{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_future_option_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security): expected_liquidation_time_utc = datetime(2020, 6, 20, 4, 0, 0) if order_event.direction == OrderDirection.SELL and future.holdings.quantity != 0: # We expect the contract to have been liquidated immediately raise AssertionError(f"Did not liquidate existing holdings for Symbol {future.symbol}") if order_event.direction == OrderDirection.SELL and order_event.utc_time.replace(tzinfo=None) != expected_liquidation_time_utc: raise AssertionError(f"Liquidated future contract, but not at the expected time. Expected: {expected_liquidation_time_utc} - found {order_event.utc_time.replace(tzinfo=None)}") # 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.0: raise AssertionError("Option did not exercise at expected strike price (3200)") if future.holdings.quantity != 1: # Here, we expect to have some holdings in the underlying, but not in the future option anymore. raise AssertionError(f"Exercised option contract, but we have no holdings for Future {future.symbol}") if option_contract.holdings.quantity != 0: raise AssertionError(f"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}") 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(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}") 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 asserting that universe symbols selection can be done by returning the symbol IDs in the selection function
```python from AlgorithmImports import * class SelectUniverseSymbolsFromIDRegressionAlgorithm(QCAlgorithm): ''' Regression algorithm asserting that universe symbols selection can be done by returning the symbol IDs in the selection function ''' def initialize(self): self.set_start_date(2014, 3, 24) self.set_end_date(2014, 3, 26) self.set_cash(100000) self._securities = [] self.universe_settings.resolution = Resolution.DAILY self.add_universe(self.select_symbol) def select_symbol(self, fundamental): symbols = [x.symbol for x in fundamental] if not symbols: return [] self.log(f"Symbols: {', '.join([str(s) for s in symbols])}") # Just for testing, but more filtering could be done here as shown below: #symbols = [x.symbol for x in fundamental if x.asset_classification.morningstar_sector_code == MorningstarSectorCode.TECHNOLOGY] history = self.history(symbols, datetime(1998, 1, 1), self.time, Resolution.DAILY) all_time_highs = history['high'].unstack(0).max() last_closes = history['close'].unstack(0).iloc[-1] security_ids = (last_closes / all_time_highs).sort_values().index[-5:] return security_ids def on_securities_changed(self, changes): self._securities.extend(changes.added_securities) def on_end_of_algorithm(self): if not self._securities: raise AssertionError("No securities were 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 : Algorithm asserting that the consolidators are removed from the SubscriptionManager. This makes sure that we don't lose references to python consolidators when they are wrapped in a DataConsolidatorPythonWrapper.
```python from AlgorithmImports import * class ManuallyRemovedConsolidatorsAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.consolidators = [] self.spy = self.add_equity("SPY").symbol # Case 1: consolidator registered through a RegisterIndicator() call, # which will wrap the consolidator instance in a DataConsolidatorPythonWrapper consolidator = self.resolve_consolidator(self.spy, Resolution.MINUTE) self.consolidators.append(consolidator) indicator_name = self.create_indicator_name(self.spy, "close", Resolution.MINUTE) identity = Identity(indicator_name) self.indicator = self.register_indicator(self.spy, identity, consolidator) # Case 2: consolidator registered directly through the SubscriptionManager consolidator = self.resolve_consolidator(self.spy, Resolution.MINUTE) self.consolidators.append(consolidator) self.subscription_manager.add_consolidator(self.spy, consolidator) # Case 3: custom python consolidator not derived from IDataConsolidator consolidator = CustomQuoteBarConsolidator(timedelta(hours=1)) self.consolidators.append(consolidator) self.subscription_manager.add_consolidator(self.spy, consolidator) def on_end_of_algorithm(self) -> None: # Remove the first consolidator for i in range(3): consolidator = self.consolidators[i] self.remove_consolidator(consolidator, expected_consolidator_count=2 - i) def remove_consolidator(self, consolidator: IDataConsolidator, expected_consolidator_count: int) -> None: self.subscription_manager.remove_consolidator(self.spy, consolidator) consolidator_count = sum(s.consolidators.count for s in self.subscription_manager.subscriptions) if consolidator_count != expected_consolidator_count: raise AssertionError(f"Unexpected number of consolidators after removal. " f"Expected: {expected_consolidator_count}. Actual: {consolidator_count}") class CustomQuoteBarConsolidator(PythonConsolidator): '''A custom quote bar consolidator that inherits from PythonConsolidator and implements the IDataConsolidator interface, it must implement all of IDataConsolidator. Reference PythonConsolidator.cs and DataConsolidatorPythonWrapper.PY for more information. This class shows how to implement a consolidator from scratch in Python, this gives us more freedom to determine the behavior of the consolidator but can't leverage any of the built in functions of an inherited class. For this example we implemented a Quotebar from scratch''' def __init__(self, period): #IDataConsolidator required vars for all consolidators self.consolidated = None #Most recently consolidated piece of data. self.working_data = None #Data being currently consolidated self.input_type = QuoteBar #The type consumed by this consolidator self.output_type = QuoteBar #The type produced by this consolidator #Consolidator Variables self.period = period def update(self, data): '''Updates this consolidator with the specified data''' #If we don't have bar yet, create one if self.working_data is None: self.working_data = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size, data.ask,data.last_ask_size,self.period) #Update bar using QuoteBar's update() self.working_data.update(data.value, data.bid.close, data.ask.close, 0, data.last_bid_size, data.last_ask_size) def scan(self, time): '''Scans this consolidator to see if it should emit a bar due to time passing''' if self.period is not None and self.working_data is not None: if time - self.working_data.time >= self.period: #Trigger the event handler with a copy of self and the data self.on_data_consolidated(self, self.working_data) #Set the most recent consolidated piece of data and then clear the working_data self.consolidated = self.working_data self.working_data = 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 : def initialize(self) -> None:
```python from AlgorithmImports import * from collections import deque from math import isclose class CustomIndicatorWithExtensionAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2013, 10, 9) self.set_end_date(2013, 10, 9) self._spy = self.add_equity("SPY", Resolution.MINUTE).symbol self._sma_values = [] self._period = 10 self._sma = self.sma(self._spy, self._period, Resolution.MINUTE) self._sma.updated += self.on_sma_updated self._custom_sma = CustomSimpleMovingAverage("My SMA", self._period) self._ext = IndicatorExtensions.of(self._custom_sma, self._sma) self._ext.updated += self.on_indicator_extension_updated self._sma_minus_custom = IndicatorExtensions.minus(self._sma, self._custom_sma) self._sma_minus_custom.updated += self.on_minus_updated self._sma_was_updated = False self._custom_sma_was_updated = False self._sma_minus_custom_was_updated = False def on_sma_updated(self, sender: object, updated: IndicatorDataPoint) -> None: self._sma_was_updated = True if self._sma.is_ready: self._sma_values.append(self._sma.current.value) def on_indicator_extension_updated(self, sender: object, updated: IndicatorDataPoint) -> None: self._custom_sma_was_updated = True sma_last_values = self._sma_values[-self._period:] expected = sum(sma_last_values) / len(sma_last_values) if not isclose(expected, self._custom_sma.value): raise AssertionError(f"Expected the custom SMA to calculate the moving average of the last {self._period} values of the SMA. " f"Current expected: {expected}. Actual {self._custom_sma.value}.") self.debug(f"{self._sma.current.value} :: {self._custom_sma.value} :: {updated}") def on_minus_updated(self, sender: object, updated: IndicatorDataPoint) -> None: self._sma_minus_custom_was_updated = True expected = self._sma.current.value - self._custom_sma.value if not isclose(expected, self._sma_minus_custom.current.value): raise AssertionError(f"Expected the composite minus indicator to calculate the difference between the SMA and custom SMA indicators. " f"Expected: {expected}. Actual {self._sma_minus_custom.current.value}.") def on_end_of_algorithm(self) -> None: if not (self._sma_was_updated and self._custom_sma_was_updated and self._sma_minus_custom_was_updated): raise AssertionError("Expected all indicators to have been updated.") # Custom indicator class CustomSimpleMovingAverage(PythonIndicator): def __init__(self, name: str, period: int) -> None: self.name = name self.value = 0 self.warm_up_period = period self._queue = deque(maxlen=period) def update(self, input: BaseData) -> bool: self._queue.appendleft(input.value) count = len(self._queue) self.value = sum(self._queue) / count return count == self._queue.maxlen ```
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 of custom volatility model
```python from AlgorithmImports import * class CustomVolatilityModelAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013,10,7) #Set Start Date self.set_end_date(2015,7,15) #Set End Date self.set_cash(100000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data self.equity = self.add_equity("SPY", Resolution.DAILY) self.equity.set_volatility_model(CustomVolatilityModel(10)) def on_data(self, data): if not self.portfolio.invested and self.equity.volatility_model.volatility > 0: self.set_holdings("SPY", 1) # Python implementation of StandardDeviationOfReturnsVolatilityModel # Computes the annualized sample standard deviation of daily returns as the volatility of the security # https://github.com/QuantConnect/Lean/blob/master/Common/Securities/Volatility/StandardDeviationOfReturnsVolatilityModel.cs class CustomVolatilityModel(): def __init__(self, periods): self.last_update = datetime.min self.last_price = 0 self.needs_update = False self.period_span = timedelta(1) self.window = RollingWindow(periods) # Volatility is a mandatory attribute self.volatility = 0 # Updates this model using the new price information in the specified security instance # Update is a mandatory method def update(self, security, data): time_since_last_update = data.end_time - self.last_update if time_since_last_update >= self.period_span and data.price > 0: if self.last_price > 0: self.window.add(float(data.price / self.last_price) - 1.0) self.needs_update = self.window.is_ready self.last_update = data.end_time self.last_price = data.price if self.window.count < 2: self.volatility = 0 return if self.needs_update: self.needs_update = False std = np.std([ x for x in self.window ]) self.volatility = std * np.sqrt(252.0) # Returns history requirements for the volatility model expressed in the form of history request # GetHistoryRequirements is a mandatory method def get_history_requirements(self, security, utc_time): # For simplicity's sake, we will not set a history requirement 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 : Demonstration of how to estimate constituents of QC500 index based on the company fundamentals The algorithm creates a default tradable and liquid universe containing 500 US equities which are chosen at the first trading day of each month.
```python from AlgorithmImports import * class ConstituentsQC500GeneratorAlgorithm(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.universe_settings.resolution = Resolution.DAILY self.set_start_date(2018, 1, 1) # Set Start Date self.set_end_date(2019, 1, 1) # Set End Date self.set_cash(100000) # Set Strategy Cash # Add QC500 Universe self.add_universe(self.universe.qc_500) ```
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 illustrating how to get a security's industry-standard identifier from its `Symbol`
```python from AlgorithmImports import * class IndustryStandardSecurityIdentifiersRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2014, 6, 5) self.set_end_date(2014, 6, 5) equity = self.add_equity("AAPL").symbol cusip = equity.cusip composite_figi = equity.composite_figi sedol = equity.sedol isin = equity.isin cik = equity.cik self.check_symbol_representation(cusip, "CUSIP") self.check_symbol_representation(composite_figi, "Composite FIGI") self.check_symbol_representation(sedol, "SEDOL") self.check_symbol_representation(isin, "ISIN") self.check_symbol_representation(f"{cik}", "CIK") # Check Symbol API vs QCAlgorithm API self.check_ap_is_symbol_representations(cusip, self.cusip(equity), "CUSIP") self.check_ap_is_symbol_representations(composite_figi, self.composite_figi(equity), "Composite FIGI") self.check_ap_is_symbol_representations(sedol, self.sedol(equity), "SEDOL") self.check_ap_is_symbol_representations(isin, self.isin(equity), "ISIN") self.check_ap_is_symbol_representations(f"{cik}", f"{self.cik(equity)}", "CIK") self.log(f"\n_aapl CUSIP: {cusip}" f"\n_aapl Composite FIGI: {composite_figi}" f"\n_aapl SEDOL: {sedol}" f"\n_aapl ISIN: {isin}" f"\n_aapl CIK: {cik}") def check_symbol_representation(self, symbol: str, standard: str) -> None: if not symbol: raise AssertionError(f"{standard} symbol representation is null or empty") def check_ap_is_symbol_representations(self, symbol_api_symbol: str, algorithm_api_symbol: str, standard: str) -> None: if symbol_api_symbol != algorithm_api_symbol: raise AssertionError(f"Symbol API {standard} symbol representation ({symbol_api_symbol}) does not match " f"QCAlgorithm API {standard} symbol representation ({algorithm_api_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 algorithm shows how you can handle universe selection in anyway you like, at any time you like. This algorithm has a list of 10 stocks that it rotates through every hour.
```python from AlgorithmImports import * class UserDefinedUniverseAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_cash(100000) self.set_start_date(2015, 1, 1) self.set_end_date(2015, 12, 1) self._symbols = ["SPY", "GOOG", "IBM", "AAPL", "MSFT", "CSCO", "ADBE", "WMT"] self.universe_settings.resolution = Resolution.HOUR self.add_universe('my_universe_name', Resolution.HOUR, self.selection) def selection(self, time: datetime) -> list[str]: index = time.hour % len(self._symbols) return [self._symbols[index]] def on_securities_changed(self, changes: SecurityChanges) -> None: for removed in changes.removed_securities: if removed.invested: self.liquidate(removed.symbol) for added in changes.added_securities: self.set_holdings(added.symbol, 1/len(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 : Regression algorithm to assert the behavior of <see cref="HistoricalReturnsAlphaModel"/>.
```python from AlgorithmImports import * from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm from Alphas.HistoricalReturnsAlphaModel import HistoricalReturnsAlphaModel class HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm): def initialize(self): super().initialize() self.set_alpha(HistoricalReturnsAlphaModel()) def on_end_of_algorithm(self): expected = 78 if self.insights.total_count != expected: raise AssertionError(f"The total number of insights should be {expected}. Actual: {self.insights.total_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 : Test algorithm using 'QCAlgorithm.add_alpha_model()'
```python from AlgorithmImports import * class AddAlphaModelAlgorithm(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) #Set Start Date self.set_end_date(2013,10,11) #Set End Date self.set_cash(100000) #Set Strategy Cash self.universe_settings.resolution = Resolution.DAILY spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA) fb = Symbol.create("FB", SecurityType.EQUITY, Market.USA) ibm = Symbol.create("IBM", SecurityType.EQUITY, Market.USA) # set algorithm framework models self.set_universe_selection(ManualUniverseSelectionModel([ spy, fb, ibm ])) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) self.set_execution(ImmediateExecutionModel()) self.add_alpha(OneTimeAlphaModel(spy)) self.add_alpha(OneTimeAlphaModel(fb)) self.add_alpha(OneTimeAlphaModel(ibm)) 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)) 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 : Test algorithm using 'ConfidenceWeightedPortfolioConstructionModel' and 'ConstantAlphaModel' generating a constant 'Insight' with a 0.25 confidence
```python from AlgorithmImports import * class ConfidenceWeightedFrameworkAlgorithm(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.''' # 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 symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ] # set algorithm framework models self.set_universe_selection(ManualUniverseSelectionModel(symbols)) self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, 0.25)) self.set_portfolio_construction(ConfidenceWeightedPortfolioConstructionModel()) self.set_execution(ImmediateExecutionModel()) def on_end_of_algorithm(self): # holdings value should be 0.25 - to avoid price fluctuation issue we compare with 0.28 and 0.23 if (self.portfolio.total_holdings_value > self.portfolio.total_portfolio_value * 0.28 or self.portfolio.total_holdings_value < self.portfolio.total_portfolio_value * 0.23): raise ValueError("Unexpected Total Holdings Value: " + str(self.portfolio.total_holdings_value)) ```
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 Consolidator Regression Algorithm shows some examples of how to build custom
```python from AlgorithmImports import * class CustomConsolidatorRegressionAlgorithm(QCAlgorithm): '''Custom Consolidator Regression Algorithm shows some examples of how to build custom consolidators in Python.''' def initialize(self): self.set_start_date(2013,10,4) self.set_end_date(2013,10,11) self.set_cash(100000) self.add_equity("SPY", Resolution.MINUTE) #Create 5 day QuoteBarConsolidator; set consolidated function; add to subscription manager five_day_consolidator = QuoteBarConsolidator(timedelta(days=5)) five_day_consolidator.data_consolidated += self.on_quote_bar_data_consolidated self.subscription_manager.add_consolidator("SPY", five_day_consolidator) #Create a 3:10PM custom quote bar consolidator timed_consolidator = DailyTimeQuoteBarConsolidator(time(hour=15, minute=10)) timed_consolidator.data_consolidated += self.on_quote_bar_data_consolidated self.subscription_manager.add_consolidator("SPY", timed_consolidator) #Create our entirely custom 2 day quote bar consolidator self.custom_consolidator = CustomQuoteBarConsolidator(timedelta(days=2)) self.custom_consolidator.data_consolidated += (self.on_quote_bar_data_consolidated) self.subscription_manager.add_consolidator("SPY", self.custom_consolidator) #Create an indicator and register a consolidator to it self.moving_average = SimpleMovingAverage(5) self.custom_consolidator2 = CustomQuoteBarConsolidator(timedelta(hours=1)) self.register_indicator("SPY", self.moving_average, self.custom_consolidator2) def on_quote_bar_data_consolidated(self, sender, bar): '''Function assigned to be triggered by consolidators. Designed to post debug messages to show how the examples work, including which consolidator is posting, as well as its values. If using an inherited class and not overwriting OnDataConsolidated we expect to see the super C# class as the sender type. Using sender.period only works when all consolidators have a Period value. ''' consolidator_info = str(type(sender)) + str(sender.period) self.debug("Bar Type: " + consolidator_info) self.debug("Bar Range: " + bar.time.ctime() + " - " + bar.end_time.ctime()) self.debug("Bar value: " + str(bar.close)) def on_data(self, slice): test = slice.get_values() if self.custom_consolidator.consolidated and slice.contains_key("SPY"): data = slice['SPY'] if self.moving_average.is_ready: if data.value > self.moving_average.current.price: self.set_holdings("SPY", .5) else : self.set_holdings("SPY", 0) class DailyTimeQuoteBarConsolidator(QuoteBarConsolidator): '''A custom QuoteBar consolidator that inherits from C# class QuoteBarConsolidator. This class shows an example of building on top of an existing consolidator class, it is important to note that this class can leverage the functions of QuoteBarConsolidator but its private fields (_period, _workingbar, etc.) are separate from this Python. For that reason if we want Scan() to work we must overwrite the function with our desired Scan function and trigger OnDataConsolidated(). For this particular example we implemented the scan method to trigger a consolidated bar at close_time everyday''' def __init__(self, close_time): self.close_time = close_time self.working_bar = None def update(self, data): '''Updates this consolidator with the specified data''' #If we don't have bar yet, create one if self.working_bar is None: self.working_bar = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size, data.ask,data.last_ask_size) #Update bar using QuoteBarConsolidator's AggregateBar() self.aggregate_bar(self.working_bar, data) def scan(self, time): '''Scans this consolidator to see if it should emit a bar due yet''' if self.working_bar is None: return #If its our desired bar end time take the steps to if time.hour == self.close_time.hour and time.minute == self.close_time.minute: #Set end time self.working_bar.end_time = time #Emit event using QuoteBarConsolidator's OnDataConsolidated() self.on_data_consolidated(self.working_bar) #Reset the working bar to None self.working_bar = None class CustomQuoteBarConsolidator(PythonConsolidator): '''A custom quote bar consolidator that inherits from PythonConsolidator and implements the IDataConsolidator interface, it must implement all of IDataConsolidator. Reference PythonConsolidator.cs and DataConsolidatorPythonWrapper.PY for more information. This class shows how to implement a consolidator from scratch in Python, this gives us more freedom to determine the behavior of the consolidator but can't leverage any of the built in functions of an inherited class. For this example we implemented a Quotebar from scratch''' def __init__(self, period): #IDataConsolidator required vars for all consolidators self.consolidated = None #Most recently consolidated piece of data. self.working_data = None #Data being currently consolidated self.input_type = QuoteBar #The type consumed by this consolidator self.output_type = QuoteBar #The type produced by this consolidator #Consolidator Variables self.period = period def update(self, data): '''Updates this consolidator with the specified data''' #If we don't have bar yet, create one if self.working_data is None: self.working_data = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size, data.ask,data.last_ask_size,self.period) #Update bar using QuoteBar's update() self.working_data.update(data.value, data.bid.close, data.ask.close, 0, data.last_bid_size, data.last_ask_size) def scan(self, time): '''Scans this consolidator to see if it should emit a bar due to time passing''' if self.period is not None and self.working_data is not None: if time - self.working_data.time >= self.period: #Trigger the event handler with a copy of self and the data self.on_data_consolidated(self, self.working_data) #Set the most recent consolidated piece of data and then clear the working_data self.consolidated = self.working_data self.working_data = 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 : Regression algorithm which tests a fine fundamental filtered universe, related to GH issue 4127
```python from AlgorithmImports import * class FineFundamentalFilteredUniverseRegressionAlgorithm(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, 10, 8) self.set_end_date(2014, 10, 13) self.universe_settings.resolution = Resolution.DAILY symbol = Symbol(SecurityIdentifier.generate_constituent_identifier("constituents-universe-qctest", SecurityType.EQUITY, Market.USA), "constituents-universe-qctest") self.add_universe(ConstituentsUniverse(symbol, self.universe_settings), self.fine_selection_function) def fine_selection_function(self, fine): return [ x.symbol for x in fine if x.company_profile != None and x.company_profile.headquarter_city != None and x.company_profile.headquarter_city.lower() == "cupertino" ] 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: if data.keys()[0].value != "AAPL": raise ValueError(f"Unexpected symbol was added to the universe: {data.keys()[0]}") self.set_holdings(data.keys()[0], 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 : The demonstration algorithm shows some of the most common order methods when working with Crypto assets.
```python from AlgorithmImports import * class BasicTemplateCryptoAlgorithm(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 # Although typically real brokerages as GDAX only support a single account currency, # here we add both USD and EUR to demonstrate how to handle non-USD account currencies. # Set Strategy Cash (USD) self.set_cash(10000) # Set Strategy Cash (EUR) # EUR/USD conversion rate will be updated dynamically self.set_cash("EUR", 10000) # Add some coins as initial holdings # When connected to a real brokerage, the amount specified in SetCash # will be replaced with the amount in your actual account. self.set_cash("BTC", 1) self.set_cash("ETH", 5) self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH) # You can uncomment the following lines when live trading with GDAX, # to ensure limit orders will only be posted to the order book and never executed as a taker (incurring fees). # Please note this statement has no effect in backtesting or paper trading. # self.default_order_properties = GDAXOrderProperties() # self.default_order_properties.post_only = True # Find more symbols here: http://quantconnect.com/data self.add_crypto("BTCUSD", Resolution.MINUTE) self.add_crypto("ETHUSD", Resolution.MINUTE) self.add_crypto("BTCEUR", Resolution.MINUTE) symbol = self.add_crypto("LTCUSD", Resolution.MINUTE).symbol # create two moving averages self.fast = self.ema(symbol, 30, Resolution.MINUTE) self.slow = self.ema(symbol, 60, 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 ''' # Note: all limit orders in this algorithm will be paying taker fees, # they shouldn't, but they do (for now) because of this issue: # https://github.com/QuantConnect/Lean/issues/1852 if self.time.hour == 1 and self.time.minute == 0: # Sell all ETH holdings with a limit order at 1% above the current price limit_price = round(self.securities["ETHUSD"].price * 1.01, 2) quantity = self.portfolio.cash_book["ETH"].amount self.limit_order("ETHUSD", -quantity, limit_price) elif self.time.hour == 2 and self.time.minute == 0: # Submit a buy limit order for BTC at 5% below the current price usd_total = self.portfolio.cash_book["USD"].amount limit_price = round(self.securities["BTCUSD"].price * 0.95, 2) # use only half of our total USD quantity = usd_total * 0.5 / limit_price self.limit_order("BTCUSD", quantity, limit_price) elif self.time.hour == 2 and self.time.minute == 1: # Get current USD available, subtracting amount reserved for buy open orders usd_total = self.portfolio.cash_book["USD"].amount usd_reserved = sum(x.quantity * x.limit_price for x in [x for x in self.transactions.get_open_orders() if x.direction == OrderDirection.BUY and x.type == OrderType.LIMIT and (x.symbol.value == "BTCUSD" or x.symbol.value == "ETHUSD")]) usd_available = usd_total - usd_reserved self.debug("usd_available: {}".format(usd_available)) # Submit a marketable buy limit order for ETH at 1% above the current price limit_price = round(self.securities["ETHUSD"].price * 1.01, 2) # use all of our available USD quantity = usd_available / limit_price # this order will be rejected (for now) because of this issue: # https://github.com/QuantConnect/Lean/issues/1852 self.limit_order("ETHUSD", quantity, limit_price) # use only half of our available USD quantity = usd_available * 0.5 / limit_price self.limit_order("ETHUSD", quantity, limit_price) elif self.time.hour == 11 and self.time.minute == 0: # Liquidate our BTC holdings (including the initial holding) self.set_holdings("BTCUSD", 0) elif self.time.hour == 12 and self.time.minute == 0: # Submit a market buy order for 1 BTC using EUR self.buy("BTCEUR", 1) # Submit a sell limit order at 10% above market price limit_price = round(self.securities["BTCEUR"].price * 1.1, 2) self.limit_order("BTCEUR", -1, limit_price) elif self.time.hour == 13 and self.time.minute == 0: # Cancel the limit order if not filled self.transactions.cancel_open_orders("BTCEUR") elif self.time.hour > 13: # To include any initial holdings, we read the LTC amount from the cashbook # instead of using Portfolio["LTCUSD"].quantity if self.fast > self.slow: if self.portfolio.cash_book["LTC"].amount == 0: self.buy("LTCUSD", 10) else: if self.portfolio.cash_book["LTC"].amount > 0: self.liquidate("LTCUSD") def on_order_event(self, order_event): self.debug("{} {}".format(self.time, order_event.to_string())) def on_end_of_algorithm(self): self.log("{} - TotalPortfolioValue: {}".format(self.time, self.portfolio.total_portfolio_value)) self.log("{} - CashBook: {}".format(self.time, self.portfolio.cash_book)) ```
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 PearsonCorrelationPairsTradingAlphaModel. This model extendes BasePairsTradingAlphaModel and uses Pearson correlation to rank the pairs trading candidates and use the best candidate to trade.
```python from AlgorithmImports import * from Alphas.PearsonCorrelationPairsTradingAlphaModel import PearsonCorrelationPairsTradingAlphaModel class PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm(QCAlgorithm): '''Framework algorithm that uses the PearsonCorrelationPairsTradingAlphaModel. This model extendes BasePairsTradingAlphaModel and uses Pearson correlation to rank the pairs trading candidates and use the best candidate to trade.''' def initialize(self): self.set_start_date(2013,10,7) self.set_end_date(2013,10,11) symbols = [Symbol.create(ticker, SecurityType.EQUITY, Market.USA) for ticker in ["SPY", "AIG", "BAC", "IBM"]] # Manually add SPY and AIG when the algorithm starts self.set_universe_selection(ManualUniverseSelectionModel(symbols[:2])) # At midnight, add all securities every day except on the last data # With this procedure, the Alpha Model will experience multiple universe changes self.add_universe_selection(ScheduledUniverseSelectionModel( self.date_rules.every_day(), self.time_rules.midnight, lambda dt: symbols if dt.day <= (self.end_date - timedelta(1)).day else [])) self.set_alpha(PearsonCorrelationPairsTradingAlphaModel(252, Resolution.DAILY)) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) self.set_execution(ImmediateExecutionModel()) self.set_risk_management(NullRiskManagementModel()) def on_end_of_algorithm(self) -> None: # 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 consolidator 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 regression algorithm tests In The Money (ITM) future option expiry for short calls. We expect 3 orders from the algorithm, which are: * Initial entry, sell ES Call Option (expiring ITM) * Option assignment, sell 1 contract of the underlying (ES) * Future contract expiry, liquidation (buy 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 FutureOptionShortCallITMExpiryRegressionAlgorithm(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 <= 3100.0 and x.id.option_right == OptionRight.CALL], 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.CALL, 3100.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 != 3100.0: raise AssertionError("Option was not assigned at expected strike price (3100)") if order_event.direction != OrderDirection.SELL 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.BUY 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 : This example demonstrates how to add futures with daily resolution.
```python from AlgorithmImports import * class BasicTemplateFuturesDailyAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 8) self.set_end_date(2014, 10, 10) self.set_cash(1000000) resolution = self.get_resolution() extended_market_hours = self.get_extended_market_hours() # Subscribe and set our expiry filter for the futures chain self.future_sp500 = self.add_future(Futures.Indices.SP_500_E_MINI, resolution, extended_market_hours=extended_market_hours) self.future_gold = self.add_future(Futures.Metals.GOLD, resolution, extended_market_hours=extended_market_hours) # set our expiry filter for this futures chain # SetFilter method accepts timedelta objects or integer for days. # The following statements yield the same filtering criteria self.future_sp500.set_filter(timedelta(0), timedelta(182)) self.future_gold.set_filter(0, 182) def on_data(self,slice): if not self.portfolio.invested: for chain in slice.future_chains: # Get contracts expiring no earlier than in 90 days contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value)) # if there is any contract, trade the front contract if len(contracts) == 0: continue contract = sorted(contracts, key = lambda x: x.expiry)[0] # if found, trade it. self.market_order(contract.symbol, 1) # Same as above, check for cases like trading on a friday night. elif all(x.exchange.hours.is_open(self.time, True) for x in self.securities.values() if x.invested): self.liquidate() def on_securities_changed(self, changes: SecurityChanges) -> None: if len(changes.removed_securities) > 0 and \ self.portfolio.invested and \ all(x.exchange.hours.is_open(self.time, True) for x in self.securities.values() if x.invested): self.liquidate() def get_resolution(self): return Resolution.DAILY def get_extended_market_hours(self): return False ```
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 : Regrssion algorithm to assert we can update indicators that inherit from IndicatorBase<TradeBar> with RenkoBar's
```python from AlgorithmImports import * class IndicatorWithRenkoBarsRegressionAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 9) self.add_equity("SPY") self.add_equity("AIG") spy_renko_consolidator = RenkoConsolidator(0.1) spy_renko_consolidator.data_consolidated += self.on_spy_data_consolidated aig_renko_consolidator = RenkoConsolidator(0.05) aig_renko_consolidator.data_consolidated += self.on_aig_data_consolidated self.subscription_manager.add_consolidator("SPY", spy_renko_consolidator) self.subscription_manager.add_consolidator("AIG", aig_renko_consolidator) self._mi = MassIndex("MassIndex", 9, 25) self._wasi = WilderAccumulativeSwingIndex("WilderAccumulativeSwingIndex", 8) self._wsi = WilderSwingIndex("WilderSwingIndex", 8) self._b = Beta("Beta", 3, "AIG", "SPY") self._indicators = [self._mi, self._wasi, self._wsi, self._b] def on_spy_data_consolidated(self, sender: object, renko_bar: RenkoBar) -> None: self._mi.update(renko_bar) self._wasi.update(renko_bar) self._wsi.update(renko_bar) self._b.update(renko_bar) def on_aig_data_consolidated(self, sender: object, renko_bar: RenkoBar) -> None: self._b.update(renko_bar) def on_end_of_algorithm(self) -> None: for indicator in self._indicators: if not indicator.is_ready: raise AssertionError(f"{indicator.name} indicator should be ready") elif indicator.current.value == 0: raise AssertionError(f"The current value of the {indicator.name} indicator should be different than zero") ```
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 'QCAlgorithm.add_universe_selection(IUniverseSelectionModel)'
```python from AlgorithmImports import * class AddUniverseSelectionModelAlgorithm(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,8) #Set Start Date self.set_end_date(2013,10,11) #Set End Date self.set_cash(100000) #Set Strategy Cash self.universe_settings.resolution = Resolution.DAILY # set algorithm framework models 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_universe_selection(ManualUniverseSelectionModel([ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ])) self.add_universe_selection(ManualUniverseSelectionModel([ Symbol.create("AAPL", SecurityType.EQUITY, Market.USA) ])) self.add_universe_selection(ManualUniverseSelectionModel( Symbol.create("SPY", SecurityType.EQUITY, Market.USA), # duplicate will be ignored Symbol.create("FB", SecurityType.EQUITY, Market.USA))) def on_end_of_algorithm(self): if self.universe_manager.count != 3: raise ValueError("Unexpected universe count") if self.universe_manager.active_securities.count != 3: raise ValueError("Unexpected active 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 : Example algorithm demonstrating the usage of the RSI indicator in combination with ETF constituents data to replicate the weighting of the ETF's assets in our own account.
```python from AlgorithmImports import * class ETFConstituentUniverseRSIAlphaModelAlgorithm(QCAlgorithm): ### <summary> ### Initialize the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. ### </summary> def initialize(self): self.set_start_date(2020, 12, 1) self.set_end_date(2021, 1, 31) self.set_cash(100000) self.set_alpha(ConstituentWeightedRsiAlphaModel()) self.set_portfolio_construction(InsightWeightingPortfolioConstructionModel()) self.set_execution(ImmediateExecutionModel()) spy = self.add_equity("SPY", Resolution.HOUR).symbol # We load hourly data for ETF constituents in this algorithm self.universe_settings.resolution = Resolution.HOUR self.settings.minimum_order_margin_portfolio_percentage = 0.01 self.add_universe(self.universe.etf(spy, self.universe_settings, self.filter_etf_constituents)) ### <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): return [i.symbol for i in constituents if i.weight is not None and i.weight >= 0.001] class ConstituentWeightedRsiAlphaModel(AlphaModel): def __init__(self, max_trades=None): self.rsi_symbol_data = {} def update(self, algorithm: QCAlgorithm, data: Slice): algo_constituents = [] for bar_symbol in data.bars.keys(): if not algorithm.securities[bar_symbol].cache.has_data(ETFConstituentUniverse): continue constituent_data = algorithm.securities[bar_symbol].cache.get_data(ETFConstituentUniverse) algo_constituents.append(constituent_data) if len(algo_constituents) == 0 or len(data.bars) == 0: # Don't do anything if we have no data we can work with return [] constituents = {i.symbol:i for i in algo_constituents} for bar in data.bars.values(): if bar.symbol not in constituents: # Dealing with a manually added equity, which in this case is SPY continue if bar.symbol not in self.rsi_symbol_data: # First time we're initializing the RSI. # It won't be ready now, but it will be # after 7 data points constituent = constituents[bar.symbol] self.rsi_symbol_data[bar.symbol] = SymbolData(bar.symbol, algorithm, constituent, 7) all_ready = all([sd.rsi.is_ready for sd in self.rsi_symbol_data.values()]) if not all_ready: # We're still warming up the RSI indicators. return [] insights = [] for symbol, symbol_data in self.rsi_symbol_data.items(): average_loss = symbol_data.rsi.average_loss.current.value average_gain = symbol_data.rsi.average_gain.current.value # If we've lost more than gained, then we think it's going to go down more direction = InsightDirection.DOWN if average_loss > average_gain else InsightDirection.UP # Set the weight of the insight as the weight of the ETF's # holding. The InsightWeightingPortfolioConstructionModel # will rebalance our portfolio to have the same percentage # of holdings in our algorithm that the ETF has. insights.append(Insight.price( symbol, timedelta(days=1), direction, float(average_loss if direction == InsightDirection.DOWN else average_gain), weight=float(symbol_data.constituent.weight) )) return insights class SymbolData: def __init__(self, symbol, algorithm, constituent, period): self.symbol = symbol self.constituent = constituent self.rsi = algorithm.rsi(symbol, period, MovingAverageType.EXPONENTIAL, Resolution.HOUR) ```
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 using FutureOptions daily resolution
```python from AlgorithmImports import * class FutureOptionDailyRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2020, 1, 7) self.set_end_date(2020, 1, 8) resolution = Resolution.DAILY # Add our underlying future contract self.es = self.add_future_contract( Symbol.create_future( Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 3, 20) ), resolution).symbol # Attempt to fetch a specific ITM future option contract es_options = [ self.add_future_option_contract(x, resolution).symbol for x in self.option_chain(self.es) if x.id.strike_price == 3200 and x.id.option_right == OptionRight.CALL ] self.es_option = es_options[0] # Validate it is the expected contract expected_contract = Symbol.create_option(self.es, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200, datetime(2020, 3, 20)) if self.es_option != expected_contract: raise AssertionError(f"Contract {self.es_option} was not the expected contract {expected_contract}") # Schedule a purchase of this contract tomorrow at 10AM when the market is open self.schedule.on(self.date_rules.tomorrow, self.time_rules.at(10,0,0), self.schedule_callback_buy) # Schedule liquidation at 2pm tomorrow when the market is open self.schedule.on(self.date_rules.tomorrow, self.time_rules.at(14,0,0), self.schedule_callback_liquidate) def schedule_callback_buy(self): self.market_order(self.es_option, 1) def on_data(self, slice): # Assert we are only getting data at 4PM NY, for ES future market closes at 16pm NY if slice.time.hour != 17: raise AssertionError(f"Expected data at 5PM each day; instead was {slice.time}") def schedule_callback_liquidate(self): self.liquidate() 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 : Test algorithm using 'InsightWeightingPortfolioConstructionModel' and 'ConstantAlphaModel' generating a constant 'Insight' with a 0.25 weight
```python from AlgorithmImports import * from Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel from Alphas.ConstantAlphaModel import ConstantAlphaModel from Portfolio.InsightWeightingPortfolioConstructionModel import InsightWeightingPortfolioConstructionModel from Execution.ImmediateExecutionModel import ImmediateExecutionModel class InsightWeightingFrameworkAlgorithm(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.''' # 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 symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ] # set algorithm framework models self.set_universe_selection(ManualUniverseSelectionModel(symbols)) self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None, 0.25)) self.set_portfolio_construction(InsightWeightingPortfolioConstructionModel()) self.set_execution(ImmediateExecutionModel()) def on_end_of_algorithm(self): # holdings value should be 0.25 - to avoid price fluctuation issue we compare with 0.28 and 0.23 if (self.portfolio.total_holdings_value > self.portfolio.total_portfolio_value * 0.28 or self.portfolio.total_holdings_value < self.portfolio.total_portfolio_value * 0.23): raise ValueError("Unexpected Total Holdings Value: " + str(self.portfolio.total_holdings_value)) ```
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 access the statistics results from within an algorithm through the `Statistics` property.
```python from AlgorithmImports import * from System.Collections.Generic import Dictionary class StatisticsResultsAlgorithm(QCAlgorithm): most_traded_security_statistic = "Most Traded Security" most_traded_security_trade_count_statistic = "Most Traded Security Trade Count" def initialize(self): self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.set_cash(100000) self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol self.ibm = self.add_equity("IBM", Resolution.MINUTE).symbol self.fast_spy_ema = self.ema(self.spy, 30, Resolution.MINUTE) self.slow_spy_ema = self.ema(self.spy, 60, Resolution.MINUTE) self.fast_ibm_ema = self.ema(self.spy, 10, Resolution.MINUTE) self.slow_ibm_ema = self.ema(self.spy, 30, Resolution.MINUTE) self.trade_counts = {self.spy: 0, self.ibm: 0} def on_data(self, data: Slice): if not self.slow_spy_ema.is_ready: return if self.fast_spy_ema > self.slow_spy_ema: self.set_holdings(self.spy, 0.5) elif self.securities[self.spy].invested: self.liquidate(self.spy) if self.fast_ibm_ema > self.slow_ibm_ema: self.set_holdings(self.ibm, 0.2) elif self.securities[self.ibm].invested: self.liquidate(self.ibm) def on_order_event(self, order_event): if order_event.status == OrderStatus.FILLED: # We can access the statistics summary at runtime statistics = self.statistics.summary statistics_str = "".join([f"{kvp.key}: {kvp.value}" for kvp in statistics]) self.debug(f"Statistics after fill:{statistics_str}") # Access a single statistic self.log(f"Total trades so far: {statistics[PerformanceMetrics.TOTAL_ORDERS]}") self.log(f"Sharpe Ratio: {statistics[PerformanceMetrics.SHARPE_RATIO]}") # -------- # We can also set custom summary statistics: if all(count == 0 for count in self.trade_counts.values()): if StatisticsResultsAlgorithm.most_traded_security_statistic in statistics: raise AssertionError(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_statistic} should not be set yet") if StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic in statistics: raise AssertionError(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic} should not be set yet") else: # The current most traded security should be set in the summary most_trade_security, most_trade_security_trade_count = self.get_most_trade_security() self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count) # Update the trade count self.trade_counts[order_event.symbol] += 1 # Set the most traded security most_trade_security, most_trade_security_trade_count = self.get_most_trade_security() self.set_summary_statistic(StatisticsResultsAlgorithm.most_traded_security_statistic, str(most_trade_security)) self.set_summary_statistic(StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic, most_trade_security_trade_count) # Re-calculate statistics: statistics = self.statistics.summary # Let's keep track of our custom summary statistics after the update self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count) def on_end_of_algorithm(self): statistics = self.statistics.summary if StatisticsResultsAlgorithm.most_traded_security_statistic not in statistics: raise AssertionError(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_statistic} should be in the summary statistics") if StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic not in statistics: raise AssertionError(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic} should be in the summary statistics") most_trade_security, most_trade_security_trade_count = self.get_most_trade_security() self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count) def check_most_traded_security_statistic(self, statistics: Dictionary[str, str], most_traded_security: Symbol, trade_count: int): most_traded_security_statistic = statistics[StatisticsResultsAlgorithm.most_traded_security_statistic] most_traded_security_trade_count_statistic = statistics[StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic] self.log(f"Most traded security: {most_traded_security_statistic}") self.log(f"Most traded security trade count: {most_traded_security_trade_count_statistic}") if most_traded_security_statistic != most_traded_security: raise AssertionError(f"Most traded security should be {most_traded_security} but it is {most_traded_security_statistic}") if most_traded_security_trade_count_statistic != str(trade_count): raise AssertionError(f"Most traded security trade count should be {trade_count} but it is {most_traded_security_trade_count_statistic}") def get_most_trade_security(self) -> tuple[Symbol, int]: most_trade_security = max(self.trade_counts, key=lambda symbol: self.trade_counts[symbol]) most_trade_security_trade_count = self.trade_counts[most_trade_security] return most_trade_security, most_trade_security_trade_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 : Example algorithm of using RiskParityPortfolioConstructionModel
```python from AlgorithmImports import * from Portfolio.RiskParityPortfolioConstructionModel import * class RiskParityPortfolioAlgorithm(QCAlgorithm): '''Example algorithm of using RiskParityPortfolioConstructionModel''' def initialize(self): self.set_start_date(2021, 2, 21) # Set Start Date self.set_end_date(2021, 3, 30) self.set_cash(100000) # Set Strategy Cash self.set_security_initializer(lambda security: security.set_market_price(self.get_last_known_price(security))) self.add_equity("SPY", Resolution.DAILY) self.add_equity("AAPL", Resolution.DAILY) self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1))) self.set_portfolio_construction(RiskParityPortfolioConstructionModel()) ```
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. Similar to CustomDataUniverseRegressionAlgorithm but with a custom schedule
```python from AlgorithmImports import * class CustomDataUniverseScheduledRegressionAlgorithm(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 = [] self._selection_time = [datetime(2014, 3, 25), datetime(2014, 3, 27), datetime(2014, 3, 29)] self.universe_settings.resolution = Resolution.DAILY self.universe_settings.schedule.on(self.date_rules.on(self._selection_time)) self.add_universe(CoarseFundamental, "custom-data-universe", self.universe_settings, self.selection) # This use case is also valid/same because it will use the algorithm settings by default # self.add_universe(CoarseFundamental, "custom-data-universe", self.selection) 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 self.current_underlying_symbols: 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}") # equity daily data arrives at 16 pm but custom data is set to arrive at midnight self.current_underlying_symbols = [symbol for symbol in data.keys() if symbol.security_type is SecurityType.EQUITY] def on_end_of_algorithm(self): if len(self._selection_time) != 0: raise ValueError(f"Unexpected selection times, missing {len(self._selection_time)}") 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 : A demonstration of consolidating futures data into larger bars for your algorithm.
```python from AlgorithmImports import * class BasicTemplateFuturesConsolidationAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.set_cash(1000000) # Subscribe and set our expiry filter for the futures chain futureSP500 = self.add_future(Futures.Indices.SP_500_E_MINI) # set our expiry filter for this future chain # SetFilter method accepts timedelta objects or integer for days. # The following statements yield the same filtering criteria futureSP500.set_filter(0, 182) # future.set_filter(timedelta(0), timedelta(182)) self.consolidators = dict() def on_data(self,slice): pass def on_data_consolidated(self, sender, quote_bar): self.log("OnDataConsolidated called on " + str(self.time)) self.log(str(quote_bar)) def on_securities_changed(self, changes): for security in changes.added_securities: consolidator = QuoteBarConsolidator(timedelta(minutes=5)) consolidator.data_consolidated += self.on_data_consolidated self.subscription_manager.add_consolidator(security.symbol, consolidator) self.consolidators[security.symbol] = consolidator for security in changes.removed_securities: consolidator = self.consolidators.pop(security.symbol) self.subscription_manager.remove_consolidator(security.symbol, consolidator) consolidator.data_consolidated -= self.on_data_consolidated ```
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 indicators history window usage
```python from AlgorithmImports import * class IndicatorHistoryAlgorithm(QCAlgorithm): '''Demonstration algorithm of indicators history window usage.''' 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) self.set_end_date(2014, 12, 31) self.set_cash(25000) self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol self.bollinger_bands = self.bb(self._symbol, 20, 2.0, resolution=Resolution.DAILY) # Let's keep BB values for a 20 day period self.bollinger_bands.window.size = 20 # Also keep the same period of data for the middle band self.bollinger_bands.middle_band.window.size = 20 def on_data(self, slice: Slice): # Let's wait for our indicator to fully initialize and have a full window of history data if not self.bollinger_bands.window.is_ready: return # We can access the current and oldest (in our period) values of the indicator self.log(f"Current BB value: {self.bollinger_bands[0].end_time} - {self.bollinger_bands[0].value}") self.log(f"Oldest BB value: {self.bollinger_bands[self.bollinger_bands.window.count - 1].end_time} - " f"{self.bollinger_bands[self.bollinger_bands.window.count - 1].value}") # Let's log the BB values for the last 20 days, for demonstration purposes on how it can be enumerated for data_point in self.bollinger_bands: self.log(f"BB @{data_point.end_time}: {data_point.value}") # We can also do the same for internal indicators: middle_band = self.bollinger_bands.middle_band self.log(f"Current BB Middle Band value: {middle_band[0].end_time} - {middle_band[0].value}") self.log(f"Oldest BB Middle Band value: {middle_band[middle_band.window.count - 1].end_time} - " f"{middle_band[middle_band.window.count - 1].value}") for data_point in middle_band: self.log(f"BB Middle Band @{data_point.end_time}: {data_point.value}") # We are done now! 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 template algorithm simply initializes the date range and cash
```python from AlgorithmImports import * class LimitFillRegressionAlgorithm(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) #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.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.''' if data.contains_key("SPY"): if self.is_round_hour(self.time): negative = 1 if self.time < (self.start_date + timedelta(days=2)) else -1 self.limit_order("SPY", negative*10, data["SPY"].price) def is_round_hour(self, date_time): '''Verify whether datetime is round hour''' return date_time.minute == 0 and date_time.second == 0 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 : Regression algorithm asserting the behavior of auxiliary data history requests
```python from AlgorithmImports import * class HistoryAuxiliaryDataRegressionAlgorithm(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(2021, 1, 1) self.set_end_date(2021, 1, 5) aapl = self.add_equity("AAPL", Resolution.DAILY).symbol # multi symbol request spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA) multi_symbol_request = self.history(Dividend, [ aapl, spy ], 360, Resolution.DAILY) if len(multi_symbol_request) != 12: raise ValueError(f"Unexpected multi symbol dividend count: {len(multi_symbol_request)}") # continuous future mapping requests sp500 = Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME) continuous_future_open_interest_mapping = self.history(SymbolChangedEvent, sp500, datetime(2007, 1, 1), datetime(2012, 1, 1), data_mapping_mode = DataMappingMode.OPEN_INTEREST) if len(continuous_future_open_interest_mapping) != 9: raise ValueError(f"Unexpected continuous future mapping event count: {len(continuous_future_open_interest_mapping)}") continuous_future_last_trading_day_mapping = self.history(SymbolChangedEvent, sp500, datetime(2007, 1, 1), datetime(2012, 1, 1), data_mapping_mode = DataMappingMode.LAST_TRADING_DAY) if len(continuous_future_last_trading_day_mapping) != 9: raise ValueError(f"Unexpected continuous future mapping event count: {len(continuous_future_last_trading_day_mapping)}") dividend = self.history(Dividend, aapl, 360) self.debug(str(dividend)) if len(dividend) != 6: raise ValueError(f"Unexpected dividend count: {len(dividend)}") for distribution in dividend.distribution: if distribution == 0: raise ValueError(f"Unexpected distribution: {distribution}") split = self.history(Split, aapl, 360) self.debug(str(split)) if len(split) != 2: raise ValueError(f"Unexpected split count: {len(split)}") for splitfactor in split.splitfactor: if splitfactor == 0: raise ValueError(f"Unexpected splitfactor: {splitfactor}") symbol = Symbol.create("BTCUSD", SecurityType.CRYPTO_FUTURE, Market.BINANCE) margin_interest = self.history(MarginInterestRate, symbol, 24 * 3, Resolution.HOUR) self.debug(str(margin_interest)) if len(margin_interest) != 8: raise ValueError(f"Unexpected margin interest count: {len(margin_interest)}") for interestrate in margin_interest.interestrate: if interestrate == 0: raise ValueError(f"Unexpected interestrate: {interestrate}") # last trading date on 2007-05-18 delisted_symbol = Symbol.create("AAA.1", SecurityType.EQUITY, Market.USA) delistings = self.history(Delisting, delisted_symbol, datetime(2007, 5, 15), datetime(2007, 5, 21)) self.debug(str(delistings)) if len(delistings) != 2: raise ValueError(f"Unexpected delistings count: {len(delistings)}") if delistings.iloc[0].type != DelistingType.WARNING: raise ValueError(f"Unexpected delisting: {delistings.iloc[0]}") if delistings.iloc[1].type != DelistingType.DELISTED: raise ValueError(f"Unexpected delisting: {delistings.iloc[1]}") # get's remapped: # 2008-09-30 spwr -> spwra # 2011-11-17 spwra -> spwr remapped_symbol = Symbol.create("SPWR", SecurityType.EQUITY, Market.USA) symbol_changed_events = self.history(SymbolChangedEvent, remapped_symbol, datetime(2007, 1, 1), datetime(2012, 1, 1)) self.debug(str(symbol_changed_events)) if len(symbol_changed_events) != 2: raise ValueError(f"Unexpected SymbolChangedEvents count: {len(symbol_changed_events)}") first_event = symbol_changed_events.iloc[0] if first_event.oldsymbol != "SPWR" or first_event.newsymbol != "SPWRA" or symbol_changed_events.index[0][1] != datetime(2008, 9, 30): raise ValueError(f"Unexpected SymbolChangedEvents: {first_event}") second_event = symbol_changed_events.iloc[1] if second_event.newsymbol != "SPWR" or second_event.oldsymbol != "SPWRA" or symbol_changed_events.index[1][1] != datetime(2011, 11, 17): raise ValueError(f"Unexpected SymbolChangedEvents: {second_event}") 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("AAPL", 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 demonstrates how to submit orders to a Financial Advisor account group, allocation profile or a single managed account.
```python from AlgorithmImports import * class FinancialAdvisorDemoAlgorithm(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 be 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 self._symbol = self.add_equity("SPY", Resolution.SECOND).symbol # The default order properties can be set here to choose the FA settings # to be automatically used in any order submission method (such as SetHoldings, Buy, Sell and Order) # Use a default FA Account Group with an Allocation Method self.default_order_properties = InteractiveBrokersOrderProperties() # account group created manually in IB/TWS self.default_order_properties.fa_group = "TestGroupEQ" # supported allocation methods are: EqualQuantity, NetLiq, AvailableEquity, PctChange self.default_order_properties.fa_method = "EqualQuantity" # set a default FA Allocation Profile # DefaultOrderProperties = InteractiveBrokersOrderProperties() # allocation profile created manually in IB/TWS # self.default_order_properties.fa_profile = "TestProfileP" # send all orders to a single managed account # DefaultOrderProperties = InteractiveBrokersOrderProperties() # a sub-account linked to the Financial Advisor master account # self.default_order_properties.account = "DU123456" 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. if not self.portfolio.invested: # when logged into IB as a Financial Advisor, this call will use order properties # set in the DefaultOrderProperties property of QCAlgorithm 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 : Provides a regression baseline focused on updating orders
```python from AlgorithmImports import * from math import copysign class UpdateOrderRegressionAlgorithm(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(2015,1,1) #Set End Date self.set_cash(100000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data self.security = self.add_equity("SPY", Resolution.DAILY) self.last_month = -1 self.quantity = 100 self.delta_quantity = 10 self.stop_percentage = 0.025 self.stop_percentage_delta = 0.005 self.limit_percentage = 0.025 self.limit_percentage_delta = 0.005 order_type_enum = [OrderType.MARKET, OrderType.LIMIT, OrderType.STOP_MARKET, OrderType.STOP_LIMIT, OrderType.MARKET_ON_OPEN, OrderType.MARKET_ON_CLOSE, OrderType.TRAILING_STOP] self.order_types_queue = CircularQueue[OrderType](order_type_enum) self.order_types_queue.circle_completed += self.on_circle_completed self.tickets = [] def on_circle_completed(self, sender, event): '''Flip our signs when we've gone through all the order types''' self.quantity *= -1 def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' if not data.bars.contains_key("SPY"): return if self.time.month != self.last_month: # we'll submit the next type of order from the queue order_type = self.order_types_queue.dequeue() self.log("\r\n--------------MONTH: {0}:: {1}".format(self.time.strftime("%B"), order_type)) self.last_month = self.time.month self.log("ORDER TYPE:: {0}".format(order_type)) is_long = self.quantity > 0 stop_price = (1 + self.stop_percentage)*data["SPY"].high if is_long else (1 - self.stop_percentage)*data["SPY"].low limit_price = (1 - self.limit_percentage)*stop_price if is_long else (1 + self.limit_percentage)*stop_price if order_type == OrderType.LIMIT: limit_price = (1 + self.limit_percentage)*data["SPY"].high if not is_long else (1 - self.limit_percentage)*data["SPY"].low request = SubmitOrderRequest(order_type, self.security.symbol.security_type, "SPY", self.quantity, stop_price, limit_price, 0, 0.01, True, self.utc_time, str(int(order_type))) ticket = self.transactions.add_order(request) self.tickets.append(ticket) elif len(self.tickets) > 0: ticket = self.tickets[-1] if self.time.day > 8 and self.time.day < 14: if len(ticket.update_requests) == 0 and ticket.status is not OrderStatus.FILLED: self.log("TICKET:: {0}".format(ticket)) update_order_fields = UpdateOrderFields() update_order_fields.quantity = ticket.quantity + copysign(self.delta_quantity, self.quantity) update_order_fields.tag = "Change quantity: {0}".format(self.time.day) ticket.update(update_order_fields) elif self.time.day > 13 and self.time.day < 20: if len(ticket.update_requests) == 1 and ticket.status is not OrderStatus.FILLED: self.log("TICKET:: {0}".format(ticket)) update_order_fields = UpdateOrderFields() update_order_fields.limit_price = self.security.price*(1 - copysign(self.limit_percentage_delta, ticket.quantity)) update_order_fields.stop_price = self.security.price*(1 + copysign(self.stop_percentage_delta, ticket.quantity)) if ticket.order_type != OrderType.TRAILING_STOP else None update_order_fields.tag = "Change prices: {0}".format(self.time.day) ticket.update(update_order_fields) else: if len(ticket.update_requests) == 2 and ticket.status is not OrderStatus.FILLED: self.log("TICKET:: {0}".format(ticket)) ticket.cancel("{0} and is still open!".format(self.time.day)) self.log("CANCELLED:: {0}".format(ticket.cancel_request)) def on_order_event(self, orderEvent): order = self.transactions.get_order_by_id(orderEvent.order_id) ticket = self.transactions.get_order_ticket(orderEvent.order_id) #order cancelations update CanceledTime if order.status == OrderStatus.CANCELED and order.canceled_time != orderEvent.utc_time: raise ValueError("Expected canceled order CanceledTime to equal canceled order event time.") #fills update LastFillTime if (order.status == OrderStatus.FILLED or order.status == OrderStatus.PARTIALLY_FILLED) and order.last_fill_time != orderEvent.utc_time: raise ValueError("Expected filled order LastFillTime to equal fill order event time.") # check the ticket to see if the update was successfully processed if len([ur for ur in ticket.update_requests if ur.response is not None and ur.response.is_success]) > 0 and order.created_time != self.utc_time and order.last_update_time is None: raise ValueError("Expected updated order LastUpdateTime to equal submitted update order event time") if orderEvent.status == OrderStatus.FILLED: self.log("FILLED:: {0} FILL PRICE:: {1}".format(self.transactions.get_order_by_id(orderEvent.order_id), orderEvent.fill_price)) else: self.log(orderEvent.to_string()) self.log("TICKET:: {0}".format(ticket)) ```
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 for trading continuous future
```python from AlgorithmImports import * class BasicTemplateFutureRolloverAlgorithm(QCAlgorithm): ### <summary> ### Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. ### </summary> def initialize(self): self.set_start_date(2013, 10, 8) self.set_end_date(2013, 12, 10) self.set_cash(1000000) self._symbol_data_by_symbol = {} futures = [ Futures.Indices.SP_500_E_MINI ] for future in futures: # Requesting data continuous_contract = self.add_future(future, resolution = Resolution.DAILY, extended_market_hours = True, data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO, data_mapping_mode = DataMappingMode.OPEN_INTEREST, contract_depth_offset = 0 ) symbol_data = SymbolData(self, continuous_contract) self._symbol_data_by_symbol[continuous_contract.symbol] = symbol_data ### <summary> ### on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here. ### </summary> ### <param name="slice">Slice object keyed by symbol containing the stock data</param> def on_data(self, slice): for symbol, symbol_data in self._symbol_data_by_symbol.items(): # Call SymbolData.update() method to handle new data slice received symbol_data.update(slice) # Check if information in SymbolData class and new slice data are ready for trading if not symbol_data.is_ready or not slice.bars.contains_key(symbol): return ema_current_value = symbol_data.EMA.current.value if ema_current_value < symbol_data.price and not symbol_data.is_long: self.market_order(symbol_data.mapped, 1) elif ema_current_value > symbol_data.price and not symbol_data.is_short: self.market_order(symbol_data.mapped, -1) class SymbolData: ### <summary> ### Constructor to instantiate the information needed to be hold ### </summary> def __init__(self, algorithm, future): self._algorithm = algorithm self._future = future self.EMA = algorithm.ema(future.symbol, 20, Resolution.DAILY) self.price = 0 self.is_long = False self.is_short = False self.reset() @property def symbol(self): return self._future.symbol @property def mapped(self): return self._future.mapped @property def is_ready(self): return self.mapped is not None and self.EMA.is_ready ### <summary> ### Handler of new slice of data received ### </summary> def update(self, slice): if slice.symbol_changed_events.contains_key(self.symbol): changed_event = slice.symbol_changed_events[self.symbol] old_symbol = changed_event.old_symbol new_symbol = changed_event.new_symbol tag = f"Rollover - Symbol changed at {self._algorithm.time}: {old_symbol} -> {new_symbol}" quantity = self._algorithm.portfolio[old_symbol].quantity # Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract self._algorithm.liquidate(old_symbol, tag = tag) self._algorithm.market_order(new_symbol, quantity, tag = tag) self.reset() self.price = slice.bars[self.symbol].price if slice.bars.contains_key(self.symbol) else self.price self.is_long = self._algorithm.portfolio[self.mapped].is_long self.is_short = self._algorithm.portfolio[self.mapped].is_short ### <summary> ### reset RollingWindow/indicator to adapt to newly mapped contract, then warm up the RollingWindow/indicator ### </summary> def reset(self): self.EMA.reset() self._algorithm.warm_up_indicator(self.symbol, self.EMA, Resolution.DAILY) ### <summary> ### disposal method to remove consolidator/update method handler, and reset RollingWindow/indicator to free up memory and speed ### </summary> def dispose(self): self.EMA.reset() ```
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 : Continuous Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
```python from AlgorithmImports import * class ContinuousFutureRegressionAlgorithm(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, 7, 1) self.set_end_date(2014, 1, 1) self._previous_mapped_contract_symbols = [] self._last_date_log = -1 self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI, data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO, data_mapping_mode = DataMappingMode.LAST_TRADING_DAY, contract_depth_offset= 0) self._current_mapped_symbol = self._continuous_contract.symbol 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 ''' currently_mapped_security = self.securities[self._continuous_contract.mapped] if len(data.keys()) != 1: raise ValueError(f"We are getting data for more than one symbols! {','.join(data.keys())}") for changed_event in data.symbol_changed_events.values(): if changed_event.symbol == self._continuous_contract.symbol: self._previous_mapped_contract_symbols.append(self.symbol(changed_event.old_symbol)) self.log(f"SymbolChanged event: {changed_event}") if self._current_mapped_symbol == self._continuous_contract.mapped: raise ValueError(f"Continuous contract current symbol did not change! {self._continuous_contract.mapped}") if self._last_date_log != self.time.month and currently_mapped_security.has_data: self._last_date_log = self.time.month self.log(f"{self.time}- {currently_mapped_security.get_last_data()}") if self.portfolio.invested: self.liquidate() else: # This works because we set this contract as tradable, even if it's a canonical security self.buy(currently_mapped_security.symbol, 1) if self.time.month == 1 and self.time.year == 2013: response = self.history( [ self._continuous_contract.symbol ], 60 * 24 * 90) if response.empty: raise ValueError("Unexpected empty history response") self._current_mapped_symbol = self._continuous_contract.mapped def on_order_event(self, order_event): if order_event.status == OrderStatus.FILLED: self.debug("Purchased Stock: {0}".format(order_event.symbol)) def on_securities_changed(self, changes): self.debug(f"{self.time}-{changes}") def on_end_of_algorithm(self): expected_mapping_counts = 2 if len(self._previous_mapped_contract_symbols) != expected_mapping_counts: raise ValueError(f"Unexpected symbol changed events: {len(self._previous_mapped_contract_symbols)}, was expecting {expected_mapping_counts}") delisted_securities = [ [security for security in self.securities.total if security.symbol == symbol][0] for symbol in self._previous_mapped_contract_symbols ] marked_delisted_securities = [security for security in delisted_securities if security.is_delisted and not security.is_tradable] if len(marked_delisted_securities) != len(delisted_securities): raise ValueError(f"Not all delisted contracts are properly marked as delisted and non-tradable: " f"only {len(marked_delisted_securities)} are marked, was expecting {len(delisted_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 : Regression algorithm to test we can specify a custom benchmark model, and override some of its methods
```python from AlgorithmImports import * from CustomBrokerageModelRegressionAlgorithm import CustomBrokerageModel class CustomBenchmarkRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013,10,7) self.set_end_date(2013,10,11) self.set_brokerage_model(CustomBrokerageModelWithCustomBenchmark()) self.add_equity("SPY", Resolution.DAILY) self.update_request_submitted = False def on_data(self, slice): benchmark = self.benchmark.evaluate(self.time) if (self.time.day % 2 == 0) and (benchmark != 1): raise AssertionError(f"Benchmark should be 1, but was {benchmark}") if (self.time.day % 2 == 1) and (benchmark != 2): raise AssertionError(f"Benchmark should be 2, but was {benchmark}") class CustomBenchmark: def evaluate(self, time): if time.day % 2 == 0: return 1 else: return 2 class CustomBrokerageModelWithCustomBenchmark(CustomBrokerageModel): def get_benchmark(self, securities): return CustomBenchmark() ```
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 you can call the History function, what it returns, and what you can do with the returned values.
```python from AlgorithmImports import * class HistoryAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013,10, 8) #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.DAILY) IBM = self.add_data(CustomDataEquity, "IBM", Resolution.DAILY) # specifying the exchange will allow the history methods that accept a number of bars to return to work properly IBM.Exchange = EquityExchange() # we can get history in initialize to set up indicators and such self.daily_sma = SimpleMovingAverage(14) # get the last calendar year's worth of SPY data at the configured resolution (daily) trade_bar_history = self.history([self.securities["SPY"].symbol], timedelta(365)) self.assert_history_count("History<TradeBar>([\"SPY\"], timedelta(365))", trade_bar_history, 250) # get the last calendar day's worth of SPY data at the specified resolution trade_bar_history = self.history(["SPY"], timedelta(1), Resolution.MINUTE) self.assert_history_count("History([\"SPY\"], timedelta(1), Resolution.MINUTE)", trade_bar_history, 390) # get the last 14 bars of SPY at the configured resolution (daily) trade_bar_history = self.history(["SPY"], 14) self.assert_history_count("History([\"SPY\"], 14)", trade_bar_history, 14) # get the last 14 minute bars of SPY trade_bar_history = self.history(["SPY"], 14, Resolution.MINUTE) self.assert_history_count("History([\"SPY\"], 14, Resolution.MINUTE)", trade_bar_history, 14) # get the historical data from last current day to this current day in minute resolution # with Fill Forward and Extended Market options interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, True) self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, True)", interval_bar_history, 960) # get the historical data from last current day to this current day in minute resolution # with Extended Market option interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, True) self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, True)", interval_bar_history, 919) # get the historical data from last current day to this current day in minute resolution # with Fill Forward option interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, False) self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, False)", interval_bar_history, 390) # get the historical data from last current day to this current day in minute resolution interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, False) self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, False)", interval_bar_history, 390) # 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 for index, trade_bar in trade_bar_history.loc["SPY"].iterrows(): self.daily_sma.update(index, trade_bar["close"]) # get the last calendar year's worth of custom_data data at the configured resolution (daily) custom_data_history = self.history(CustomDataEquity, "IBM", timedelta(365)) self.assert_history_count("History(CustomDataEquity, \"IBM\", timedelta(365))", custom_data_history, 250) # get the last 10 bars of IBM at the configured resolution (daily) custom_data_history = self.history(CustomDataEquity, "IBM", 14) self.assert_history_count("History(CustomDataEquity, \"IBM\", 14)", custom_data_history, 14) # we can loop over the return values from these functions and we'll get Custom data # this can be used in much the same way as the trade_bar_history above self.daily_sma.reset() for index, custom_data in custom_data_history.loc["IBM"].iterrows(): self.daily_sma.update(index, custom_data["value"]) # get the last 10 bars worth of Custom data for the specified symbols at the configured resolution (daily) all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14) self.assert_history_count("History(CustomDataEquity, self.securities.keys(), 14)", all_custom_data, 14 * 2) # NOTE: Using different resolutions require that they are properly implemented in your data type. If your # custom data source has different resolutions, it would need to be implemented in the GetSource and # Reader methods properly. #custom_data_history = self.history(CustomDataEquity, "IBM", timedelta(7), Resolution.MINUTE) #custom_data_history = self.history(CustomDataEquity, "IBM", 14, Resolution.MINUTE) #all_custom_data = self.history(CustomDataEquity, timedelta(365), Resolution.MINUTE) #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14, Resolution.MINUTE) #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), timedelta(1), Resolution.MINUTE) #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14, Resolution.MINUTE) # get the last calendar year's worth of all custom_data data all_custom_data = self.history(CustomDataEquity, self.securities.keys(), timedelta(365)) self.assert_history_count("History(CustomDataEquity, self.securities.keys(), timedelta(365))", all_custom_data, 250 * 2) # we can also access the return value from the multiple symbol functions to request a single # symbol and then loop over it single_symbol_custom = all_custom_data.loc["IBM"] self.assert_history_count("all_custom_data.loc[\"IBM\"]", single_symbol_custom, 250) for custom_data in single_symbol_custom: # do something with 'IBM.custom_data_equity' custom_data data pass custom_data_spyvalues = all_custom_data.loc["IBM"]["value"] self.assert_history_count("all_custom_data.loc[\"IBM\"][\"value\"]", custom_data_spyvalues, 250) for value in custom_data_spyvalues: # do something with 'IBM.custom_data_equity' value data pass 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("SPY", 1) def assert_history_count(self, method_call, trade_bar_history, expected): count = len(trade_bar_history.index) if count != expected: raise AssertionError("{} expected {}, but received {}".format(method_call, expected, count)) class CustomDataEquity(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 = CustomDataEquity() 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]) 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 extended market hours trading.
```python from AlgorithmImports import * class ExtendedMarketTradingRegressionAlgorithm(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) #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.spy = self.add_equity("SPY", Resolution.MINUTE, Market.USA, True, 1, True) self._last_action = None 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.''' if self._last_action is not None and self._last_action.date() == self.time.date(): return spy_bar = data.bars['SPY'] if not self.in_market_hours(): self.limit_order("SPY", 10, spy_bar.low) self._last_action = self.time def on_order_event(self, order_event): self.log(str(order_event)) if self.in_market_hours(): raise AssertionError("Order processed during market hours.") def in_market_hours(self): now = self.time.time() open = time(9,30,0) close = time(16,0,0) return (open < now) and (close > now) ```
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 sector weighted portfolio.
```python from AlgorithmImports import * class SectorWeightingFrameworkAlgorithm(QCAlgorithm): '''This example algorithm defines its own custom coarse/fine fundamental selection model with sector weighted portfolio.''' def initialize(self): # Set requested data resolution self.universe_settings.resolution = Resolution.DAILY self.set_start_date(2014, 4, 2) self.set_end_date(2014, 4, 6) 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(SectorWeightingPortfolioConstructionModel()) 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): # IndustryTemplateCode of AAPL, IBM and GOOG is N, AIG is I, BAC is B. SPY have no fundamentals tickers = ["AAPL", "AIG", "IBM"] if self.time.date() < date(2014, 4, 4) 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 : Regression algorithm testing portfolio construction model control over rebalancing, specifying a custom rebalance function that returns null in some cases, see GH 4075.
```python from AlgorithmImports import * class PortfolioRebalanceOnCustomFuncRegressionAlgorithm(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.universe_settings.resolution = Resolution.DAILY # 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(2015, 1, 1) self.set_end_date(2018, 1, 1) self.settings.rebalance_portfolio_on_insight_changes = False self.settings.rebalance_portfolio_on_security_changes = False self.set_universe_selection(CustomUniverseSelectionModel("CustomUniverseSelectionModel", lambda time: [ "AAPL", "IBM", "FB", "SPY", "AIG", "BAC", "BNO" ])) self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, TimeSpan.from_minutes(20), 0.025, None)) self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(self.rebalance_function)) self.set_execution(ImmediateExecutionModel()) self.last_rebalance_time = self.start_date def rebalance_function(self, time): # for performance only run rebalance logic once a week, monday if time.weekday() != 0: return None if self.last_rebalance_time == self.start_date: # initial rebalance self.last_rebalance_time = time return time deviation = 0 count = sum(1 for security in self.securities.values() if security.invested) if count > 0: self.last_rebalance_time = time portfolio_value_per_security = self.portfolio.total_portfolio_value / count for security in self.securities.values(): if not security.invested: continue reserved_buying_power_for_current_position = (security.buying_power_model.get_reserved_buying_power_for_position( ReservedBuyingPowerForPositionParameters(security)).absolute_used_buying_power * security.buying_power_model.get_leverage(security)) # see GH issue 4107 # we sum up deviation for each security deviation += (portfolio_value_per_security - reserved_buying_power_for_current_position) / portfolio_value_per_security # if securities are deviated 1.5% from their theoretical share of TotalPortfolioValue we rebalance if deviation >= 0.015: return time return None def on_order_event(self, order_event): if order_event.status == OrderStatus.SUBMITTED: if self.utc_time != self.last_rebalance_time or self.utc_time.weekday() != 0: raise ValueError(f"{self.utc_time} {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 : Regression algorithm illustrating how to request history data for different data mapping modes.
```python from AlgorithmImports import * class HistoryWithDifferentDataMappingModeRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 6) self.set_end_date(2014, 1, 1) self._continuous_contract_symbol = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.DAILY).symbol def on_end_of_algorithm(self): history_results = [ self.history([self._continuous_contract_symbol], self.start_date, self.end_date, Resolution.DAILY, data_mapping_mode=data_mapping_mode) .droplevel(0, axis=0) .loc[self._continuous_contract_symbol] .close for data_mapping_mode in DataMappingMode ] if any(x.size != history_results[0].size for x in history_results): raise AssertionError("History results bar count did not match") # Check that close prices at each time are different for different data mapping modes for j in range(history_results[0].size): close_prices = set(history_results[i][j] for i in range(len(history_results))) if len(close_prices) != len(DataMappingMode): raise AssertionError("History results close prices should have been different for each data mapping mode at each time") ```
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="MaximumSectorExposureRiskManagementModel"/>.
```python from AlgorithmImports import * from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm from Risk.MaximumSectorExposureRiskManagementModel import MaximumSectorExposureRiskManagementModel class MaximumSectorExposureRiskManagementModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm): def initialize(self): super().initialize() # Set requested data resolution self.universe_settings.resolution = Resolution.DAILY self.set_start_date(2014, 2, 1) #Set Start Date self.set_end_date(2014, 5, 1) #Set End Date # set algorithm framework models tickers = [ "AAPL", "MSFT", "GOOG", "AIG", "BAC" ] self.set_universe_selection(FineFundamentalUniverseSelectionModel( lambda coarse: [ x.symbol for x in coarse if x.symbol.value in tickers ], lambda fine: [ x.symbol for x in fine ] )) # define risk management model such that maximum weight of a single sector be 10% # Number of of trades changed from 34 to 30 when using the MaximumSectorExposureRiskManagementModel self.set_risk_management(MaximumSectorExposureRiskManagementModel(0.1)) def on_end_of_algorithm(self): 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 : This regression algorithm tests In The Money (ITM) future option expiry for puts. We expect 3 orders from the algorithm, which are: * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1) * Option exercise, receiving short ES future contracts (sell, qty -1) * Future contract liquidation, due to impending expiry (buy qty 1) 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 FutureOptionPutITMExpiryRegressionAlgorithm(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 >= 3300.0 and x.id.option_right == OptionRight.PUT], key=lambda x: x.id.strike_price) )[0], Resolution.MINUTE).symbol self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3300.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.schedule_callback) def schedule_callback(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}") elif 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: # Expected contract is ES19M20 Call Option expiring ITM @ 3250 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"{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_future_option_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security): expected_liquidation_time_utc = datetime(2020, 6, 20, 4, 0, 0) if order_event.direction == OrderDirection.BUY and future.holdings.quantity != 0: # We expect the contract to have been liquidated immediately raise AssertionError(f"Did not liquidate existing holdings for Symbol {future.symbol}") if order_event.direction == OrderDirection.BUY and order_event.utc_time.replace(tzinfo=None) != expected_liquidation_time_utc: raise AssertionError(f"Liquidated future contract, but not at the expected time. Expected: {expected_liquidation_time_utc} - found {order_event.utc_time.replace(tzinfo=None)}") # 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.0: raise AssertionError("Option did not exercise at expected strike price (3300)") if future.holdings.quantity != -1: # Here, we expect to have some holdings in the underlying, but not in the future option anymore. raise AssertionError(f"Exercised option contract, but we have no holdings for Future {future.symbol}") if option_contract.holdings.quantity != 0: raise AssertionError(f"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}") 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(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}") 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 : A demonstration of consolidating options data into larger bars for your algorithm.
```python from AlgorithmImports import * class BasicTemplateOptionsConsolidationAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 7) self.set_end_date(2013, 10, 11) self.set_cash(1000000) # Subscribe and set our filter for the options chain option = self.add_option('SPY') # set our strike/expiry filter for this option chain # SetFilter method accepts timedelta objects or integer for days. # The following statements yield the same filtering criteria option.set_filter(-2, +2, 0, 180) # option.set_filter(-2, +2, timedelta(0), timedelta(180)) self.consolidators = dict() def on_quote_bar_consolidated(self, sender, quote_bar): self.log("OnQuoteBarConsolidated called on " + str(self.time)) self.log(str(quote_bar)) def on_trade_bar_consolidated(self, sender, trade_bar): self.log("OnTradeBarConsolidated called on " + str(self.time)) self.log(str(trade_bar)) def on_securities_changed(self, changes): for security in changes.added_securities: if security.type == SecurityType.EQUITY: trade_bar_consolidator = TradeBarConsolidator(timedelta(minutes=5)) trade_bar_consolidator.data_consolidated += self.on_trade_bar_consolidated self.subscription_manager.add_consolidator(security.symbol, trade_bar_consolidator) self.consolidators[security.symbol] = trade_bar_consolidator else: quote_bar_consolidator = QuoteBarConsolidator(timedelta(minutes=5)) quote_bar_consolidator.data_consolidated += self.on_quote_bar_consolidated self.subscription_manager.add_consolidator(security.symbol, quote_bar_consolidator) self.consolidators[security.symbol] = quote_bar_consolidator for security in changes.removed_securities: consolidator = self.consolidators.pop(security.symbol) self.subscription_manager.remove_consolidator(security.symbol, consolidator) if security.type == SecurityType.EQUITY: consolidator.data_consolidated -= self.on_trade_bar_consolidated else: consolidator.data_consolidated -= self.on_quote_bar_consolidated ```
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 brokerage model works as expected with custom data types
```python from datetime import time import os from AlgorithmImports import * class BybitCustomDataCryptoRegressionAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2022, 12, 13) self.set_end_date(2022, 12, 13) self.set_account_currency("USDT") self.set_cash(100000) self.set_brokerage_model(BrokerageName.BYBIT, AccountType.CASH) symbol = self.add_crypto("BTCUSDT").symbol self._btc_usdt = self.add_data(CustomCryptoData, symbol, Resolution.MINUTE).symbol # create two moving averages self._fast = self.ema(self._btc_usdt, 30, Resolution.MINUTE) self._slow = self.ema(self._btc_usdt, 60, Resolution.MINUTE) def on_data(self, data: Slice) -> None: if not self._slow.is_ready: return if self._fast.current.value > self._slow.current.value: if self.transactions.orders_count == 0: self.buy(self._btc_usdt, 1) else: if self.transactions.orders_count == 1: self.liquidate(self._btc_usdt) def on_order_event(self, order_event: OrderEvent) -> None: self.debug(f"{self.time} {order_event}") class CustomCryptoData(PythonData): def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource: tick_type_string = Extensions.tick_type_to_lower(config.tick_type) formatted_date = date.strftime("%Y%m%d") source = os.path.join(Globals.data_folder, "crypto", "bybit", "minute", config.symbol.value.lower(), f"{formatted_date}_{tick_type_string}.zip") return SubscriptionDataSource(source, SubscriptionTransportMedium.LOCAL_FILE, FileFormat.CSV) def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> BaseData: csv = line.split(',') data = CustomCryptoData() data.symbol = config.symbol data_datetime = datetime.combine(date.date(), time()) + timedelta(milliseconds=int(csv[0])) data.time = Extensions.convert_to(data_datetime, config.data_time_zone, config.exchange_time_zone) data.end_time = data.time + timedelta(minutes=1) data["Open"] = float(csv[1]) data["High"] = float(csv[2]) data["Low"] = float(csv[3]) data["Close"] = float(csv[4]) data["Volume"] = float(csv[5]) data.value = float(csv[4]) return 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 base algorithm demonstrates how to use OptionStrategies helper class to batch send orders for common strategies.
```python from AlgorithmImports import * from QuantConnect.Securities.Positions import IPositionGroup class OptionStrategyFactoryMethodsBaseAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2015, 12, 24) self.set_end_date(2015, 12, 24) self.set_cash(1000000) option = self.add_option("GOOG") self._option_symbol = option.symbol option.set_filter(-2, +2, 0, 180) self.set_benchmark("GOOG") def on_data(self, slice): if not self.portfolio.invested: chain = slice.option_chains.get(self._option_symbol) if chain is not None: self.trade_strategy(chain, self._option_symbol) else: # Verify that the strategy was traded position_group = list(self.portfolio.positions.groups)[0] buying_power_model = position_group.buying_power_model if not isinstance(buying_power_model, OptionStrategyPositionGroupBuyingPowerModel): raise AssertionError("Expected position group buying power model type: OptionStrategyPositionGroupBuyingPowerModel. " f"Actual: {type(position_group.buying_power_model).__name__}") self.assert_strategy_position_group(position_group, self._option_symbol) # Now we should be able to close the position self.liquidate_strategy() # We can quit now, no more testing required self.quit() def on_end_of_algorithm(self): if self.portfolio.invested: raise AssertionError("Expected no holdings at end of algorithm") orders_count = len(list(self.transactions.get_orders(lambda order: order.status == OrderStatus.FILLED))) if orders_count != self.expected_orders_count(): raise AssertionError(f"Expected {self.expected_orders_count()} orders to have been submitted and filled, " f"half for buying the strategy and the other half for the liquidation. Actual {orders_count}") def expected_orders_count(self) -> int: raise NotImplementedError("ExpectedOrdersCount method is not implemented") def trade_strategy(self, chain: OptionChain, option_symbol: Symbol) -> None: raise NotImplementedError("TradeStrategy method is not implemented") def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol) -> None: raise NotImplementedError("AssertStrategyPositionGroup method is not implemented") def liquidate_strategy(self) -> None: raise NotImplementedError("LiquidateStrategy method is not implemented") ```
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 shows how to import and use Tiingo daily prices data.
```python from AlgorithmImports import * from QuantConnect.Data.Custom.Tiingo import TiingoPrice class TiingoPriceAlgorithm(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(2017, 1, 1) self.set_end_date(2017, 12, 31) self.set_cash(100000) # Set your Tiingo API Token here Tiingo.set_auth_code("my-tiingo-api-token") self._equity = self.add_equity("AAPL").symbol self._aapl = self.add_data(TiingoPrice, self._equity, Resolution.DAILY).symbol self._ema_fast = self.ema(self._equity, 5) self._ema_slow = self.ema(self._equity, 10) def on_data(self, slice): # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. if not slice.contains_key(self._equity): return # Extract Tiingo data from the slice row = slice[self._equity] if not row: return if self._ema_fast.is_ready and self._ema_slow.is_ready: self.log(f"{self.time} - {row.symbol.value} - {row.close} {row.value} {row.price} - EmaFast:{self._ema_fast} - EmaSlow:{self._ema_slow}") # Simple EMA cross if not self.portfolio.invested and self._ema_fast > self._ema_slow: self.set_holdings(self._equity, 1) elif self.portfolio.invested and self._ema_fast < self._ema_slow: self.liquidate(self._equity) ```
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 GH issue #5921. Asserting a security can be warmup correctly on initialize
```python from AlgorithmImports import * class SecuritySeederRegressionAlgorithm(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, 8) self.set_end_date(2013,10,10) self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices))) 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 ''' if not self.portfolio.invested: self.set_holdings("SPY", 1) def on_securities_changed(self, changes): for added_security in changes.added_securities: if not added_security.has_data \ or added_security.ask_price == 0 \ or added_security.bid_price == 0 \ or added_security.bid_size == 0 \ or added_security.ask_size == 0 \ or added_security.price == 0 \ or added_security.volume == 0 \ or added_security.high == 0 \ or added_security.low == 0 \ or added_security.open == 0 \ or added_security.close == 0: raise ValueError(f"Security {added_security.symbol} was not warmed up!") ```
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 payments for cash dividends in backtesting. When data normalization mode is set to "Raw" the dividends are paid as cash directly into your portfolio.
```python from AlgorithmImports import * class DividendAlgorithm(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(1998,1,1) #Set Start Date self.set_end_date(2006,1,21) #Set End Date self.set_cash(100000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data equity = self.add_equity("MSFT", Resolution.DAILY) equity.set_data_normalization_mode(DataNormalizationMode.RAW) # this will use the Tradier Brokerage open order split behavior # forward split will modify open order to maintain order value # reverse split open orders will be cancelled self.set_brokerage_model(BrokerageName.TRADIER_BROKERAGE) def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' bar = data["MSFT"] if self.transactions.orders_count == 0: self.set_holdings("MSFT", .5) # place some orders that won't fill, when the split comes in they'll get modified to reflect the split quantity = self.calculate_order_quantity("MSFT", .25) self.debug(f"Purchased Stock: {bar.price}") self.stop_market_order("MSFT", -quantity, bar.low/2) self.limit_order("MSFT", -quantity, bar.high*2) if data.dividends.contains_key("MSFT"): dividend = data.dividends["MSFT"] self.log(f"{self.time} >> DIVIDEND >> {dividend.symbol} - {dividend.distribution} - {self.portfolio.cash} - {self.portfolio['MSFT'].price}") if data.splits.contains_key("MSFT"): split = data.splits["MSFT"] self.log(f"{self.time} >> SPLIT >> {split.symbol} - {split.split_factor} - {self.portfolio.cash} - {self.portfolio['MSFT'].price}") def on_order_event(self, order_event): # orders get adjusted based on split events to maintain order value order = self.transactions.get_order_by_id(order_event.order_id) self.log(f"{self.time} >> ORDER >> {order}") ```
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 calls. We expect 2 orders from the algorithm, which are: * Initial entry, buy SPX Call Option (expiring OTM) - contract expires worthless, not exercised, so never opened a position in the underlying * Liquidation of worthless SPX call option (expiring OTM) 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 IndexOptionCallOTMExpiryRegressionAlgorithm(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 call expiring OTM, 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("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM") 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: 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 not "OTM" 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") ### <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 checks if all the option chain data coming to the algo is consistent with current securities manager state
```python from AlgorithmImports import * class OptionChainConsistencyRegressionAlgorithm(QCAlgorithm): underlying_ticker = "GOOG" def initialize(self): self.set_cash(10000) self.set_start_date(2015,12,24) self.set_end_date(2015,12,24) self.equity = self.add_equity(self.underlying_ticker) self.option = self.add_option(self.underlying_ticker) # set our strike/expiry filter for this option chain self.option.set_filter(self.universe_func) self.set_benchmark(self.equity.symbol) def on_data(self, slice): if self.portfolio.invested: return for kvp in slice.option_chains: chain = kvp.value for o in chain: if not self.securities.contains_key(o.symbol): self.log("Inconsistency found: option chains contains contract {0} that is not available in securities manager and not available for trading".format(o.symbol.value)) contracts = filter(lambda x: x.expiry.date() == self.time.date() and x.strike < chain.underlying.price and x.right == OptionRight.CALL, chain) sorted_contracts = sorted(contracts, key = lambda x: x.strike, reverse = True) if len(sorted_contracts) > 2: self.market_order(sorted_contracts[2].symbol, 1) self.market_on_close_order(sorted_contracts[2].symbol, -1) # 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(10)) 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 Channel algorithm simply initializes the date range and cash
```python from AlgorithmImports import * class RegressionChannelAlgorithm(QCAlgorithm): def initialize(self): self.set_cash(100000) self.set_start_date(2009,1,1) self.set_end_date(2015,1,1) equity = self.add_equity("SPY", Resolution.MINUTE) self._spy = equity.symbol self._holdings = equity.holdings self._rc = self.rc(self._spy, 30, 2, Resolution.DAILY) stock_plot = Chart("Trade Plot") stock_plot.add_series(Series("Buy", SeriesType.SCATTER, 0)) stock_plot.add_series(Series("Sell", SeriesType.SCATTER, 0)) stock_plot.add_series(Series("UpperChannel", SeriesType.LINE, 0)) stock_plot.add_series(Series("LowerChannel", SeriesType.LINE, 0)) stock_plot.add_series(Series("Regression", SeriesType.LINE, 0)) self.add_chart(stock_plot) def on_data(self, data): if (not self._rc.is_ready) or (not data.contains_key(self._spy)): return if data[self._spy] is None: return value = data[self._spy].value if self._holdings.quantity <= 0 and value < self._rc.lower_channel.current.value: self.set_holdings(self._spy, 1) self.plot("Trade Plot", "Buy", value) if self._holdings.quantity >= 0 and value > self._rc.upper_channel.current.value: self.set_holdings(self._spy, -1) self.plot("Trade Plot", "Sell", value) def on_end_of_day(self, symbol): self.plot("Trade Plot", "UpperChannel", self._rc.upper_channel.current.value) self.plot("Trade Plot", "LowerChannel", self._rc.lower_channel.current.value) self.plot("Trade Plot", "Regression", self._rc.linear_regression.current.value) ```
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 : his algorithm sends a list of portfolio targets to custom endpoint
```python from AlgorithmImports import * class CustomSignalExportDemonstrationAlgorithm(QCAlgorithm): def initialize(self) -> None: ''' 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 # Our custom signal export accepts all asset types self.add_equity("SPY", Resolution.SECOND) self.add_crypto("BTCUSD", Resolution.SECOND) self.add_forex("EURUSD", Resolution.SECOND) self.add_future_contract(Symbol.create_future("ES", Market.CME, datetime(2023, 12, 15))) self.add_option_contract(Symbol.create_option("SPY", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 130, datetime(2023, 9, 1))) # Set CustomSignalExport signal export provider. self.signal_export.add_signal_export_provider(CustomSignalExport()) def on_data(self, data: Slice) -> None: '''Buy and hold EURUSD and SPY''' for ticker in [ "SPY", "EURUSD", "BTCUSD" ]: if not self.portfolio[ticker].invested and self.securities[ticker].has_data: self.set_holdings(ticker, 0.5) from requests import post class CustomSignalExport: def send(self, parameters: SignalExportTargetParameters) -> bool: targets = [PortfolioTarget.percent(parameters.algorithm, x.symbol, x.quantity) for x in parameters.targets] data = [ {'symbol' : x.symbol.value, 'quantity': x.quantity} for x in targets ] response = post("http://localhost:5000/", json = data) result = response.json() success = result.get('success', False) parameters.algorithm.log(f"Send #{len(parameters.targets)} targets. Success: {success}") return success def dispose(self): pass ''' # To test the algorithm, you can create a simple Python Flask application (app.py) and run flask # $ flask --app app run # app.py: from flask import Flask, request, jsonify from json import loads app = Flask(__name__) @app.post('/') def handle_positions(): result = loads(request.data) print(result) return jsonify({'success': True,'message': f'{len(result)} positions received'}) if __name__ == '__main__': app.run(debug=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 : In this algorithm we submit/update/cancel each order type
```python from AlgorithmImports import * class OrderTicketDemoAlgorithm(QCAlgorithm): '''In this algorithm we submit/update/cancel each order type''' 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 equity = self.add_equity("SPY") self.spy = equity.symbol self.__open_market_on_open_orders = [] self.__open_market_on_close_orders = [] self.__open_limit_orders = [] self.__open_stop_market_orders = [] self.__open_stop_limit_orders = [] self.__open_trailing_stop_orders = [] def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' # MARKET ORDERS self.market_orders() # LIMIT ORDERS self.limit_orders() # STOP MARKET ORDERS self.stop_market_orders() # STOP LIMIT ORDERS self.stop_limit_orders() # TRAILING STOP ORDERS self.trailing_stop_orders() # MARKET ON OPEN ORDERS self.market_on_open_orders() # MARKET ON CLOSE ORDERS self.market_on_close_orders() def market_orders(self): ''' MarketOrders are the only orders that are processed synchronously by default, so they'll fill by the next line of code. This behavior equally applies to live mode. You can opt out of this behavior by specifying the 'asynchronous' parameter as True.''' if self.time_is(7, 9, 31): self.log("Submitting MarketOrder") # submit a market order to buy 10 shares, this function returns an OrderTicket object # we submit the order with asynchronous = False, so it block until it is filled new_ticket = self.market_order(self.spy, 10, asynchronous = False) if new_ticket.status != OrderStatus.FILLED: self.log("Synchronous market order was not filled synchronously!") self.quit() # we can also submit the ticket asynchronously. In a backtest, we'll still perform the fill # before the next time events for your algorithm. here we'll submit the order asynchronously # and try to cancel it, sometimes it will, sometimes it will be filled first. new_ticket = self.market_order(self.spy, 10, asynchronous = True) response = new_ticket.cancel("Attempt to cancel async order") if response.is_success: self.log("Successfully canceled async market order: {0}".format(new_ticket.order_id)) else: self.log("Unable to cancel async market order: {0}".format(response.error_code)) def limit_orders(self): '''LimitOrders are always processed asynchronously. Limit orders are used to set 'good' entry points for an order. For example, you may wish to go long a stock, but want a good price, so can place a LimitOrder to buy with a limit price below the current market price. Likewise the opposite is True when selling, you can place a LimitOrder to sell with a limit price above the current market price to get a better sale price. You can submit requests to update or cancel the LimitOrder at any time. The 'LimitPrice' for an order can be retrieved from the ticket using the OrderTicket.get(OrderField) method, for example: Code: current_limit_price = order_ticket.get(OrderField.LIMIT_PRICE)''' if self.time_is(7, 12, 0): self.log("Submitting LimitOrder") # submit a limit order to buy 10 shares at .1% below the bar's close close = self.securities[self.spy.value].close new_ticket = self.limit_order(self.spy, 10, close * .999) self.__open_limit_orders.append(new_ticket) # submit another limit order to sell 10 shares at .1% above the bar's close new_ticket = self.limit_order(self.spy, -10, close * 1.001) self.__open_limit_orders.append(new_ticket) # when we submitted new limit orders we placed them into this list, # so while there's two entries they're still open and need processing if len(self.__open_limit_orders) == 2: open_orders = self.__open_limit_orders # check if either is filled and cancel the other long_order = open_orders[0] short_order = open_orders[1] if self.check_pair_orders_for_fills(long_order, short_order): self.__open_limit_orders = [] return # if neither order has filled, bring in the limits by a penny new_long_limit = long_order.get(OrderField.LIMIT_PRICE) + 0.01 new_short_limit = short_order.get(OrderField.LIMIT_PRICE) - 0.01 self.log("Updating limits - Long: {0:.2f} Short: {1:.2f}".format(new_long_limit, new_short_limit)) update_order_fields = UpdateOrderFields() update_order_fields.limit_price = new_long_limit update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1) long_order.update(update_order_fields) update_order_fields = UpdateOrderFields() update_order_fields.limit_price = new_short_limit update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1) short_order.update(update_order_fields) def stop_market_orders(self): '''StopMarketOrders work in the opposite way that limit orders do. When placing a long trade, the stop price must be above current market price. In this way it's a 'stop loss' for a short trade. When placing a short trade, the stop price must be below current market price. In this way it's a 'stop loss' for a long trade. You can submit requests to update or cancel the StopMarketOrder at any time. The 'StopPrice' for an order can be retrieved from the ticket using the OrderTicket.get(OrderField) method, for example: Code: current_stop_price = order_ticket.get(OrderField.STOP_PRICE)''' if self.time_is(7, 12 + 4, 0): self.log("Submitting StopMarketOrder") # a long stop is triggered when the price rises above the value # so we'll set a long stop .25% above the current bar's close close = self.securities[self.spy.value].close new_ticket = self.stop_market_order(self.spy, 10, close * 1.0025) self.__open_stop_market_orders.append(new_ticket) # a short stop is triggered when the price falls below the value # so we'll set a short stop .25% below the current bar's close new_ticket = self.stop_market_order(self.spy, -10, close * .9975) self.__open_stop_market_orders.append(new_ticket) # when we submitted new stop market orders we placed them into this list, # so while there's two entries they're still open and need processing if len(self.__open_stop_market_orders) == 2: # check if either is filled and cancel the other long_order = self.__open_stop_market_orders[0] short_order = self.__open_stop_market_orders[1] if self.check_pair_orders_for_fills(long_order, short_order): self.__open_stop_market_orders = [] return # if neither order has filled, bring in the stops by a penny new_long_stop = long_order.get(OrderField.STOP_PRICE) - 0.01 new_short_stop = short_order.get(OrderField.STOP_PRICE) + 0.01 self.log("Updating stops - Long: {0:.2f} Short: {1:.2f}".format(new_long_stop, new_short_stop)) update_order_fields = UpdateOrderFields() update_order_fields.stop_price = new_long_stop update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1) long_order.update(update_order_fields) update_order_fields = UpdateOrderFields() update_order_fields.stop_price = new_short_stop update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1) short_order.update(update_order_fields) self.log("Updated price - Long: {0} Short: {1}".format(long_order.get(OrderField.STOP_PRICE), short_order.get(OrderField.STOP_PRICE))) def stop_limit_orders(self): '''StopLimitOrders work as a combined stop and limit order. First, the price must pass the stop price in the same way a StopMarketOrder works, but then we're also guaranteed a fill price at least as good as the limit price. This order type can be beneficial in gap down scenarios where a StopMarketOrder would have triggered and given the not as beneficial gapped down price, whereas the StopLimitOrder could protect you from getting the gapped down price through prudent placement of the limit price. You can submit requests to update or cancel the StopLimitOrder at any time. The 'StopPrice' or 'LimitPrice' for an order can be retrieved from the ticket using the OrderTicket.get(OrderField) method, for example: Code: current_stop_price = order_ticket.get(OrderField.STOP_PRICE) current_limit_price = order_ticket.get(OrderField.LIMIT_PRICE)''' if self.time_is(8, 12, 1): self.log("Submitting StopLimitOrder") # a long stop is triggered when the price rises above the # value so we'll set a long stop .25% above the current bar's # close now we'll also be setting a limit, this means we are # guaranteed to get at least the limit price for our fills, # so make the limit price a little higher than the stop price close = self.securities[self.spy.value].close new_ticket = self.stop_limit_order(self.spy, 10, close * 1.001, close - 0.03) self.__open_stop_limit_orders.append(new_ticket) # a short stop is triggered when the price falls below the # value so we'll set a short stop .25% below the current bar's # close now we'll also be setting a limit, this means we are # guaranteed to get at least the limit price for our fills, # so make the limit price a little softer than the stop price new_ticket = self.stop_limit_order(self.spy, -10, close * .999, close + 0.03) self.__open_stop_limit_orders.append(new_ticket) # when we submitted new stop limit orders we placed them into this list, # so while there's two entries they're still open and need processing if len(self.__open_stop_limit_orders) == 2: long_order = self.__open_stop_limit_orders[0] short_order = self.__open_stop_limit_orders[1] if self.check_pair_orders_for_fills(long_order, short_order): self.__open_stop_limit_orders = [] return # if neither order has filled, bring in the stops/limits in by a penny new_long_stop = long_order.get(OrderField.STOP_PRICE) - 0.01 new_long_limit = long_order.get(OrderField.LIMIT_PRICE) + 0.01 new_short_stop = short_order.get(OrderField.STOP_PRICE) + 0.01 new_short_limit = short_order.get(OrderField.LIMIT_PRICE) - 0.01 self.log("Updating stops - Long: {0:.2f} Short: {1:.2f}".format(new_long_stop, new_short_stop)) self.log("Updating limits - Long: {0:.2f} Short: {1:.2f}".format(new_long_limit, new_short_limit)) update_order_fields = UpdateOrderFields() update_order_fields.stop_price = new_long_stop update_order_fields.limit_price = new_long_limit update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1) long_order.update(update_order_fields) update_order_fields = UpdateOrderFields() update_order_fields.stop_price = new_short_stop update_order_fields.limit_price = new_short_limit update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1) short_order.update(update_order_fields) def trailing_stop_orders(self): '''TrailingStopOrders work the same way as StopMarketOrders, except their stop price is adjusted to a certain amount, keeping it a certain fixed distance from/to the market price, depending on the order direction, which allows to preserve profits and protecting against losses. The stop price can be accessed just as with StopMarketOrders, and the trailing amount can be accessed with the OrderTicket.get(OrderField), for example: Code: current_trailing_amount = order_ticket.get(OrderField.STOP_PRICE) trailing_as_percentage = order_ticket.get[bool](OrderField.TRAILING_AS_PERCENTAGE)''' if self.time_is(7, 12, 0): self.log("Submitting TrailingStopOrder") # a long stop is triggered when the price rises above the # value so we'll set a long stop .25% above the current bar's close = self.securities[self.spy.value].close stop_price = close * 1.0025 new_ticket = self.trailing_stop_order(self.spy, 10, stop_price, trailing_amount=0.0025, trailing_as_percentage=True) self.__open_trailing_stop_orders.append(new_ticket) # a short stop is triggered when the price falls below the # value so we'll set a short stop .25% below the current bar's stop_price = close * .9975 new_ticket = self.trailing_stop_order(self.spy, -10, stop_price, trailing_amount=0.0025, trailing_as_percentage=True) self.__open_trailing_stop_orders.append(new_ticket) # when we submitted new stop market orders we placed them into this list, # so while there's two entries they're still open and need processing elif len(self.__open_trailing_stop_orders) == 2: long_order = self.__open_trailing_stop_orders[0] short_order = self.__open_trailing_stop_orders[1] if self.check_pair_orders_for_fills(long_order, short_order): self.__open_trailing_stop_orders = [] return # if neither order has filled in the last 5 minutes, bring in the trailing percentage by 0.01% if ((self.utc_time - long_order.time).total_seconds() / 60) % 5 != 0: return long_trailing_percentage = long_order.get(OrderField.TRAILING_AMOUNT) new_long_trailing_percentage = max(long_trailing_percentage - 0.0001, 0.0001) short_trailing_percentage = short_order.get(OrderField.TRAILING_AMOUNT) new_short_trailing_percentage = max(short_trailing_percentage - 0.0001, 0.0001) self.log("Updating trailing percentages - Long: {0:.3f} Short: {1:.3f}".format(new_long_trailing_percentage, new_short_trailing_percentage)) update_order_fields = UpdateOrderFields() # we could change the quantity, but need to specify it #Quantity = update_order_fields.trailing_amount = new_long_trailing_percentage update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1) long_order.update(update_order_fields) update_order_fields = UpdateOrderFields() update_order_fields.trailing_amount = new_short_trailing_percentage update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1) short_order.update(update_order_fields) def market_on_close_orders(self): '''MarketOnCloseOrders are always executed at the next market's closing price. The only properties that can be updated are the quantity and order tag properties.''' if self.time_is(9, 12, 0): self.log("Submitting MarketOnCloseOrder") # open a new position or triple our existing position qty = self.portfolio[self.spy.value].quantity qty = 100 if qty == 0 else 2*qty new_ticket = self.market_on_close_order(self.spy, qty) self.__open_market_on_close_orders.append(new_ticket) if len(self.__open_market_on_close_orders) == 1 and self.time.minute == 59: ticket = self.__open_market_on_close_orders[0] # check for fills if ticket.status == OrderStatus.FILLED: self.__open_market_on_close_orders = [] return quantity = ticket.quantity + 1 self.log("Updating quantity - New Quantity: {0}".format(quantity)) # we can update the quantity and tag update_order_fields = UpdateOrderFields() update_order_fields.quantity = quantity update_order_fields.tag = "Update #{0}".format(len(ticket.update_requests) + 1) ticket.update(update_order_fields) if self.time_is(self.end_date.day, 12 + 3, 45): self.log("Submitting MarketOnCloseOrder to liquidate end of algorithm") self.market_on_close_order(self.spy, -self.portfolio[self.spy.value].quantity, tag="Liquidate end of algorithm") def market_on_open_orders(self): '''MarketOnOpenOrders are always executed at the next market's opening price. The only properties that can be updated are the quantity and order tag properties.''' if self.time_is(8, 14 + 2, 0): self.log("Submitting MarketOnOpenOrder") # its EOD, let's submit a market on open order to short even more! new_ticket = self.market_on_open_order(self.spy, 50) self.__open_market_on_open_orders.append(new_ticket) if len(self.__open_market_on_open_orders) == 1 and self.time.minute == 59: ticket = self.__open_market_on_open_orders[0] # check for fills if ticket.status == OrderStatus.FILLED: self.__open_market_on_open_orders = [] return quantity = ticket.quantity + 1 self.log("Updating quantity - New Quantity: {0}".format(quantity)) # we can update the quantity and tag update_order_fields = UpdateOrderFields() update_order_fields.quantity = quantity update_order_fields.tag = "Update #{0}".format(len(ticket.update_requests) + 1) ticket.update(update_order_fields) def on_order_event(self, order_event): order = self.transactions.get_order_by_id(order_event.order_id) self.log("{0}: {1}: {2}".format(self.time, order.type, order_event)) 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") if (type(order) is LimitOrder and order_event.limit_price == 0 or type(order) is StopLimitOrder and order_event.limit_price == 0): raise AssertionError("OrderEvent LimitPrice is Not expected to be 0 for LimitOrder and StopLimitOrder") if type(order) is StopMarketOrder and order_event.stop_price == 0: raise AssertionError("OrderEvent StopPrice is Not expected to be 0 for StopMarketOrder") # We can access the order ticket from the order event if order_event.ticket is None: raise AssertionError("OrderEvent Ticket was not set") if order_event.order_id != order_event.ticket.order_id: raise AssertionError("OrderEvent.ORDER_ID and order_event.ticket.order_id do not match") def check_pair_orders_for_fills(self, long_order, short_order): if long_order.status == OrderStatus.FILLED: self.log("{0}: Cancelling short order, long order is filled.".format(short_order.order_type)) short_order.cancel("Long filled.") return True if short_order.status == OrderStatus.FILLED: self.log("{0}: Cancelling long order, short order is filled.".format(long_order.order_type)) long_order.cancel("Short filled") return True return False def time_is(self, day, hour, minute): return self.time.day == day and self.time.hour == hour and self.time.minute == minute def on_end_of_algorithm(self): basic_order_ticket_filter = lambda x: x.symbol == self.spy filled_orders = self.transactions.get_orders(lambda x: x.status == OrderStatus.FILLED) order_tickets = self.transactions.get_order_tickets(basic_order_ticket_filter) open_orders = self.transactions.get_open_orders(lambda x: x.symbol == self.spy) open_order_tickets = self.transactions.get_open_order_tickets(basic_order_ticket_filter) remaining_open_orders = self.transactions.get_open_orders_remaining_quantity(basic_order_ticket_filter) # The type returned by self.transactions.get_orders() is iterable and not a list # that's why we use sum() to get the size of the iterable object type filled_orders_size = sum(1 for order in filled_orders) order_tickets_size = sum(1 for ticket in order_tickets) open_order_tickets_size = sum(1 for ticket in open_order_tickets) assert(filled_orders_size == 9 and order_tickets_size == 12), "There were expected 9 filled orders and 12 order tickets" assert(not (len(open_orders) or open_order_tickets_size)), "No open orders or tickets were expected" assert(not remaining_open_orders), "No remaining quantity to be filled from open orders was expected" spy_open_orders = self.transactions.get_open_orders(self.spy) spy_open_order_tickets = self.transactions.get_open_order_tickets(self.spy) spy_open_order_tickets_size = sum(1 for tickets in spy_open_order_tickets) spy_open_orders_remaining_quantity = self.transactions.get_open_orders_remaining_quantity(self.spy) assert(not (len(spy_open_orders) or spy_open_order_tickets_size)), "No open orders or tickets were expected" assert(not spy_open_orders_remaining_quantity), "No remaining quantity to be filled from open orders was expected" default_orders = self.transactions.get_orders() default_order_tickets = self.transactions.get_order_tickets() default_open_orders = self.transactions.get_open_orders() default_open_order_tickets = self.transactions.get_open_order_tickets() default_open_orders_remaining = self.transactions.get_open_orders_remaining_quantity() default_orders_size = sum(1 for order in default_orders) default_order_tickets_size = sum(1 for ticket in default_order_tickets) default_open_order_tickets_size = sum(1 for ticket in default_open_order_tickets) assert(default_orders_size == 12 and default_order_tickets_size == 12), "There were expected 12 orders and 12 order tickets" assert(not (len(default_open_orders) or default_open_order_tickets_size)), "No open orders or tickets were expected" assert(not default_open_orders_remaining), "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 test algorithm for scheduled universe selection GH 3890
```python from AlgorithmImports import * class FundamentalCustomSelectionTimeRegressionAlgorithm(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._month_start_selection = 0 self._month_end_selection = 0 self._specific_date_selection = 0 self._symbol = Symbol.create("SPY", SecurityType.EQUITY, Market.USA) self.set_start_date(2014, 3, 25) self.set_end_date(2014, 5, 10) self.universe_settings.resolution = Resolution.DAILY # Test use case A self.add_universe(self.date_rules.month_start(), self.selection_function__month_start) # Test use case B other_settings = UniverseSettings(self.universe_settings) other_settings.schedule.on(self.date_rules.month_end()) self.add_universe(FundamentalUniverse.usa(self.selection_function__month_end, other_settings)) # Test use case C self.universe_settings.schedule.on(self.date_rules.on(datetime(2014, 5, 9))) self.add_universe(FundamentalUniverse.usa(self.selection_function__specific_date)) def selection_function__specific_date(self, coarse): self._specific_date_selection += 1 if self.time != datetime(2014, 5, 9): raise ValueError("SelectionFunction_SpecificDate unexpected selection: " + str(self.time)) return [ self._symbol ] def selection_function__month_start(self, coarse): self._month_start_selection += 1 if self._month_start_selection == 1: if self.time != self.start_date: raise ValueError("Month Start Unexpected initial selection: " + str(self.time)) elif self.time != datetime(2014, 4, 1) and self.time != datetime(2014, 5, 1): raise ValueError("Month Start unexpected selection: " + str(self.time)) return [ self._symbol ] def selection_function__month_end(self, coarse): self._month_end_selection += 1 if self._month_end_selection == 1: if self.time != self.start_date: raise ValueError("Month End unexpected initial selection: " + str(self.time)) elif self.time != datetime(2014, 3, 31) and self.time != datetime(2014, 4, 30): raise ValueError("Month End unexpected selection: " + str(self.time)) return [ self._symbol ] 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(self._symbol, 1) def on_end_of_algorithm(self): if self._month_end_selection != 3: raise ValueError("Month End unexpected selection count: " + str(self._month_end_selection)) if self._month_start_selection != 3: raise ValueError("Month Start unexpected selection count: " + str(self._month_start_selection)) if self._specific_date_selection != 1: raise ValueError("Specific date unexpected selection count: " + str(self._month_start_selection)) ```
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 India Index Algorithm uses framework components to define the algorithm.
```python from AlgorithmImports import * class BasicTemplateIndiaIndexAlgorithm(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, 1) #Set Start Date self.set_end_date(2019, 1, 5) #Set End Date self.set_cash(1000000) #Set Strategy Cash # Use indicator for signal; but it cannot be traded self.nifty = self.add_index("NIFTY50", Resolution.MINUTE, Market.INDIA).symbol # Trade Index based ETF self.nifty_etf = self.add_equity("JUNIORBEES", Resolution.MINUTE, Market.INDIA).symbol # Set Order Properties as per the requirements for order placement self.default_order_properties = IndiaOrderProperties(Exchange.NSE) # Define indicator self._ema_slow = self.ema(self.nifty, 80) self._ema_fast = self.ema(self.nifty, 200) self.debug("numpy test >>> print numpy.pi: " + str(np.pi)) 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 data.bars.contains_key(self.nifty) or not data.bars.contains_key(self.nifty_etf): return if not self._ema_slow.is_ready: return if self._ema_fast > self._ema_slow: if not self.portfolio.invested: self.market_ticket = self.market_order(self.nifty_etf, 1) else: self.liquidate() def on_end_of_algorithm(self): if self.portfolio[self.nifty].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 : Regression algorithm for asserting that tick history that includes multiple tick types (trade, quote) is correctly converted to a pandas dataframe without raising exceptions. The main exception in this case was a "non-unique multi-index" error due to trades adn quote ticks with duplicated timestamps.
```python from AlgorithmImports import * class PandasDataFrameFromMultipleTickTypeTickHistoryRegressionAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2013, 10, 8) self.set_end_date(2013, 10, 8) spy = self.add_equity("SPY", Resolution.MINUTE).symbol subscriptions = [x for x in self.subscription_manager.subscriptions if x.symbol == spy] if len(subscriptions) != 2: raise AssertionError(f"Expected 2 subscriptions, but found {len(subscriptions)}") history = pd.DataFrame() try: history = self.history(Tick, spy, timedelta(days=1), Resolution.TICK) except Exception as e: raise AssertionError(f"History call failed: {e}") if history.shape[0] == 0: raise AssertionError("SPY tick history is empty") if not np.array_equal(history.columns.to_numpy(), ['askprice', 'asksize', 'bidprice', 'bidsize', 'exchange', 'lastprice', 'quantity']): raise AssertionError("Unexpected columns in SPY tick history") 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 : In this example we look at the canonical 15/30 day moving average cross. This algorithm will go long when the 15 crosses above the 30 and will liquidate when the 15 crosses back below the 30.
```python from AlgorithmImports import * class MovingAverageCrossAlgorithm(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(2009, 1, 1) #Set Start Date self.set_end_date(2015, 1, 1) #Set End Date self.set_cash(100000) #Set Strategy Cash # Find more symbols here: http://quantconnect.com/data self.add_equity("SPY") # create a 15 day exponential moving average self.fast = self.ema("SPY", 15, Resolution.DAILY) # create a 30 day exponential moving average self.slow = self.ema("SPY", 30, Resolution.DAILY) self.previous = None def on_data(self, data): '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.''' # a couple things to notice in this method: # 1. We never need to 'update' our indicators with the data, the engine takes care of this for us # 2. We can use indicators directly in math expressions # 3. We can easily plot many indicators at the same time # wait for our slow ema to fully initialize if not self.slow.is_ready: return # only once per day if self.previous is not None and self.previous.date() == self.time.date(): return # define a small tolerance on our checks to avoid bouncing tolerance = 0.00015 holdings = self.portfolio["SPY"].quantity # we only want to go long if we're currently short or flat if holdings <= 0: # if the fast is greater than the slow, we'll go long if self.fast.current.value > self.slow.current.value *(1 + tolerance): self.log("BUY >> {0}".format(self.securities["SPY"].price)) self.set_holdings("SPY", 1.0) # we only want to liquidate if we're currently long # if the fast is less than the slow we'll liquidate our long if holdings > 0 and self.fast.current.value < self.slow.current.value: self.log("SELL >> {0}".format(self.securities["SPY"].price)) self.liquidate("SPY") self.previous = self.time ```