Dataset Viewer
Auto-converted to Parquet Duplicate
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) ```
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
8