diff --git "a/lean_dataset.jsonl" "b/lean_dataset.jsonl" new file mode 100644--- /dev/null +++ "b/lean_dataset.jsonl" @@ -0,0 +1,373 @@ +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm illustrating how to manually set market hours and symbol properties database entries to be picked up by the algorithm's securities.\nThis specific case illustrates how to do it for CFDs to match InteractiveBrokers brokerage, which has different market hours\ndepending on the CFD underlying asset.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nimport Newtonsoft.Json as json\n\nclass ManuallySetMarketHoursAndSymbolPropertiesDatabaseEntriesAlgorithm(QCAlgorithm):\n '''\n Algorithm illustrating how to manually set market hours and symbol properties database entries to be picked up by the algorithm's securities.\n This specific case illustrates how to do it for CFDs to match InteractiveBrokers brokerage, which has different market hours\n depending on the CFD underlying asset.\n '''\n\n def initialize(self):\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n self.set_cash(100000)\n\n self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE)\n\n # Some brokerages like InteractiveBrokers make a difference on CFDs depending on the underlying (equity, index, metal, forex).\n # Depending on this, the market hours can be different. In order to be more specific with the market hours,\n # we can set the MarketHoursDatabase entry for the CFDs.\n\n # Equity CFDs are usually traded the same hours as the equity market.\n equity_market_hours_entry = self.market_hours_database.get_entry(Market.USA, Symbol.EMPTY, SecurityType.EQUITY)\n self.market_hours_database.set_entry(Market.INTERACTIVE_BROKERS, \"\", SecurityType.CFD, equity_market_hours_entry.exchange_hours, equity_market_hours_entry.data_time_zone)\n\n # The same can be done for the symbol properties, in case they are different depending on the underlying\n equity_symbol_properties = self.symbol_properties_database.get_symbol_properties(Market.USA, Symbol.EMPTY, SecurityType.EQUITY, Currencies.USD)\n self.symbol_properties_database.set_entry(Market.INTERACTIVE_BROKERS, \"\", SecurityType.CFD, equity_symbol_properties)\n\n spy_cfd = self.add_cfd(\"SPY\", market=Market.INTERACTIVE_BROKERS)\n\n if json.JsonConvert.serialize_object(spy_cfd.exchange.hours) != json.JsonConvert.serialize_object(equity_market_hours_entry.exchange_hours):\n raise AssertionError(\"Expected the SPY CFD market hours to be the same as the underlying equity market hours.\")\n\n if json.JsonConvert.serialize_object(spy_cfd.symbol_properties) != json.JsonConvert.serialize_object(equity_symbol_properties):\n raise AssertionError(\"Expected the SPY CFD symbol properties to be the same as the underlying equity symbol properties.\")\n\n # We can also do it for a specific ticker\n aud_usd_forex_market_hours_entry = self.market_hours_database.get_entry(Market.OANDA, Symbol.EMPTY, SecurityType.FOREX)\n 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)\n\n aud_usd_forex_symbol_properties = self.symbol_properties_database.get_symbol_properties(Market.OANDA, \"AUDUSD\", SecurityType.FOREX, Currencies.USD)\n self.symbol_properties_database.set_entry(Market.INTERACTIVE_BROKERS, \"AUDUSD\", SecurityType.CFD, aud_usd_forex_symbol_properties)\n\n aud_usd_cfd = self.add_cfd(\"AUDUSD\", market=Market.INTERACTIVE_BROKERS)\n\n if json.JsonConvert.serialize_object(aud_usd_cfd.exchange.hours) != json.JsonConvert.serialize_object(aud_usd_forex_market_hours_entry.exchange_hours):\n raise AssertionError(\"Expected the AUDUSD CFD market hours to be the same as the underlying forex market hours.\")\n\n if json.JsonConvert.serialize_object(aud_usd_cfd.symbol_properties) != json.JsonConvert.serialize_object(aud_usd_forex_symbol_properties):\n raise AssertionError(\"Expected the AUDUSD CFD symbol properties to be the same as the underlying forex symbol properties.\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm is a regression test for issue #2018 and PR #2038.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionDataNullReferenceRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2016, 12, 1)\n self.set_end_date(2017, 1, 1)\n self.set_cash(500000)\n\n self.add_equity(\"DUST\")\n\n option = self.add_option(\"DUST\")\n\n option.set_filter(self.universe_func)\n\n def universe_func(self, universe):\n return universe.include_weeklys().strikes(-1, +1).expiration(timedelta(25), timedelta(100))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm demonstrates using the history provider to retrieve data\nto warm up indicators before data is received.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass WarmupHistoryAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2014,5,2) #Set Start Date\n self.set_end_date(2014,5,2) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n forex = self.add_forex(\"EURUSD\", Resolution.SECOND)\n forex = self.add_forex(\"NZDUSD\", Resolution.SECOND)\n\n fast_period = 60\n slow_period = 3600\n self.fast = self.ema(\"EURUSD\", fast_period)\n self.slow = self.ema(\"EURUSD\", slow_period)\n\n # \"slow_period + 1\" because rolling window waits for one to fall off the back to be considered ready\n # History method returns a dict with a pandas.data_frame\n history = self.history([\"EURUSD\", \"NZDUSD\"], slow_period + 1)\n\n # prints out the tail of the dataframe\n self.log(str(history.loc[\"EURUSD\"].tail()))\n self.log(str(history.loc[\"NZDUSD\"].tail()))\n\n for index, row in history.loc[\"EURUSD\"].iterrows():\n self.fast.update(index, row[\"close\"])\n self.slow.update(index, row[\"close\"])\n\n self.log(\"FAST {0} READY. Samples: {1}\".format(\"IS\" if self.fast.is_ready else \"IS NOT\", self.fast.samples))\n self.log(\"SLOW {0} READY. Samples: {1}\".format(\"IS\" if self.slow.is_ready else \"IS NOT\", self.slow.samples))\n\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n\n if self.fast.current.value > self.slow.current.value:\n self.set_holdings(\"EURUSD\", 1)\n else:\n self.set_holdings(\"EURUSD\", -1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: The demonstration algorithm shows some of the most common order methods when working with FutureOption assets.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\n\nclass BasicTemplateFutureOptionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2022, 1, 1)\n self.set_end_date(2022, 2, 1)\n self.set_cash(100000)\n\n gold_futures = self.add_future(Futures.Metals.GOLD, Resolution.MINUTE)\n gold_futures.set_filter(0, 180)\n self._symbol = gold_futures.symbol\n self.add_future_option(self._symbol, lambda universe: universe.strikes(-5, +5)\n .calls_only()\n .back_month()\n .only_apply_filter_at_market_open())\n\n # Historical Data\n history = self.history(self._symbol, 60, Resolution.DAILY)\n self.log(f\"Received {len(history)} bars from {self._symbol} FutureOption historical data call.\")\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n Arguments:\n slice: Slice object keyed by symbol containing the stock data\n '''\n # Access Data\n for kvp in data.option_chains:\n underlying_future_contract = kvp.key.underlying\n chain = kvp.value\n\n if not chain: continue\n\n for contract in chain:\n self.log(f\"\"\"Canonical Symbol: {kvp.key}; \n Contract: {contract}; \n Right: {contract.right}; \n Expiry: {contract.expiry}; \n Bid price: {contract.bid_price}; \n Ask price: {contract.ask_price}; \n Implied Volatility: {contract.implied_volatility}\"\"\")\n\n if not self.portfolio.invested:\n atm_strike = sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike))[0].strike\n selected_contract = sorted([contract for contract in chain if contract.strike == atm_strike], \\\n key = lambda x: x.expiry, reverse=True)[0]\n self.market_order(selected_contract.symbol, 1)\n\n def on_order_event(self, order_event):\n self.debug(\"{} {}\".format(self.time, order_event.to_string()))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to execute a Call Butterfly option equity strategy\nIt adds options for a given underlying equity security, and shows how you can prefilter contracts easily based on strikes and expirations", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateOptionEquityStrategyAlgorithm(QCAlgorithm):\n underlying_ticker = \"GOOG\"\n\n def initialize(self) -> None:\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n\n equity = self.add_equity(self.underlying_ticker)\n option = self.add_option(self.underlying_ticker)\n self._option_symbol = option.symbol\n\n # set our strike/expiry filter for this option chain\n option.set_filter(lambda u: (u.strikes(-2, +2)\n # Expiration method accepts TimeSpan objects or integer for days.\n # The following statements yield the same filtering criteria\n .expiration(0, 180)))\n\n def on_data(self, slice: Slice) -> None:\n if self.portfolio.invested or not self.is_market_open(self._option_symbol):\n return\n\n chain = slice.option_chains.get(self._option_symbol)\n if not chain:\n return\n\n grouped_by_expiry = dict()\n for contract in [contract for contract in chain if contract.right == OptionRight.CALL]:\n grouped_by_expiry.setdefault(int(contract.expiry.timestamp()), []).append(contract)\n\n first_expiry = list(sorted(grouped_by_expiry))[0]\n call_contracts = sorted(grouped_by_expiry[first_expiry], key = lambda x: x.strike)\n \n expiry = call_contracts[0].expiry\n lower_strike = call_contracts[0].strike\n middle_strike = call_contracts[1].strike\n higher_strike = call_contracts[2].strike\n\n option_strategy = OptionStrategies.call_butterfly(self._option_symbol, higher_strike, middle_strike, lower_strike, expiry)\n \n self.order(option_strategy, 10)\n\n def on_order_event(self, order_event: OrderEvent) -> None:\n self.log(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example of custom fill model for security to only fill bars of data obtained after the order was placed. This is to encourage more\npessimistic fill models and eliminate the possibility to fill on old market data that may not be relevant.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ForwardDataOnlyFillModelAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013,10,1)\n self.set_end_date(2013,10,31)\n\n self.security = self.add_equity(\"SPY\", Resolution.HOUR)\n self.security.set_fill_model(ForwardDataOnlyFillModel())\n\n self.schedule.on(self.date_rules.week_start(), self.time_rules.after_market_open(self.security.symbol), self.trade)\n\n def trade(self):\n if not self.portfolio.invested:\n if self.time.hour != 9 or self.time.minute != 30:\n raise AssertionError(f\"Unexpected event time {self.time}\")\n\n ticket = self.buy(\"SPY\", 1)\n if ticket.status != OrderStatus.SUBMITTED:\n raise AssertionError(f\"Unexpected order status {ticket.status}\")\n\n def on_order_event(self, order_event: OrderEvent):\n self.debug(f\"OnOrderEvent:: {order_event}\")\n if order_event.status == OrderStatus.FILLED and (self.time.hour != 10 or self.time.minute != 0):\n raise AssertionError(f\"Unexpected fill time {self.time}\")\n\nclass ForwardDataOnlyFillModel(EquityFillModel):\n def fill(self, parameters: FillModelParameters):\n order_local_time = Extensions.convert_from_utc(parameters.order.time, parameters.security.exchange.time_zone)\n for data_type in [ QuoteBar, TradeBar, Tick ]:\n data = parameters.security.cache.get_data(data_type)\n if not data is None and order_local_time <= data.end_time:\n return super().fill(parameters)\n return Fill([])\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration on how to access order tickets right after placing an order.", "output": "```python\n\n\nfrom datetime import timedelta\nfrom AlgorithmImports import *\n\nclass OrderTicketAssignmentDemoAlgorithm(QCAlgorithm):\n '''Demonstration on how to access order tickets right after placing an order.'''\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(100000)\n\n self._symbol = self.add_equity(\"SPY\").symbol\n\n self.trade_count = 0\n self.consolidate(self._symbol, timedelta(hours=1), self.hour_consolidator)\n\n def hour_consolidator(self, bar: TradeBar):\n # Reset self.ticket to None on each new bar\n self.ticket = None\n self.ticket = self.market_order(self._symbol, 1, asynchronous=True)\n self.debug(f\"{self.time}: Buy: Price {bar.price}, order_id: {self.ticket.order_id}\")\n self.trade_count += 1\n\n def on_order_event(self, order_event: OrderEvent):\n # We cannot access self.ticket directly because it is assigned asynchronously:\n # this order event could be triggered before self.ticket is assigned.\n ticket = order_event.ticket\n if ticket is None:\n raise AssertionError(\"Expected order ticket in order event to not be null\")\n if order_event.status == OrderStatus.SUBMITTED and self.ticket is not None:\n raise AssertionError(\"Field self.ticket not expected no be assigned on the first order event\")\n\n self.debug(ticket.to_string())\n\n def on_end_of_algorithm(self):\n # Just checking that orders were placed\n if not self.portfolio.invested or self.trade_count != self.transactions.orders_count:\n raise AssertionError(f\"Expected the portfolio to have holdings and to have {self.trade_count} trades, but had {self.transactions.orders_count}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of using custom fee, slippage, fill, and buying power models for modeling transactions in backtesting.\nQuantConnect allows you to model all orders as deeply and accurately as you need.\nThis example illustrates how Lean exports its API to Python conforming to PEP8 style guide.", "output": "```python\n\n\nfrom AlgorithmImports import *\nimport random\n\nclass CustomModelsPEP8Algorithm(QCAlgorithm):\n '''Demonstration of using custom fee, slippage, fill, and buying power models for modeling transactions in backtesting.\n QuantConnect allows you to model all orders as deeply and accurately as you need.'''\n\n def initialize(self):\n self.set_start_date(2013,10,1) # Set Start Date\n self.set_end_date(2013,10,31) # Set End Date\n self.security = self.add_equity(\"SPY\", Resolution.HOUR)\n self.spy = self.security.symbol\n\n # set our models\n self.security.set_fee_model(CustomFeeModelPEP8(self))\n self.security.set_fill_model(CustomFillModelPEP8(self))\n self.security.set_slippage_model(CustomSlippageModelPEP8(self))\n self.security.set_buying_power_model(CustomBuyingPowerModelPEP8(self))\n\n def on_data(self, data):\n open_orders = self.transactions.get_open_orders(self.spy)\n if len(open_orders) != 0: return\n if self.time.day > 10 and self.security.holdings.quantity <= 0:\n quantity = self.calculate_order_quantity(self.spy, .5)\n self.log(f\"MarketOrder: {quantity}\")\n self.market_order(self.spy, quantity, True) # async needed for partial fill market orders\n elif self.time.day > 20 and self.security.holdings.quantity >= 0:\n quantity = self.calculate_order_quantity(self.spy, -.5)\n self.log(f\"MarketOrder: {quantity}\")\n self.market_order(self.spy, quantity, True) # async needed for partial fill market orders\n\nclass CustomFillModelPEP8(ImmediateFillModel):\n def __init__(self, algorithm):\n super().__init__()\n self.algorithm = algorithm\n self.absolute_remaining_by_order_id = {}\n self.random = Random(387510346)\n\n def market_fill(self, asset, order):\n absolute_remaining = order.absolute_quantity\n\n if order.id in self.absolute_remaining_by_order_id.keys():\n absolute_remaining = self.absolute_remaining_by_order_id[order.id]\n\n fill = super().market_fill(asset, order)\n absolute_fill_quantity = int(min(absolute_remaining, self.random.next(0, 2*int(order.absolute_quantity))))\n fill.fill_quantity = np.sign(order.quantity) * absolute_fill_quantity\n\n if absolute_remaining == absolute_fill_quantity:\n fill.status = OrderStatus.FILLED\n if self.absolute_remaining_by_order_id.get(order.id):\n self.absolute_remaining_by_order_id.pop(order.id)\n else:\n absolute_remaining = absolute_remaining - absolute_fill_quantity\n self.absolute_remaining_by_order_id[order.id] = absolute_remaining\n fill.status = OrderStatus.PARTIALLY_FILLED\n self.algorithm.log(f\"CustomFillModel: {fill}\")\n return fill\n\nclass CustomFeeModelPEP8(FeeModel):\n def __init__(self, algorithm):\n super().__init__()\n self.algorithm = algorithm\n\n def get_order_fee(self, parameters):\n # custom fee math\n fee = max(1, parameters.security.price\n * parameters.order.absolute_quantity\n * 0.00001)\n self.algorithm.log(f\"CustomFeeModel: {fee}\")\n return OrderFee(CashAmount(fee, \"USD\"))\n\nclass CustomSlippageModelPEP8:\n def __init__(self, algorithm):\n self.algorithm = algorithm\n\n def get_slippage_approximation(self, asset, order):\n # custom slippage math\n slippage = asset.price * 0.0001 * np.log10(2*float(order.absolute_quantity))\n self.algorithm.log(f\"CustomSlippageModel: {slippage}\")\n return slippage\n\nclass CustomBuyingPowerModelPEP8(BuyingPowerModel):\n def __init__(self, algorithm):\n super().__init__()\n self.algorithm = algorithm\n\n def has_sufficient_buying_power_for_order(self, parameters):\n # custom behavior: this model will assume that there is always enough buying power\n has_sufficient_buying_power_for_order_result = HasSufficientBuyingPowerForOrderResult(True)\n self.algorithm.log(f\"CustomBuyingPowerModel: {has_sufficient_buying_power_for_order_result.is_sufficient}\")\n return has_sufficient_buying_power_for_order_result\n\nclass SimpleCustomFillModelPEP8(FillModel):\n def __init__(self):\n super().__init__()\n\n def _create_order_event(self, asset, order):\n utc_time = Extensions.convert_to_utc(asset.local_time, asset.exchange.time_zone)\n return OrderEvent(order, utc_time, OrderFee.ZERO)\n\n def _set_order_event_to_filled(self, fill, fill_price, fill_quantity):\n fill.status = OrderStatus.FILLED\n fill.fill_quantity = fill_quantity\n fill.fill_price = fill_price\n return fill\n\n def _get_trade_bar(self, asset, order_direction):\n trade_bar = asset.cache.get_data(TradeBar)\n if trade_bar:\n return trade_bar\n\n price = asset.price\n return TradeBar(asset.local_time, asset.symbol, price, price, price, price, 0)\n\n def market_fill(self, asset, order):\n fill = self._create_order_event(asset, order)\n if order.status == OrderStatus.CANCELED:\n return fill\n\n fill_price = asset.cache.ask_price if order.direction == OrderDirection.BUY else asset.cache.bid_price\n return self._set_order_event_to_filled(fill, fill_price, order.quantity)\n\n def stop_market_fill(self, asset, order):\n fill = self._create_order_event(asset, order)\n if order.status == OrderStatus.CANCELED:\n return fill\n\n stop_price = order.stop_price\n trade_bar = self._get_trade_bar(asset, order.direction)\n\n if order.direction == OrderDirection.SELL and trade_bar.low < stop_price:\n return self._set_order_event_to_filled(fill, stop_price, order.quantity)\n\n if order.direction == OrderDirection.BUY and trade_bar.high > stop_price:\n return self._set_order_event_to_filled(fill, stop_price, order.quantity)\n\n return fill\n\n def limit_fill(self, asset, order):\n fill = self._create_order_event(asset, order)\n if order.status == OrderStatus.CANCELED:\n return fill\n\n limit_price = order.limit_price\n trade_bar = self._get_trade_bar(asset, order.direction)\n\n if order.direction == OrderDirection.SELL and trade_bar.high > limit_price:\n return self._set_order_event_to_filled(fill, limit_price, order.quantity)\n\n if order.direction == OrderDirection.BUY and trade_bar.low < limit_price:\n return self._set_order_event_to_filled(fill, limit_price, order.quantity)\n\n return fill\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of how to define a universe as a combination of use the coarse fundamental data and fine fundamental data", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CoarseFineFundamentalRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2014,3,24) #Set Start Date\n self.set_end_date(2014,4,7) #Set End Date\n self.set_cash(50000) #Set Strategy Cash\n\n self.universe_settings.resolution = Resolution.DAILY\n\n # this add universe method accepts two parameters:\n # - coarse selection function: accepts an List[CoarseFundamental] and returns an List[Symbol]\n # - fine selection function: accepts an List[FineFundamental] and returns an List[Symbol]\n self.add_universe(self.coarse_selection_function, self.fine_selection_function)\n\n self.changes = None\n self.number_of_symbols_fine = 2\n\n # return a list of three fixed symbol objects\n def coarse_selection_function(self, coarse):\n tickers = [ \"GOOG\", \"BAC\", \"SPY\" ]\n\n if self.time.date() < date(2014, 4, 1):\n tickers = [ \"AAPL\", \"AIG\", \"IBM\" ]\n\n return [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers ]\n\n\n # sort the data by market capitalization and take the top 'number_of_symbols_fine'\n def fine_selection_function(self, fine):\n # sort descending by market capitalization\n sorted_by_market_cap = sorted(fine, key=lambda x: x.market_cap, reverse=True)\n\n # take the top entries from our sorted collection\n return [ x.symbol for x in sorted_by_market_cap[:self.number_of_symbols_fine] ]\n\n def on_data(self, data):\n # if we have no changes, do nothing\n if self.changes is None: return\n\n # liquidate removed securities\n for security in self.changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n self.debug(\"Liquidated Stock: \" + str(security.symbol.value))\n\n # we want 50% allocation in each security in our universe\n for security in self.changes.added_securities:\n if (security.fundamentals.earning_ratios.equity_per_share_growth.one_year > 0.25):\n self.set_holdings(security.symbol, 0.5)\n self.debug(\"Purchased Stock: \" + str(security.symbol.value))\n\n self.changes = None\n\n # this event fires whenever we have changes to our universe\n def on_securities_changed(self, changes):\n self.changes = changes\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm tests the functionality of the CompositeIndicator\nusing either a lambda expression or a method reference.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CompositeIndicatorWorksAsExpectedRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013, 10, 4)\n self.set_end_date(2013, 10, 5)\n self.add_equity(\"SPY\", Resolution.MINUTE)\n close = self.identity(\"SPY\", Resolution.MINUTE, Field.CLOSE)\n low = self.min(\"SPY\", 420, Resolution.MINUTE, Field.LOW)\n self.composite_min_direct = CompositeIndicator(\"CompositeMinDirect\", close, low, lambda l, r: IndicatorResult(min(l.current.value, r.current.value)))\n self.composite_min_method = CompositeIndicator(\"CompositeMinMethod\", close, low, self.composer)\n\n self.data_received = False\n\n def composer(self, l, r):\n return IndicatorResult(min(l.current.value, r.current.value))\n\n def on_data(self, data):\n self.data_received = True\n if self.composite_min_direct.current.value != self.composite_min_method.current.value:\n raise AssertionError(f\"Values of indicators differ: {self.composite_min_direct.current.value} | {self.composite_min_method.current.value}\")\n \n def on_end_of_algorithm(self):\n if not self.data_received:\n raise AssertionError(\"No data was processed during the algorithm execution.\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm giving an introduction into using IDataConsolidators.\nThis is an advanced QC concept and requires a certain level of comfort using C# and its event system.\n\nWhat is an IDataConsolidator?\nIDataConsolidator is a plugin point that can be used to transform your data more easily.\nIn this example we show one of the simplest consolidators, the TradeBarConsolidator.\nThis type is capable of taking a timespan to indicate how long each bar should be, or an\ninteger to indicate how many bars should be aggregated into one.\n\nWhen a new 'consolidated' piece of data is produced by the IDataConsolidator, an event is fired\nwith the argument of the new data.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass DataConsolidationAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013, 10, 7) #Set Start Date\n self.set_end_date(2013, 12, 7) #Set End Date\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\")\n self.add_forex(\"EURUSD\", Resolution.HOUR)\n\n # define our 30 minute trade bar consolidator. we can\n # access the 30 minute bar from the DataConsolidated events\n thirty_minute_consolidator = TradeBarConsolidator(timedelta(minutes=30))\n\n # attach our event handler. the event handler is a function that will\n # be called each time we produce a new consolidated piece of data.\n thirty_minute_consolidator.data_consolidated += self.thirty_minute_bar_handler\n\n # this call adds our 30 minute consolidator to\n # the manager to receive updates from the engine\n self.subscription_manager.add_consolidator(\"SPY\", thirty_minute_consolidator)\n\n # here we'll define a slightly more complex consolidator. what we're trying to produce is\n # a 3 day bar. Now we could just use a single TradeBarConsolidator like above and pass in\n # TimeSpan.from_days(3), but in reality that's not what we want. For time spans of longer than\n # a day we'll get incorrect results around weekends and such. What we really want are tradeable\n # days. So we'll create a daily consolidator, and then wrap it with a 3 count consolidator.\n\n # first define a one day trade bar -- this produces a consolidated piece of data after a day has passed\n one_day_consolidator = TradeBarConsolidator(timedelta(1))\n\n # next define our 3 count trade bar -- this produces a consolidated piece of data after it sees 3 pieces of data\n three_count_consolidator = TradeBarConsolidator(3)\n\n # here we combine them to make a new, 3 day trade bar. The SequentialConsolidator allows composition of\n # consolidators. It takes the consolidated output of one consolidator (in this case, the one_day_consolidator)\n # and pipes it through to the three_count_consolidator. His output will be a 3 day bar.\n three_one_day_bar = SequentialConsolidator(one_day_consolidator, three_count_consolidator)\n\n # attach our handler\n three_one_day_bar.data_consolidated += self.three_day_bar_consolidated_handler\n\n # this call adds our 3 day to the manager to receive updates from the engine\n self.subscription_manager.add_consolidator(\"SPY\", three_one_day_bar)\n\n # Custom monthly consolidator\n custom_monthly_consolidator = TradeBarConsolidator(self.custom_monthly)\n custom_monthly_consolidator.data_consolidated += self.custom_monthly_handler\n self.subscription_manager.add_consolidator(\"SPY\", custom_monthly_consolidator)\n\n # API convenience method for easily receiving consolidated data\n self.consolidate(\"SPY\", timedelta(minutes=45), self.forty_five_minute_bar_handler)\n self.consolidate(\"SPY\", Resolution.HOUR, self.hour_bar_handler)\n self.consolidate(\"EURUSD\", Resolution.DAILY, self.daily_eur_usd_bar_handler)\n\n # API convenience method for easily receiving weekly-consolidated data\n self.consolidate(\"SPY\", Calendar.WEEKLY, self.calendar_trade_bar_handler)\n self.consolidate(\"EURUSD\", Calendar.WEEKLY, self.calendar_quote_bar_handler)\n\n # API convenience method for easily receiving monthly-consolidated data\n self.consolidate(\"SPY\", Calendar.MONTHLY, self.calendar_trade_bar_handler)\n self.consolidate(\"EURUSD\", Calendar.MONTHLY, self.calendar_quote_bar_handler)\n\n # API convenience method for easily receiving quarterly-consolidated data\n self.consolidate(\"SPY\", Calendar.QUARTERLY, self.calendar_trade_bar_handler)\n self.consolidate(\"EURUSD\", Calendar.QUARTERLY, self.calendar_quote_bar_handler)\n\n # API convenience method for easily receiving yearly-consolidated data\n self.consolidate(\"SPY\", Calendar.YEARLY, self.calendar_trade_bar_handler)\n self.consolidate(\"EURUSD\", Calendar.YEARLY, self.calendar_quote_bar_handler)\n\n # some securities may have trade and quote data available, so we can choose it based on TickType:\n #self.consolidate(\"BTCUSD\", Resolution.HOUR, TickType.TRADE, self.hour_bar_handler) # to get TradeBar\n #self.consolidate(\"BTCUSD\", Resolution.HOUR, TickType.QUOTE, self.hour_bar_handler) # to get QuoteBar (default)\n\n self.consolidated_hour = False\n self.consolidated45_minute = False\n self.__last = None\n\n def on_data(self, data):\n '''We need to declare this method'''\n pass\n\n\n def on_end_of_day(self, symbol):\n # close up shop each day and reset our 'last' value so we start tomorrow fresh\n self.liquidate(\"SPY\")\n self.__last = None\n\n def thirty_minute_bar_handler(self, sender, consolidated):\n '''This is our event handler for our 30 minute trade bar defined above in Initialize(). So each time the\n consolidator produces a new 30 minute bar, this function will be called automatically. The 'sender' parameter\n will be the instance of the IDataConsolidator that invoked the event, but you'll almost never need that!'''\n\n if self.__last is not None and consolidated.close > self.__last.close:\n self.log(f\"{consolidated.time} >> SPY >> LONG >> 100 >> {self.portfolio['SPY'].quantity}\")\n self.order(\"SPY\", 100)\n\n elif self.__last is not None and consolidated.close < self.__last.close:\n self.log(f\"{consolidated.time} >> SPY >> SHORT >> 100 >> {self.portfolio['SPY'].quantity}\")\n self.order(\"SPY\", -100)\n\n self.__last = consolidated\n\n\n def three_day_bar_consolidated_handler(self, sender, consolidated):\n ''' This is our event handler for our 3 day trade bar defined above in Initialize(). So each time the\n consolidator produces a new 3 day bar, this function will be called automatically. The 'sender' parameter\n will be the instance of the IDataConsolidator that invoked the event, but you'll almost never need that!'''\n self.log(f\"{consolidated.time} >> Plotting!\")\n self.plot(consolidated.symbol.value, \"3HourBar\", consolidated.close)\n\n def forty_five_minute_bar_handler(self, consolidated):\n ''' This is our event handler for our 45 minute consolidated defined using the Consolidate method'''\n self.consolidated45_minute = True\n self.log(f\"{consolidated.end_time} >> FortyFiveMinuteBarHandler >> {consolidated.close}\")\n\n def hour_bar_handler(self, consolidated):\n '''This is our event handler for our one hour consolidated defined using the Consolidate method'''\n self.consolidated_hour = True\n self.log(f\"{consolidated.end_time} >> FortyFiveMinuteBarHandler >> {consolidated.close}\")\n\n def daily_eur_usd_bar_handler(self, consolidated):\n '''This is our event handler for our daily consolidated defined using the Consolidate method'''\n self.log(f\"{consolidated.end_time} EURUSD Daily consolidated.\")\n\n def calendar_trade_bar_handler(self, trade_bar):\n self.log(f'{self.time} :: {trade_bar.time} {trade_bar.close}')\n\n def calendar_quote_bar_handler(self, quote_bar):\n self.log(f'{self.time} :: {quote_bar.time} {quote_bar.close}')\n\n def custom_monthly(self, dt):\n '''Custom Monthly Func'''\n start = dt.replace(day=1).date()\n end = dt.replace(day=28) + timedelta(4)\n end = (end - timedelta(end.day-1)).date()\n return CalendarInfo(start, end - start)\n\n def custom_monthly_handler(self, sender, consolidated):\n '''This is our event handler Custom Monthly function'''\n self.log(f\"{consolidated.time} >> CustomMonthlyHandler >> {consolidated.close}\")\n\n def on_end_of_algorithm(self):\n if not self.consolidated_hour:\n raise AssertionError(\"Expected hourly consolidator to be fired.\")\n\n if not self.consolidated45_minute:\n raise AssertionError(\"Expected 45-minute consolidator to be fired.\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm illustrating the usage of the method\nto get a future option chain.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionChainFullDataRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 1, 6)\n self.set_end_date(2020, 1, 6)\n\n future_contract = self.add_future_contract(\n Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 3, 20)),\n Resolution.MINUTE).symbol\n\n option_chain = self.option_chain(future_contract, flatten=True)\n\n # Demonstration using data frame:\n df = option_chain.data_frame\n # Get contracts expiring within 4 months, with the latest expiration date, highest strike and lowest price\n contracts = df.loc[(df.expiry <= self.time + timedelta(days=120))]\n contracts = contracts.sort_values(['expiry', 'strike', 'lastprice'], ascending=[False, False, True])\n self._option_contract = contracts.index[0]\n\n self.add_future_option_contract(self._option_contract)\n\n def on_data(self, data):\n # Do some trading with the selected contract for sample purposes\n if not self.portfolio.invested:\n self.set_holdings(self._option_contract, 0.5)\n else:\n self.liquidate()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: The regression algorithm showcases the utilization of a custom data source with the Sort flag set to true.\nThis means that the source initially provides data in descending order, which is then organized into ascending order and returned in the 'on_data' function.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\n\nclass DescendingCustomDataObjectStoreRegressionAlgorithm(QCAlgorithm):\n descending_custom_data = [\n \"2024-10-03 19:00:00,173.5,176.0,172.0,175.2,120195681,4882.29\",\n \"2024-10-02 18:00:00,174.0,177.0,173.0,175.8,116275729,4641.97\",\n \"2024-10-01 17:00:00,175.0,178.0,172.5,174.5,127707078,6591.27\",\n \"2024-09-30 11:00:00,174.8,176.5,172.8,175.0,127707078,6591.27\",\n \"2024-09-27 10:00:00,172.5,175.0,171.5,173.5,120195681,4882.29\",\n \"2024-09-26 09:00:00,171.0,172.5,170.0,171.8,117516350,4820.53\",\n \"2024-09-25 08:00:00,169.5,172.0,169.0,171.0,110427867,4661.55\",\n \"2024-09-24 07:00:00,170.0,171.0,168.0,169.5,127624733,4823.52\",\n \"2024-09-23 06:00:00,172.0,173.5,169.5,171.5,123586417,4303.93\",\n \"2024-09-20 05:00:00,168.0,171.0,167.5,170.5,151929179,5429.87\",\n \"2024-09-19 04:00:00,170.5,171.5,166.0,167.0,160523863,5219.24\",\n \"2024-09-18 03:00:00,173.0,174.0,169.0,172.0,145721790,5163.09\",\n \"2024-09-17 02:00:00,171.0,173.5,170.0,172.5,144794030,5405.72\",\n \"2024-09-16 01:00:00,168.0,171.0,167.0,170.0,214402430,8753.33\",\n \"2024-09-13 16:00:00,173.5,176.0,172.0,175.2,120195681,4882.29\",\n \"2024-09-12 15:00:00,174.5,177.5,173.5,176.5,171728134,7774.83\",\n \"2024-09-11 14:00:00,175.0,178.0,174.0,175.5,191516153,8349.59\",\n \"2024-09-10 13:00:00,174.5,176.0,173.0,174.0,151162819,5915.8\",\n \"2024-09-09 12:00:00,176.0,178.0,175.0,177.0,116275729,4641.97\"\n ]\n\n def initialize(self) -> None:\n self.set_start_date(2024, 9, 9)\n self.set_end_date(2024, 10, 3)\n self.set_cash(100000)\n\n self.set_benchmark(lambda x: 0)\n\n SortCustomData.custom_data_key = self.get_custom_data_key()\n\n self._custom_symbol = self.add_data(SortCustomData, \"SortCustomData\", Resolution.DAILY).symbol\n\n # Saving data here for demonstration and regression testing purposes.\n # In real scenarios, data has to be saved to the object store before the algorithm starts.\n self.object_store.save(self.get_custom_data_key(), \"\\n\".join(self.descending_custom_data))\n\n self.received_data = []\n\n def on_data(self, slice: Slice) -> None:\n if slice.contains_key(self._custom_symbol):\n custom_data = slice.get(SortCustomData, self._custom_symbol)\n 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:\n raise AssertionError(\"One or more custom data fields (open, high, low, close, price) are zero.\")\n\n self.received_data.append(custom_data)\n\n def on_end_of_algorithm(self) -> None:\n if not self.received_data:\n raise AssertionError(\"Custom data was not fetched\")\n\n # Make sure history requests work as expected\n history = self.history(SortCustomData, self._custom_symbol, self.start_date, self.end_date, Resolution.DAILY)\n\n if history.shape[0] != len(self.received_data):\n raise AssertionError(\"History request returned more or less data than expected\")\n\n # Iterate through the history collection, checking if the time is in ascending order.\n for i in range(len(history) - 1):\n # [1] - time\n if history.index[i][1] > history.index[i + 1][1]:\n raise AssertionError(\n f\"Order failure: {history.index[i][1]} > {history.index[i + 1][1]} at index {i}.\")\n\n def get_custom_data_key(self) -> str:\n return \"CustomData/SortCustomData\"\n\n\nclass SortCustomData(PythonData):\n custom_data_key = \"\"\n\n def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:\n subscription = SubscriptionDataSource(self.custom_data_key, SubscriptionTransportMedium.OBJECT_STORE,\n FileFormat.CSV)\n # Indicate that the data from the subscription will be returned in descending order.\n subscription.sort = True\n return subscription\n\n def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData:\n data = line.split(',')\n obj_data = SortCustomData()\n obj_data.symbol = config.symbol\n obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S')\n obj_data.value = float(data[4])\n obj_data[\"Open\"] = float(data[1])\n obj_data[\"High\"] = float(data[2])\n obj_data[\"Low\"] = float(data[3])\n obj_data[\"Close\"] = float(data[4])\n return obj_data\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic Continuous Futures Template Algorithm", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateContinuousFutureAlgorithm(QCAlgorithm):\n '''Basic template algorithm simply initializes the date range and cash'''\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013, 7, 1)\n self.set_end_date(2014, 1, 1)\n\n self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI,\n data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,\n data_mapping_mode = DataMappingMode.LAST_TRADING_DAY,\n contract_depth_offset = 0)\n\n self._fast = self.sma(self._continuous_contract.symbol, 4, Resolution.DAILY)\n self._slow = self.sma(self._continuous_contract.symbol, 10, Resolution.DAILY)\n self._current_contract = None\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n for changed_event in data.symbol_changed_events.values():\n if changed_event.symbol == self._continuous_contract.symbol:\n self.log(f\"SymbolChanged event: {changed_event}\")\n\n if not self.portfolio.invested:\n if self._fast.current.value > self._slow.current.value:\n self._current_contract = self.securities[self._continuous_contract.mapped]\n self.buy(self._current_contract.symbol, 1)\n elif self._fast.current.value < self._slow.current.value:\n self.liquidate()\n\n # We check exchange hours because the contract mapping can call OnData outside of regular hours.\n if self._current_contract is not None and self._current_contract.symbol != self._continuous_contract.mapped and self._continuous_contract.exchange.exchange_open:\n self.log(f\"{self.time} - rolling position from {self._current_contract.symbol} to {self._continuous_contract.mapped}\")\n\n current_position_size = self._current_contract.holdings.quantity\n self.liquidate(self._current_contract.symbol)\n self.buy(self._continuous_contract.mapped, current_position_size)\n self._current_contract = self.securities[self._continuous_contract.mapped]\n\n def on_order_event(self, order_event):\n self.debug(\"Purchased Stock: {0}\".format(order_event.symbol))\n\n def on_securities_changed(self, changes):\n self.debug(f\"{self.time}-{changes}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm sends portfolio targets to CrunchDAO API once a week.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CrunchDAOSignalExportDemonstrationAlgorithm(QCAlgorithm):\n\n crunch_universe = []\n\n def initialize(self) -> None:\n self.set_start_date(2023, 5, 22)\n self.set_end_date(2023, 5, 26)\n self.set_cash(1_000_000)\n\n # Disable automatic exports as we manually set them\n self.signal_export.automatic_export_time_span = None\n\n # Connect to CrunchDAO\n api_key = \"\" # Your CrunchDAO API key\n model = \"\" # The Id of your CrunchDAO model\n submission_name = \"\" # A name for the submission to distinguish it from your other submissions\n comment = \"\" # A comment for the submission\n self.signal_export.add_signal_export_provider(CrunchDAOSignalExport(api_key, model, submission_name, comment))\n\n self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))\n\n # Add a custom data universe to read the CrunchDAO skeleton\n self.add_universe(CrunchDaoSkeleton, \"CrunchDaoSkeleton\", Resolution.DAILY, self.select_symbols)\n\n # Create a Scheduled Event to submit signals every monday before the market opens\n self._week = -1\n self.schedule.on(\n self.date_rules.every([DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY]),\n self.time_rules.at(13, 15, TimeZones.UTC),\n self.submit_signals)\n\n self.settings.minimum_order_margin_portfolio_percentage = 0\n\n self.set_warm_up(timedelta(45))\n\n def select_symbols(self, data: list[CrunchDaoSkeleton]) -> list[Symbol]:\n return [x.symbol for x in data]\n\n def on_securities_changed(self, changes: SecurityChanges) -> None:\n for security in changes.removed_securities:\n if security in self.crunch_universe:\n self.crunch_universe.remove(security)\n self.crunch_universe.extend(changes.added_securities)\n\n def submit_signals(self) -> None:\n if self.is_warming_up:\n return\n\n # Submit signals once per week\n week_num = self.time.isocalendar()[1]\n if self._week == week_num:\n return\n self._week = week_num\n\n symbols = [security.symbol for security in self.crunch_universe if security.price > 0]\n\n # Get historical price data\n # close_prices = self.history(symbols, 22, Resolution.DAILY).close.unstack(0)\n\n # Create portfolio targets\n weight_by_symbol = {symbol: 1/len(symbols) for symbol in symbols} # Add your logic here\n targets = [PortfolioTarget(symbol, weight) for symbol, weight in weight_by_symbol.items()]\n\n # (Optional) Place trades\n self.set_holdings(targets)\n\n # Send signals to CrunchDAO\n success = self.signal_export.set_target_portfolio(targets)\n if not success:\n self.debug(f\"Couldn't send targets at {self.time}\")\n\n\nclass CrunchDaoSkeleton(PythonData):\n\n def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:\n return SubscriptionDataSource(\"https://tournament.crunchdao.com/data/skeleton.csv\", SubscriptionTransportMedium.REMOTE_FILE)\n\n def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData:\n if not line[0].isdigit():\n return None\n skeleton = CrunchDaoSkeleton()\n skeleton.symbol = config.symbol\n\n try:\n csv = line.split(',')\n skeleton.end_time = datetime.strptime(csv[0], \"%Y-%m-%d\")\n skeleton.symbol = Symbol(SecurityIdentifier.generate_equity(csv[1], Market.USA, mapping_resolve_date=skeleton.time), csv[1])\n skeleton[\"Ticker\"] = csv[1]\n\n except ValueError:\n # Do nothing\n return None\n\n return skeleton\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example and regression algorithm asserting the behavior of registering and unregistering an indicator from the engine", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass UnregisterIndicatorRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n\n spy = self.add_equity(\"SPY\")\n ibm = self.add_equity(\"IBM\")\n\n self._symbols = [ spy.symbol, ibm.symbol ]\n self._trin = self.trin(self._symbols, Resolution.MINUTE)\n self._trin2 = None\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if self._trin.is_ready:\n self._trin.reset()\n self.unregister_indicator(self._trin)\n\n # let's create a new one with a differente resolution\n self._trin2 = self.trin(self._symbols, Resolution.HOUR)\n\n if not self._trin2 is None and self._trin2.is_ready:\n if self._trin.is_ready:\n raise ValueError(\"Indicator should of stop getting updates!\")\n\n if not self.portfolio.invested:\n self.set_holdings(self._symbols[0], 0.5)\n self.set_holdings(self._symbols[1], 0.5)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm testing GH feature 3790, using SetHoldings with a collection of targets\nwhich will be ordered by margin impact before being executed, with the objective of avoiding any\nmargin errors", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass SetHoldingsMultipleTargetsRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n\n # use leverage 1 so we test the margin impact ordering\n self._spy = self.add_equity(\"SPY\", Resolution.MINUTE, Market.USA, False, 1).symbol\n self._ibm = self.add_equity(\"IBM\", Resolution.MINUTE, Market.USA, False, 1).symbol\n\n # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.\n # Commented so regression algorithm is more sensitive\n #self.settings.minimum_order_margin_portfolio_percentage = 0.005\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings([PortfolioTarget(self._spy, 0.8), PortfolioTarget(self._ibm, 0.2)])\n else:\n self.set_holdings([PortfolioTarget(self._ibm, 0.8), PortfolioTarget(self._spy, 0.2)])\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm demonstrating the portfolio target tags usage", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass PortfolioTargetTagsRegressionAlgorithm(QCAlgorithm):\n '''Algorithm demonstrating the portfolio target tags usage'''\n\n def initialize(self):\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self.universe_settings.resolution = Resolution.MINUTE\n\n symbols = [ Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA) ]\n\n # set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel(symbols))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))\n\n self.set_portfolio_construction(CustomPortfolioConstructionModel())\n self.set_risk_management(CustomRiskManagementModel())\n self.set_execution(CustomExecutionModel(self.set_target_tags_checked))\n\n self.target_tags_checked = False\n\n def set_target_tags_checked(self):\n self.target_tags_checked = True\n\n def on_end_of_algorithm(self):\n if not self.target_tags_checked:\n raise AssertionError(\"The portfolio targets tag were not checked\")\n\nclass CustomPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):\n def __init__(self):\n super().__init__(Resolution.DAILY)\n\n def create_targets(self, algorithm: QCAlgorithm, insights: List[Insight]) -> List[IPortfolioTarget]:\n targets = super().create_targets(algorithm, insights)\n return CustomPortfolioConstructionModel.add_p_portfolio_targets_tags(targets)\n\n @staticmethod\n def generate_portfolio_target_tag(target: IPortfolioTarget) -> str:\n return f\"Portfolio target tag: {target.symbol} - {target.quantity:g}\"\n\n @staticmethod\n def add_p_portfolio_targets_tags(targets: Iterable[IPortfolioTarget]) -> List[IPortfolioTarget]:\n return [PortfolioTarget(target.symbol, target.quantity, CustomPortfolioConstructionModel.generate_portfolio_target_tag(target))\n for target in targets]\n\nclass CustomRiskManagementModel(MaximumDrawdownPercentPerSecurity):\n def __init__(self):\n super().__init__(0.01)\n\n def manage_risk(self, algorithm: QCAlgorithm, targets: List[IPortfolioTarget]) -> List[IPortfolioTarget]:\n risk_managed_targets = super().manage_risk(algorithm, targets)\n return CustomPortfolioConstructionModel.add_p_portfolio_targets_tags(risk_managed_targets)\n\nclass CustomExecutionModel(ImmediateExecutionModel):\n def __init__(self, targets_tag_checked_callback: Callable) -> None:\n super().__init__()\n self.targets_tag_checked_callback = targets_tag_checked_callback\n\n def execute(self, algorithm: QCAlgorithm, targets: List[IPortfolioTarget]) -> None:\n if len(targets) > 0:\n self.targets_tag_checked_callback()\n\n for target in targets:\n expected_tag = CustomPortfolioConstructionModel.generate_portfolio_target_tag(target)\n if target.tag != expected_tag:\n raise AssertionError(f\"Unexpected portfolio target tag: {target.tag} - Expected: {expected_tag}\")\n\n super().execute(algorithm, targets)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of using the Delisting event in your algorithm. Assets are delisted on their last day of trading, or when their contract expires.\nThis data is not included in the open source project.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass DelistingEventsAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2007, 5, 15) #Set Start Date\n self.set_end_date(2007, 5, 25) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"AAA.1\", Resolution.DAILY)\n self.add_equity(\"SPY\", Resolution.DAILY)\n\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if self.transactions.orders_count == 0:\n self.set_holdings(\"AAA.1\", 1)\n self.debug(\"Purchased stock\")\n\n for kvp in data.bars:\n symbol = kvp.key\n value = kvp.value\n\n self.log(\"OnData(Slice): {0}: {1}: {2}\".format(self.time, symbol, value.close))\n\n # the slice can also contain delisting data: data.delistings in a dictionary string->Delisting\n\n aaa = self.securities[\"AAA.1\"]\n if aaa.is_delisted and aaa.is_tradable:\n raise AssertionError(\"Delisted security must NOT be tradable\")\n\n if not aaa.is_delisted and not aaa.is_tradable:\n raise AssertionError(\"Securities must be marked as tradable until they're delisted or removed from the universe\")\n\n for kvp in data.delistings:\n symbol = kvp.key\n value = kvp.value\n\n if value.type == DelistingType.WARNING:\n self.log(\"OnData(Delistings): {0}: {1} will be delisted at end of day today.\".format(self.time, symbol))\n\n # liquidate on delisting warning\n self.set_holdings(symbol, 0)\n\n if value.type == DelistingType.DELISTED:\n self.log(\"OnData(Delistings): {0}: {1} has been delisted.\".format(self.time, symbol))\n\n # fails because the security has already been delisted and is no longer tradable\n self.set_holdings(symbol, 1)\n\n\n def on_order_event(self, order_event):\n self.log(\"OnOrderEvent(OrderEvent): {0}: {1}\".format(self.time, order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration algorithm showing how to easily convert an old algorithm into the framework.\n\n 1. When making orders, also create insights for the correct direction (up/down/flat), can also set insight prediction period/magnitude/direction\n 2. Emit insights before placing any trades\n 3. Profit :)", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ConvertToFrameworkAlgorithm(QCAlgorithm):\n '''Demonstration algorithm showing how to easily convert an old algorithm into the framework.'''\n\n fast_ema_period = 12\n slow_ema_period = 26\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2004, 1, 1)\n self.set_end_date(2015, 1, 1)\n\n self._symbol = self.add_security(SecurityType.EQUITY, 'SPY', Resolution.DAILY).symbol\n\n # define our daily macd(12,26) with a 9 day signal\n self._macd = self.macd(self._symbol, self.fast_ema_period, self.slow_ema_period, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY)\n\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n Args:\n data: Slice object with your stock data'''\n # wait for our indicator to be ready\n if not self._macd.is_ready or not data.contains_key(self._symbol) or data[self._symbol] is None: return\n\n holding = self.portfolio[self._symbol]\n\n signal_delta_percent = float(self._macd.current.value - self._macd.signal.current.value) / float(self._macd.fast.current.value)\n tolerance = 0.0025\n\n # if our macd is greater than our signal, then let's go long\n if holding.quantity <= 0 and signal_delta_percent > tolerance:\n # 1. Call emit_insights with insights created in correct direction, here we're going long\n # The emit_insights method can accept multiple insights separated by commas\n self.emit_insights(\n # Creates an insight for our symbol, predicting that it will move up within the fast ema period number of days\n Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.UP)\n )\n\n # longterm says buy as well\n self.set_holdings(self._symbol, 1)\n\n # if our macd is less than our signal, then let's go short\n elif holding.quantity >= 0 and signal_delta_percent < -tolerance:\n # 1. Call emit_insights with insights created in correct direction, here we're going short\n # The emit_insights method can accept multiple insights separated by commas\n self.emit_insights(\n # Creates an insight for our symbol, predicting that it will move down within the fast ema period number of days\n Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.DOWN)\n )\n\n self.set_holdings(self._symbol, -1)\n\n # if we wanted to liquidate our positions\n ## 1. Call emit_insights with insights create in the correct direction -- Flat\n\n #self.emit_insights(\n # 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\n # Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.FLAT)\n #)\n\n # self.liquidate()\n\n # plot both lines\n self.plot(\"MACD\", self._macd, self._macd.signal)\n self.plot(self._symbol.value, self._macd.fast, self._macd.slow)\n self.plot(self._symbol.value, \"Open\", data[self._symbol].open)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm asserting that consolidated bars are of type `QuoteBar` when `QCAlgorithm.consolidate()` is called with `tick_type=TickType.QUOTE`", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CorrectConsolidatedBarTypeForTickTypesAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 7)\n\n symbol = self.add_equity(\"SPY\", Resolution.TICK).symbol\n\n self.consolidate(symbol, timedelta(minutes=1), TickType.QUOTE, self.quote_tick_consolidation_handler)\n self.consolidate(symbol, timedelta(minutes=1), TickType.TRADE, self.trade_tick_consolidation_handler)\n\n self.quote_tick_consolidation_handler_called = False\n self.trade_tick_consolidation_handler_called = False\n\n def on_data(self, slice: Slice) -> None:\n if self.time.hour > 9:\n self.quit(\"Early quit to save time\")\n\n def on_end_of_algorithm(self):\n if not self.quote_tick_consolidation_handler_called:\n raise AssertionError(\"quote_tick_consolidation_handler was not called\")\n\n if not self.trade_tick_consolidation_handler_called:\n raise AssertionError(\"trade_tick_consolidation_handler was not called\")\n\n def quote_tick_consolidation_handler(self, consolidated_bar: QuoteBar) -> None:\n if type(consolidated_bar) != QuoteBar:\n raise AssertionError(f\"Expected the consolidated bar to be of type {QuoteBar} but was {type(consolidated_bar)}\")\n\n self.quote_tick_consolidation_handler_called = True\n\n def trade_tick_consolidation_handler(self, consolidated_bar: TradeBar) -> None:\n if type(consolidated_bar) != TradeBar:\n raise AssertionError(f\"Expected the consolidated bar to be of type {TradeBar} but was {type(consolidated_bar)}\")\n\n self.trade_tick_consolidation_handler_called = True\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of the Scheduled Events features available in QuantConnect.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ScheduledEventsAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\")\n\n # events are scheduled using date and time rules\n # date rules specify on what dates and event will fire\n # time rules specify at what time on thos dates the event will fire\n\n # schedule an event to fire at a specific date/time\n self.schedule.on(self.date_rules.on(2013, 10, 7), self.time_rules.at(13, 0), self.specific_time)\n\n # schedule an event to fire every trading day for a security the\n # time rule here tells it to fire 10 minutes after SPY's market open\n self.schedule.on(self.date_rules.every_day(\"SPY\"), self.time_rules.after_market_open(\"SPY\", 10), self.every_day_after_market_open)\n\n # schedule an event to fire every trading day for a security the\n # time rule here tells it to fire 10 minutes before SPY's market close\n self.schedule.on(self.date_rules.every_day(\"SPY\"), self.time_rules.before_market_close(\"SPY\", 10), self.every_day_after_market_close)\n\n # schedule an event to fire on a single day of the week\n self.schedule.on(self.date_rules.every(DayOfWeek.WEDNESDAY), self.time_rules.at(12, 0), self.every_wed_at_noon)\n\n # schedule an event to fire on certain days of the week\n self.schedule.on(self.date_rules.every(DayOfWeek.MONDAY, DayOfWeek.FRIDAY), self.time_rules.at(12, 0), self.every_mon_fri_at_noon)\n\n # the scheduling methods return the ScheduledEvent object which can be used for other things here I set\n # the event up to check the portfolio value every 10 minutes, and liquidate if we have too many losses\n self.schedule.on(self.date_rules.every_day(), self.time_rules.every(timedelta(minutes=10)), self.liquidate_unrealized_losses)\n\n # schedule an event to fire at the beginning of the month, the symbol is optional\n # if specified, it will fire the first trading day for that symbol of the month,\n # if not specified it will fire on the first day of the month\n self.schedule.on(self.date_rules.month_start(\"SPY\"), self.time_rules.after_market_open(\"SPY\"), self.rebalancing_code)\n\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n\n\n def specific_time(self):\n self.log(f\"SpecificTime: Fired at : {self.time}\")\n\n\n def every_day_after_market_open(self):\n self.log(f\"EveryDay.SPY 10 min after open: Fired at: {self.time}\")\n\n\n def every_day_after_market_close(self):\n self.log(f\"EveryDay.SPY 10 min before close: Fired at: {self.time}\")\n\n\n def every_wed_at_noon(self):\n self.log(f\"Wed at 12pm: Fired at: {self.time}\")\n\n\n def every_mon_fri_at_noon(self):\n self.log(f\"Mon/Fri at 12pm: Fired at: {self.time}\")\n\n\n def liquidate_unrealized_losses(self):\n ''' if we have over 1000 dollars in unrealized losses, liquidate'''\n if self.portfolio.total_unrealized_profit < -1000:\n self.log(f\"Liquidated due to unrealized losses at: {self.time}\")\n self.liquidate()\n\n\n def rebalancing_code(self):\n ''' Good spot for rebalancing code?'''\n pass\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Show example of how to use the TrailingStopRiskManagementModel", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm\nfrom Risk.TrailingStopRiskManagementModel import TrailingStopRiskManagementModel\n\nclass TrailingStopRiskFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):\n '''Show example of how to use the TrailingStopRiskManagementModel'''\n\n def initialize(self):\n super().initialize()\n self.set_universe_selection(ManualUniverseSelectionModel([Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA)]))\n\n self.set_risk_management(TrailingStopRiskManagementModel(0.01))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm showing how to use QCAlgorithm.train method", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom time import sleep\n\nclass TrainingExampleAlgorithm(QCAlgorithm):\n '''Example algorithm showing how to use QCAlgorithm.train method'''\n\n def initialize(self):\n\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 14)\n\n self.add_equity(\"SPY\", Resolution.DAILY)\n\n # Set TrainingMethod to be executed immediately\n self.train(self.training_method)\n\n # Set TrainingMethod to be executed at 8:00 am every Sunday\n self.train(self.date_rules.every(DayOfWeek.SUNDAY), self.time_rules.at(8 , 0), self.training_method)\n\n def training_method(self):\n\n self.log(f'Start training at {self.time}')\n # Use the historical data to train the machine learning model\n history = self.history([\"SPY\"], 200, Resolution.DAILY)\n\n # ML code:\n pass\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting that the option chain APIs return consistent values for index options.\nSee QCAlgorithm.OptionChain(Symbol) and QCAlgorithm.OptionChainProvider", "output": "```python\n\n\nfrom datetime import datetime\nfrom AlgorithmImports import *\n\nfrom OptionChainApisConsistencyRegressionAlgorithm import OptionChainApisConsistencyRegressionAlgorithm\n\nclass IndexOptionChainApisConsistencyRegressionAlgorithm(OptionChainApisConsistencyRegressionAlgorithm):\n\n def get_test_date(self) -> datetime:\n return datetime(2021, 1, 4)\n\n def get_option(self) -> Option:\n return self.add_index_option(\"SPX\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm illustrating the usage of the method\nto get multiple option chains, which contains additional data besides the symbols, including prices, implied volatility and greeks.\nIt also shows how this data can be used to filter the contracts based on certain criteria.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom datetime import timedelta\n\nclass OptionChainsMultipleFullDataRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n self.set_cash(100000)\n\n goog = self.add_equity(\"GOOG\").symbol\n spx = self.add_index(\"SPX\").symbol\n\n chains = self.option_chains([goog, spx], flatten=True)\n\n self._goog_option_contract = self.get_contract(chains, goog, timedelta(days=10))\n self._spx_option_contract = self.get_contract(chains, spx, timedelta(days=60))\n\n self.add_option_contract(self._goog_option_contract)\n self.add_index_option_contract(self._spx_option_contract)\n\n def get_contract(self, chains: OptionChains, underlying: Symbol, expiry_span: timedelta) -> Symbol:\n df = chains.data_frame\n\n # Index by the requested underlying, by getting all data with canonicals which underlying is the requested underlying symbol:\n canonicals = df.index.get_level_values('canonical')\n condition = [canonical for canonical in canonicals if canonical.underlying == underlying]\n df = df.loc[condition]\n\n # Get contracts expiring in the next 10 days with an implied volatility greater than 0.5 and a delta less than 0.5\n contracts = df.loc[(df.expiry <= self.time + expiry_span) & (df.impliedvolatility > 0.5) & (df.delta < 0.5)]\n\n # Select the contract with the latest expiry date\n contracts.sort_values(by='expiry', ascending=False, inplace=True)\n\n # Get the symbol: the resulting series name is a tuple (canonical symbol, contract symbol)\n return contracts.iloc[0].name[1]\n\n def on_data(self, data):\n # Do some trading with the selected contract for sample purposes\n if not self.portfolio.invested:\n self.market_order(self._goog_option_contract, 1)\n else:\n self.liquidate()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: In this algorithm we demonstrate how to use the UniverseSettings\nto define the data normalization mode (raw)", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass RawPricesUniverseRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n # what resolution should the data *added* to the universe be?\n self.universe_settings.resolution = Resolution.DAILY\n\n # Use raw prices\n self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW\n\n self.set_start_date(2014,3,24) #Set Start Date\n self.set_end_date(2014,4,7) #Set End Date\n self.set_cash(50000) #Set Strategy Cash\n\n # Set the security initializer with zero fees and price initial seed\n securitySeeder = FuncSecuritySeeder(self.get_last_known_prices)\n self.set_security_initializer(CompositeSecurityInitializer(\n FuncSecurityInitializer(lambda x: x.set_fee_model(ConstantFeeModel(0))),\n FuncSecurityInitializer(lambda security: securitySeeder.seed_security(security))))\n\n self.add_universe(\"MyUniverse\", Resolution.DAILY, self.selection_function)\n\n\n def selection_function(self, date_time):\n if date_time.day % 2 == 0:\n return [\"SPY\", \"IWM\", \"QQQ\"]\n else:\n return [\"AIG\", \"BAC\", \"IBM\"]\n\n\n # this event fires whenever we have changes to our universe\n def on_securities_changed(self, changes):\n # liquidate removed securities\n for security in changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n\n # we want 20% allocation in each security in our universe\n for security in changes.added_securities:\n self.set_holdings(security.symbol, 0.2)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm asserting that closed orders can be updated with a new tag", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CompleteOrderTagUpdateAlgorithm(QCAlgorithm):\n\n _tag_after_fill = \"This is the tag set after order was filled.\"\n _tag_after_canceled = \"This is the tag set after order was canceled.\"\n\n def initialize(self) -> None:\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n self.set_cash(100000)\n\n self._spy = self.add_equity(\"SPY\", Resolution.MINUTE).symbol\n\n self._market_order_ticket = None\n self._limit_order_ticket = None\n\n self._quantity = 100\n\n def on_data(self, data: Slice) -> None:\n if not self.portfolio.invested:\n if self._limit_order_ticket is None:\n # a limit order to test the tag update after order was canceled.\n\n # low price, we don't want it to fill since we are canceling it\n self._limit_order_ticket = self.limit_order(self._spy, 100, self.securities[self._spy].price * 0.1)\n self._limit_order_ticket.cancel()\n else:\n # a market order to test the tag update after order was filled.\n self.buy(self._spy, self._quantity)\n\n def on_order_event(self, order_event: OrderEvent) -> None:\n if order_event.status == OrderStatus.CANCELED:\n if not self._limit_order_ticket or order_event.order_id != self._limit_order_ticket.order_id:\n raise AssertionError(\"The only canceled order should have been the limit order.\")\n\n # update canceled order tag\n self.update_order_tag(self._limit_order_ticket, self._tag_after_canceled, \"Error updating order tag after canceled\")\n elif order_event.status == OrderStatus.FILLED:\n self._market_order_ticket = list(self.transactions.get_order_tickets(lambda x: x.order_type == OrderType.MARKET))[0]\n if not self._market_order_ticket or order_event.order_id != self._market_order_ticket.order_id:\n raise AssertionError(\"The only filled order should have been the market order.\")\n\n # update filled order tag\n self.update_order_tag(self._market_order_ticket, self._tag_after_fill, \"Error updating order tag after fill\")\n\n def on_end_of_algorithm(self) -> None:\n # check the filled order\n self.assert_order_tag_update(self._market_order_ticket, self._tag_after_fill, \"filled\")\n if self._market_order_ticket.quantity != self._quantity or self._market_order_ticket.quantity_filled != self._quantity:\n raise AssertionError(\"The market order quantity should not have been updated.\")\n\n # check the canceled order\n self.assert_order_tag_update(self._limit_order_ticket, self._tag_after_canceled, \"canceled\")\n\n def assert_order_tag_update(self, ticket: OrderTicket, expected_tag: str, order_action: str) -> None:\n if ticket is None:\n raise AssertionError(f\"The order ticket was not set for the {order_action} order\")\n\n if ticket.tag != expected_tag:\n raise AssertionError(f\"Order ticket tag was not updated after order was {order_action}\")\n\n order = self.transactions.get_order_by_id(ticket.order_id)\n if order.tag != expected_tag:\n raise AssertionError(f\"Order tag was not updated after order was {order_action}\")\n\n def update_order_tag(self, ticket: OrderTicket, tag: str, error_message_prefix: str) -> None:\n update_fields = UpdateOrderFields()\n update_fields.tag = tag\n response = ticket.update(update_fields)\n\n if response.is_error:\n raise AssertionError(f\"{error_message_prefix}: {response.error_message}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm for the StandardDeviationExecutionModel.\nThis algorithm shows how the execution model works to split up orders and submit them\nonly when the price is 2 standard deviations from the 60min mean (default model settings).", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Alphas.RsiAlphaModel import RsiAlphaModel\nfrom Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\nfrom Execution.StandardDeviationExecutionModel import StandardDeviationExecutionModel\n\nclass StandardDeviationExecutionModelRegressionAlgorithm(QCAlgorithm):\n '''Regression algorithm for the StandardDeviationExecutionModel.\n This algorithm shows how the execution model works to split up orders and submit them\n only when the price is 2 standard deviations from the 60min mean (default model settings).'''\n\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.MINUTE\n\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,11)\n self.set_cash(1000000)\n\n self.set_universe_selection(ManualUniverseSelectionModel([\n Symbol.create('AIG', SecurityType.EQUITY, Market.USA),\n Symbol.create('BAC', SecurityType.EQUITY, Market.USA),\n Symbol.create('IBM', SecurityType.EQUITY, Market.USA),\n Symbol.create('SPY', SecurityType.EQUITY, Market.USA)\n ]))\n\n self.set_alpha(RsiAlphaModel(14, Resolution.HOUR))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(StandardDeviationExecutionModel())\n\n def on_order_event(self, order_event):\n self.log(f\"{self.time}: {order_event}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm of the Identity indicator with the filtering enhancement. Filtering is used to check\nthe output of the indicator before returning it.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FilteredIdentityAlgorithm(QCAlgorithm):\n ''' Example algorithm of the Identity indicator with the filtering enhancement '''\n \n def initialize(self):\n \n self.set_start_date(2014,5,2) # Set Start Date\n self.set_end_date(self.start_date) # Set End Date\n self.set_cash(100000) # Set Stratgy Cash\n \n # Find more symbols here: http://quantconnect.com/data\n security = self.add_forex(\"EURUSD\", Resolution.TICK)\n\n self._symbol = security.symbol\n self._identity = self.filtered_identity(self._symbol, filter=self.filter)\n \n def filter(self, data):\n '''Filter function: True if data is not an instance of Tick. If it is, true if TickType is Trade\n data -- Data for applying the filter'''\n if isinstance(data, Tick):\n return data.tick_type == TickType.TRADE\n return True\n \n def on_data(self, data):\n # Since we are only accepting TickType.TRADE,\n # this indicator will never be ready\n if not self._identity.is_ready: return\n if not self.portfolio.invested:\n self.set_holdings(self._symbol, 1)\n self.debug(\"Purchased Stock\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm asserts we can consolidate Tick data with different tick types", "output": "```python\n\n\n\nfrom AlgorithmImports import *\n\nclass ConsolidateDifferentTickTypesRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013, 10, 6)\n self.set_end_date(2013, 10, 7)\n self.set_cash(1000000)\n\n equity = self.add_equity(\"SPY\", Resolution.TICK, Market.USA)\n quote_consolidator = self.consolidate(equity.symbol, Resolution.TICK, TickType.QUOTE, lambda tick : self.on_quote_tick(tick))\n self.there_is_at_least_one_quote_tick = False\n\n trade_consolidator = self.consolidate(equity.symbol, Resolution.TICK, TickType.TRADE, lambda tick : self.on_trade_tick(tick))\n self.there_is_at_least_one_trade_tick = False\n\n # Tick consolidators with max count\n self.consolidate(TradeBar, equity.symbol, 10, TickType.TRADE, lambda trade_bar: self.on_trade_tick_max_count(trade_bar))\n self._there_is_at_least_one_trade_bar = False\n\n self.consolidate(QuoteBar, equity.symbol, 10, TickType.QUOTE, lambda quote_bar: self.on_quote_tick_max_count(quote_bar))\n self._there_is_at_least_one_quote_bar = False\n\n self._consolidation_count = 0\n\n def on_trade_tick_max_count(self, trade_bar):\n self._there_is_at_least_one_trade_bar = True\n if type(trade_bar) != TradeBar:\n raise AssertionError(f\"The type of the bar should be Trade, but was {type(trade_bar)}\")\n\n def on_quote_tick_max_count(self, quote_bar):\n self._there_is_at_least_one_quote_bar = True\n if type(quote_bar) != QuoteBar:\n raise AssertionError(f\"The type of the bar should be Quote, but was {type(quote_bar)}\")\n\n self._consolidation_count += 1\n # Let's shortcut to reduce regression test duration: algorithms using tick data are too long\n if self._consolidation_count >= 1000:\n self.quit()\n\n def on_quote_tick(self, tick):\n self.there_is_at_least_one_quote_tick = True\n if tick.tick_type != TickType.QUOTE:\n raise AssertionError(f\"The type of the tick should be Quote, but was {tick.tick_type}\")\n\n def on_trade_tick(self, tick):\n self.there_is_at_least_one_trade_tick = True\n if tick.tick_type != TickType.TRADE:\n raise AssertionError(f\"The type of the tick should be Trade, but was {tick.tick_type}\")\n\n def on_end_of_algorithm(self):\n if not self.there_is_at_least_one_quote_tick:\n raise AssertionError(f\"There should have been at least one tick in OnQuoteTick() method, but there wasn't\")\n\n if not self.there_is_at_least_one_trade_tick:\n raise AssertionError(f\"There should have been at least one tick in OnTradeTick() method, but there wasn't\")\n\n if not self._there_is_at_least_one_trade_bar:\n raise AssertionError(\"There should have been at least one bar in OnTradeTickMaxCount() method, but there wasn't\")\n\n if not self._there_is_at_least_one_quote_bar:\n raise AssertionError(\"There should have been at least one bar in OnQuoteTickMaxCount() method, but there wasn't\")\n\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm demonstrating the option universe filter by greeks and other options data feature", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionUniverseFilterGreeksRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n self.set_cash(100000)\n\n underlying_ticker = \"GOOG\"\n self.add_equity(underlying_ticker)\n option = self.add_option(underlying_ticker)\n self.option_symbol = option.symbol\n\n self._min_delta = 0.5\n self._max_delta = 1.5\n self._min_gamma = 0.0001\n self._max_gamma = 0.0006\n self._min_vega = 0.01\n self._max_vega = 1.5\n self._min_theta = -2.0\n self._max_theta = -0.5\n self._min_rho = 0.5\n self._max_rho = 3.0\n self._min_iv = 1.0\n self._max_iv = 3.0\n self._min_open_interest = 100\n self._max_open_interest = 500\n\n option.set_filter(self.main_filter)\n self.option_chain_received = False\n\n def main_filter(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:\n total_contracts = len(list(universe))\n\n filtered_universe = self.option_filter(universe)\n filtered_contracts = len(list(filtered_universe))\n\n if filtered_contracts == total_contracts:\n raise AssertionError(f\"Expected filtered universe to have less contracts than original universe. \"\n f\"Filtered contracts count ({filtered_contracts}) is equal to total contracts count ({total_contracts})\")\n\n return filtered_universe\n\n def option_filter(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:\n # Contracts can be filtered by greeks, implied volatility, open interest:\n return universe \\\n .delta(self._min_delta, self._max_delta) \\\n .gamma(self._min_gamma, self._max_gamma) \\\n .vega(self._min_vega, self._max_vega) \\\n .theta(self._min_theta, self._max_theta) \\\n .rho(self._min_rho, self._max_rho) \\\n .implied_volatility(self._min_iv, self._max_iv) \\\n .open_interest(self._min_open_interest, self._max_open_interest)\n\n # Note: there are also shortcuts for these filter methods:\n '''\n return universe \\\n .d(self._min_delta, self._max_delta) \\\n .g(self._min_gamma, self._max_gamma) \\\n .v(self._min_vega, self._max_vega) \\\n .t(self._min_theta, self._max_theta) \\\n .r(self._min_rho, self._max_rho) \\\n .iv(self._min_iv, self._max_iv) \\\n .oi(self._min_open_interest, self._max_open_interest)\n '''\n\n def on_data(self, slice: Slice) -> None:\n chain = slice.option_chains.get(self.option_symbol)\n if chain and len(chain.contracts) > 0:\n self.option_chain_received = True\n\n def on_end_of_algorithm(self) -> None:\n if not self.option_chain_received:\n raise AssertionError(\"Option chain was not received.\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm asserts the consolidated US equity daily bars from the hour bars exactly matches\nthe daily bars returned from the database", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ConsolidateHourBarsIntoDailyBarsRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2020, 5, 1)\n self.set_end_date(2020, 6, 5)\n\n self.spy = self.add_equity(\"SPY\", Resolution.HOUR).symbol\n\n # We will use these two indicators to compare the daily consolidated bars equals\n # the ones returned from the database. We use this specific type of indicator as\n # it depends on its previous values. Thus, if at some point the bars received by\n # the indicators differ, so will their final values\n self._rsi = RelativeStrengthIndex(\"First\", 15, MovingAverageType.WILDERS)\n self.register_indicator(self.spy, self._rsi, Resolution.DAILY, selector= lambda bar: (bar.close + bar.open) / 2)\n\n # We won't register this indicator as we will update it manually at the end of the\n # month, so that we can compare the values of the indicator that received consolidated\n # bars and the values of this one\n self._rsi_timedelta = RelativeStrengthIndex(\"Second\", 15, MovingAverageType.WILDERS)\n self._values = {}\n self.count = 0\n self._indicators_compared = False\n\n def on_data(self, data: Slice):\n if self.is_warming_up:\n return\n\n if data.contains_key(self.spy) and data[self.spy] != None:\n if self.time.month == self.end_date.month:\n history = self.history[TradeBar](self.spy, self.count, Resolution.DAILY)\n for bar in history:\n time = bar.end_time.strftime('%Y-%m-%d')\n average = (bar.close + bar.open) / 2\n self._rsi_timedelta.update(bar.end_time, average)\n if self._rsi_timedelta.current.value != self._values[time]:\n 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}\")\n self._indicators_compared = True\n self.quit()\n else:\n time = self.time.strftime('%Y-%m-%d')\n self._values[time] = self._rsi.current.value\n\n # Since the symbol resolution is hour and the symbol is equity, we know the last bar received in a day will\n # be at the market close, this is 16h. We need to count how many daily bars were consolidated in order to know\n # how many we need to request from the history\n if self.time.hour == 16:\n self.count += 1\n\n def on_end_of_algorithm(self):\n if not self._indicators_compared:\n 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\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm testing the SetHolding trading API precision", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass SetHoldingsRegressionAlgorithm(QCAlgorithm):\n '''Basic template algorithm simply initializes the date range and cash'''\n\n asynchronous_orders = False\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 8)\n self.add_equity(\"SPY\", Resolution.MINUTE)\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 0.1, asynchronous=self.asynchronous_orders)\n self.set_holdings(\"SPY\", float(0.20), asynchronous=self.asynchronous_orders)\n self.set_holdings(\"SPY\", np.float64(0.30), asynchronous=self.asynchronous_orders)\n self.set_holdings(\"SPY\", 1, asynchronous=self.asynchronous_orders)\n\n def on_end_of_algorithm(self):\n for ticket in self.transactions.get_order_tickets():\n if ticket.submit_request.asynchronous != self.asynchronous_orders:\n raise AssertionError(\"Expected all orders to have the same asynchronous flag as the algorithm.\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm shows how to grab symbols from an external api each day\nand load data using the universe selection feature. In this example we\ndefine a custom data type for the NYSE top gainers and then short the\ntop 2 gainers each day", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomDataUniverseAlgorithm(QCAlgorithm):\n\n def initialize(self):\n\n # Data ADDED via universe selection is added with Daily resolution.\n self.universe_settings.resolution = Resolution.DAILY\n\n self.set_start_date(2015,1,5)\n self.set_end_date(2015,7,1)\n self.set_cash(100000)\n\n self.add_equity(\"SPY\", Resolution.DAILY)\n self.set_benchmark(\"SPY\")\n\n # add a custom universe data source (defaults to usa-equity)\n self.add_universe(NyseTopGainers, \"universe-nyse-top-gainers\", Resolution.DAILY, self.nyse_top_gainers)\n \n def nyse_top_gainers(self, data):\n return [ x.symbol for x in data if x[\"TopGainersRank\"] <= 2 ]\n\n\n def on_data(self, slice):\n pass\n \n def on_securities_changed(self, changes):\n self._changes = changes\n\n for security in changes.removed_securities:\n # liquidate securities that have been removed\n if security.invested:\n self.liquidate(security.symbol)\n self.log(\"Exit {0} at {1}\".format(security.symbol, security.close))\n\n for security in changes.added_securities:\n # enter short positions on new securities\n if not security.invested and security.close != 0:\n qty = self.calculate_order_quantity(security.symbol, -0.25)\n self.market_on_open_order(security.symbol, qty)\n self.log(\"Enter {0} at {1}\".format(security.symbol, security.close))\n\n \nclass NyseTopGainers(PythonData):\n def __init__(self):\n self.count = 0\n self.last_date = datetime.min\n\n def get_source(self, config, date, is_live_mode):\n url = \"http://www.wsj.com/mdc/public/page/2_3021-gainnyse-gainer.html\" if is_live_mode else \\\n \"https://www.dropbox.com/s/vrn3p38qberw3df/nyse-gainers.csv?dl=1\"\n\n return SubscriptionDataSource(url, SubscriptionTransportMedium.REMOTE_FILE)\n \n def reader(self, config, line, date, is_live_mode):\n \n if not is_live_mode:\n # backtest gets data from csv file in dropbox\n if not (line.strip() and line[0].isdigit()): return None\n csv = line.split(',')\n nyse = NyseTopGainers()\n nyse.time = datetime.strptime(csv[0], \"%Y%m%d\")\n nyse.end_time = nyse.time + timedelta(1)\n nyse.symbol = Symbol.create(csv[1], SecurityType.EQUITY, Market.USA)\n nyse[\"TopGainersRank\"] = int(csv[2])\n return nyse\n\n if self.last_date != date:\n # reset our counter for the new day\n self.last_date = date\n self.count = 0\n \n # parse the html into a symbol\n if not line.startswith(' y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.gamma).to_list()\n 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()\n 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()\n 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()\n 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()\n\n # The commented out test cases all return zero.\n # This is because of failure to evaluate the greeks in the option pricing model, most likely\n # due to us not clearing the default 30 day requirement for the volatility model to start being updated.\n if any([i for i in deltas if i == 0]):\n raise AssertionError(\"Option contract Delta was equal to zero\")\n\n # Delta is 1, therefore we expect a gamma of 0\n if any([i for i in gammas if i == 0]):\n raise AssertionError(\"Option contract Gamma was equal to zero\")\n\n if any([i for i in lambda_ if lambda_ == 0]):\n raise AssertionError(\"Option contract Lambda was equal to zero\")\n\n if any([i for i in rho if i == 0]):\n raise AssertionError(\"Option contract Rho was equal to zero\")\n\n if any([i for i in theta if i == 0]):\n raise AssertionError(\"Option contract Theta was equal to zero\")\n\n # The strike is far away from the underlying asset's price, and we're very close to expiry.\n # Zero is an expected value here.\n if any([i for i in vega if vega == 0]):\n raise AggregateException(\"Option contract Vega was equal to zero\")\n\n if not self.invested:\n self.set_holdings(list(list(data.option_chains.values())[0].contracts.values())[0].symbol, 1)\n self.invested = True\n\n ### \n ### Ran at the end of the algorithm to ensure the algorithm has no holdings\n ### \n ### The algorithm has holdings\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}\")\n\n if not self.invested:\n raise AssertionError(f\"Never checked greeks, maybe we have no option data?\")\n\n def sort_by_max_volume(self, data: Slice):\n 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]\n return chain.contracts.values()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression test illustrating how history from custom data sources can be requested. The method used in this\nexample also allows to specify other parameters than just the resolution, such as the data normalization mode, the data mapping mode, etc.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass HistoryWithCustomDataSourceRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2014, 6, 5)\n self.set_end_date(2014, 6, 6)\n\n self.aapl = self.add_data(CustomData, \"AAPL\", Resolution.MINUTE).symbol\n self.spy = self.add_data(CustomData, \"SPY\", Resolution.MINUTE).symbol\n\n def on_end_of_algorithm(self):\n aapl_history = self.history(CustomData, self.aapl, self.start_date, self.end_date, Resolution.MINUTE,\n fill_forward=False, extended_market_hours=False, data_normalization_mode=DataNormalizationMode.RAW).droplevel(0, axis=0)\n spy_history = self.history(CustomData, self.spy, self.start_date, self.end_date, Resolution.MINUTE,\n fill_forward=False, extended_market_hours=False, data_normalization_mode=DataNormalizationMode.RAW).droplevel(0, axis=0)\n\n if aapl_history.size == 0 or spy_history.size == 0:\n raise AssertionError(\"At least one of the history results is empty\")\n\n # Check that both resutls contain the same data, since CustomData fetches APPL data regardless of the symbol\n if not aapl_history.equals(spy_history):\n raise AssertionError(\"Histories are not equal\")\n\nclass CustomData(PythonData):\n '''Custom data source for the regression test algorithm, which returns AAPL equity data regardless of the symbol requested.'''\n\n def get_source(self, config, date, is_live_mode):\n return TradeBar().get_source(\n SubscriptionDataConfig(\n config,\n CustomData,\n # Create a new symbol as equity so we find the existing data files\n # Symbol.create(config.mapped_symbol, SecurityType.EQUITY, config.market)),\n Symbol.create(\"AAPL\", SecurityType.EQUITY, config.market)),\n date,\n is_live_mode)\n\n def reader(self, config, line, date, is_live_mode):\n trade_bar = TradeBar.parse_equity(config, line, date)\n data = CustomData()\n data.time = trade_bar.time\n data.value = trade_bar.value\n data.close = trade_bar.close\n data.open = trade_bar.open\n data.high = trade_bar.high\n data.low = trade_bar.low\n data.volume = trade_bar.volume\n\n return data\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm which tests that a two leg currency conversion happens correctly", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass TwoLegCurrencyConversionRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2018, 4, 4)\n self.set_end_date(2018, 4, 4)\n self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH)\n # GDAX doesn't have LTCETH or ETHLTC, but they do have ETHUSD and LTCUSD to form a path between ETH and LTC\n self.set_account_currency(\"ETH\")\n self.set_cash(\"ETH\", 100000)\n self.set_cash(\"LTC\", 100000)\n self.set_cash(\"USD\", 100000)\n\n self._eth_usd_symbol = self.add_crypto(\"ETHUSD\", Resolution.MINUTE).symbol\n self._ltc_usd_symbol = self.add_crypto(\"LTCUSD\", Resolution.MINUTE).symbol\n\n def on_data(self, data):\n if not self.portfolio.invested:\n self.market_order(self._ltc_usd_symbol, 1)\n\n def on_end_of_algorithm(self):\n ltc_cash = self.portfolio.cash_book[\"LTC\"]\n\n conversion_symbols = [x.symbol for x in ltc_cash.currency_conversion.conversion_rate_securities]\n\n if len(conversion_symbols) != 2:\n raise ValueError(\n f\"Expected two conversion rate securities for LTC to ETH, is {len(conversion_symbols)}\")\n\n if conversion_symbols[0] != self._ltc_usd_symbol:\n raise ValueError(\n f\"Expected first conversion rate security from LTC to ETH to be {self._ltc_usd_symbol}, is {conversion_symbols[0]}\")\n\n if conversion_symbols[1] != self._eth_usd_symbol:\n raise ValueError(\n f\"Expected second conversion rate security from LTC to ETH to be {self._eth_usd_symbol}, is {conversion_symbols[1]}\")\n\n ltc_usd_value = self.securities[self._ltc_usd_symbol].get_last_data().value\n eth_usd_value = self.securities[self._eth_usd_symbol].get_last_data().value\n\n expected_conversion_rate = ltc_usd_value / eth_usd_value\n actual_conversion_rate = ltc_cash.conversion_rate\n\n if actual_conversion_rate != expected_conversion_rate:\n raise ValueError(\n f\"Expected conversion rate from LTC to ETH to be {expected_conversion_rate}, is {actual_conversion_rate}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Test algorithm verifying OnEndOfDay callbacks are called as expected. See GH issue 2865.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OnEndOfDayRegressionAlgorithm(QCAlgorithm):\n '''Test algorithm verifying OnEndOfDay callbacks are called as expected. See GH issue 2865.'''\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n self.set_cash(100000)\n\n self._spy_symbol = Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n self._bac_symbol = Symbol.create(\"BAC\", SecurityType.EQUITY, Market.USA)\n self._ibm_symbol = Symbol.create(\"IBM\", SecurityType.EQUITY, Market.USA)\n self._on_end_of_day_spy_call_count = 0\n self._on_end_of_day_bac_call_count = 0\n self._on_end_of_day_ibm_call_count = 0\n\n self.add_universe('my_universe_name', self.selection)\n\n def selection(self, time):\n if time.day == 8:\n return [self._spy_symbol.value, self._ibm_symbol.value]\n return [self._spy_symbol.value]\n\n def on_end_of_day(self, symbol):\n '''We expect it to be called on each day after the first selection process\n happens and the algorithm has a security in it\n '''\n if symbol == self._spy_symbol:\n if self._on_end_of_day_spy_call_count == 0:\n # just the first time\n self.set_holdings(self._spy_symbol, 0.5)\n self.add_equity(\"BAC\")\n self._on_end_of_day_spy_call_count += 1\n if symbol == self._bac_symbol:\n if self._on_end_of_day_bac_call_count == 0:\n # just the first time\n self.set_holdings(self._bac_symbol, 0.5)\n self._on_end_of_day_bac_call_count += 1\n if symbol == self._ibm_symbol:\n self._on_end_of_day_ibm_call_count += 1\n\n self.log(\"OnEndOfDay() called: \" + str(self.utc_time)\n + \". SPY count \" + str(self._on_end_of_day_spy_call_count)\n + \". BAC count \" + str(self._on_end_of_day_bac_call_count)\n + \". IBM count \" + str(self._on_end_of_day_ibm_call_count))\n\n def on_end_of_algorithm(self):\n '''Assert expected behavior'''\n if self._on_end_of_day_spy_call_count != 5:\n raise ValueError(\"OnEndOfDay(SPY) unexpected count call \" + str(self._on_end_of_day_spy_call_count))\n if self._on_end_of_day_bac_call_count != 4:\n raise ValueError(\"OnEndOfDay(BAC) unexpected count call \" + str(self._on_end_of_day_bac_call_count))\n if self._on_end_of_day_ibm_call_count != 1:\n raise ValueError(\"OnEndOfDay(IBM) unexpected count call \" + str(self._on_end_of_day_ibm_call_count))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm illustrating how to request history data for different data normalization modes.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass HistoryWithDifferentDataNormalizationModeRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2014, 1, 1)\n self.aapl_equity_symbol = self.add_equity(\"AAPL\", Resolution.DAILY).symbol\n self.es_future_symbol = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.DAILY).symbol\n\n def on_end_of_algorithm(self):\n equity_data_normalization_modes = [\n DataNormalizationMode.RAW,\n DataNormalizationMode.ADJUSTED,\n DataNormalizationMode.SPLIT_ADJUSTED\n ]\n self.check_history_results_for_data_normalization_modes(self.aapl_equity_symbol, self.start_date, self.end_date, Resolution.DAILY,\n equity_data_normalization_modes)\n\n future_data_normalization_modes = [\n DataNormalizationMode.RAW,\n DataNormalizationMode.BACKWARDS_RATIO,\n DataNormalizationMode.BACKWARDS_PANAMA_CANAL,\n DataNormalizationMode.FORWARD_PANAMA_CANAL\n ]\n self.check_history_results_for_data_normalization_modes(self.es_future_symbol, self.start_date, self.end_date, Resolution.DAILY,\n future_data_normalization_modes)\n\n def check_history_results_for_data_normalization_modes(self, symbol, start, end, resolution, data_normalization_modes):\n history_results = [self.history([symbol], start, end, resolution, data_normalization_mode=x) for x in data_normalization_modes]\n history_results = [x.droplevel(0, axis=0) for x in history_results] if len(history_results[0].index.levels) == 3 else history_results\n history_results = [x.loc[symbol].close for x in history_results]\n\n if any(x.size == 0 or x.size != history_results[0].size for x in history_results):\n raise AssertionError(f\"History results for {symbol} have different number of bars\")\n\n # Check that, for each history result, close prices at each time are different for these securities (AAPL and ES)\n for j in range(history_results[0].size):\n close_prices = set(history_results[i][j] for i in range(len(history_results)))\n if len(close_prices) != len(data_normalization_modes):\n raise AssertionError(f\"History results for {symbol} have different close prices at the same time\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Tests delistings for Futures and Futures Options to ensure that they are delisted at the expected times.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FuturesAndFutures_optionsExpiryTimeAndLiquidationRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.invested = False\n self.liquidated = 0\n self.delistings_received = 0\n\n self.expected_expiry_warning_time = datetime(2020, 6, 19)\n self.expected_expiry_delisting_time = datetime(2020, 6, 20)\n self.expected_liquidation_time = datetime(2020, 6, 20)\n\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 12, 1)\n self.set_cash(100000)\n\n es = Symbol.create_future(\n \"ES\",\n Market.CME,\n datetime(2020, 6, 19)\n )\n\n es_option = Symbol.create_option(\n es,\n Market.CME,\n OptionStyle.AMERICAN,\n OptionRight.PUT,\n 3400.0,\n datetime(2020, 6, 19)\n )\n\n self.es_future = self.add_future_contract(es, Resolution.MINUTE).symbol\n self.es_future_option = self.add_future_option_contract(es_option, Resolution.MINUTE).symbol\n\n def on_data(self, data: Slice):\n for delisting in data.delistings.values():\n self.delistings_received += 1\n\n if delisting.type == DelistingType.WARNING and delisting.time != self.expected_expiry_warning_time:\n raise AssertionError(f\"Expiry warning with time {delisting.time} but is expected to be {self.expected_expiry_warning_time}\")\n\n if delisting.type == DelistingType.WARNING and delisting.time != datetime(self.time.year, self.time.month, self.time.day):\n raise AssertionError(f\"Delisting warning received at an unexpected date: {self.time} - expected {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED and delisting.time != self.expected_expiry_delisting_time:\n raise AssertionError(f\"Delisting occurred at unexpected time: {delisting.time} - expected: {self.expected_expiry_delisting_time}\")\n\n if delisting.type == DelistingType.DELISTED and delisting.time != datetime(self.time.year, self.time.month, self.time.day):\n raise AssertionError(f\"Delisting notice received at an unexpected date: {self.time} - expected {delisting.time}\")\n\n if not self.invested and \\\n (self.es_future in data.bars or self.es_future in data.quote_bars) and \\\n (self.es_future_option in data.bars or self.es_future_option in data.quote_bars):\n\n self.invested = True\n\n self.market_order(self.es_future, 1)\n self.market_order(self.es_future_option, 1)\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.direction != OrderDirection.SELL or order_event.status != OrderStatus.FILLED:\n return\n\n # * Future Liquidation\n # * Future Option Exercise\n # * We expect NO Underlying Future Liquidation because we already hold a Long future position so the FOP Put selling leaves us breakeven\n self.liquidated += 1\n if order_event.symbol.security_type == SecurityType.FUTURE_OPTION and self.expected_liquidation_time != self.time:\n raise AssertionError(f\"Expected to liquidate option {order_event.symbol} at {self.expected_liquidation_time}, instead liquidated at {self.time}\")\n\n if order_event.symbol.security_type == SecurityType.FUTURE and \\\n (self.expected_liquidation_time - timedelta(minutes=1)) != self.time and \\\n self.expected_liquidation_time != self.time:\n\n raise AssertionError(f\"Expected to liquidate future {order_event.symbol} at {self.expected_liquidation_time} (+1 minute), instead liquidated at {self.time}\")\n\n def on_end_of_algorithm(self):\n if not self.invested:\n raise AssertionError(\"Never invested in ES futures and FOPs\")\n\n if self.delistings_received != 4:\n raise AssertionError(f\"Expected 4 delisting events received, found: {self.delistings_received}\")\n\n if self.liquidated != 2:\n raise AssertionError(f\"Expected 3 liquidation events, found {self.liquidated}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting a default symbol is created using equity market when scheduling if none found", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass DefaultSchedulingSymbolRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n\n # implicitly figured usa equity\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(\"AAPL\"), self._implicit_check)\n\n # picked up from cache\n self.add_index(\"SPX\")\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.before_market_close(\"SPX\", extended_market_close = True), self._explicit_check)\n\n def _implicit_check(self):\n self._implicitChecked = True\n if self.time.time() != time(9, 30, 0):\n raise RegressionTestException(f\"Unexpected time of day {self.time.time()}\")\n\n def _explicit_check(self):\n self._explicitChecked = True\n if self.time.time() != time(16, 15, 0):\n raise RegressionTestException(f\"Unexpected time of day {self.time.time()}\")\n\n def on_end_of_algorithm(self):\n if not self._explicitChecked or not self._implicitChecked:\n raise RegressionTestException(\"Failed to run expected checks!\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to assert the behavior of .", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm\nfrom Risk.MaximumDrawdownPercentPerSecurity import MaximumDrawdownPercentPerSecurity\n\nclass MaximumDrawdownPercentPerSecurityFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):\n\n def initialize(self):\n super().initialize()\n self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA)))\n\n self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.004))\n\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests In The Money (ITM) future option expiry for calls.\nWe expect 3 orders from the algorithm, which are:\n\n * Initial entry, buy ES Call Option (expiring ITM)\n * Option exercise, receiving ES future contracts\n * Future contract liquidation, due to impending expiry\n\nAdditionally, we test delistings for future options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionCallITMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 6, 30)\n\n self.es19m20 = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 6, 19)\n ),\n Resolution.MINUTE).symbol\n\n # Select a future option expiring ITM, and adds it to the algorithm.\n self.es_option = self.add_future_option_contract(\n list(\n sorted([x for x in self.option_chain(self.es19m20) if x.id.strike_price <= 3200.0 and x.id.option_right == OptionRight.CALL],\n key=lambda x: x.id.strike_price, reverse=True)\n )[0], Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200.0, datetime(2020, 6, 19))\n if self.es_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.schedule_callback)\n\n def schedule_callback(self):\n self.market_order(self.es_option, 1)\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2020, 6, 19):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n elif delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2020, 6, 20):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if not self.securities.contains_key(order_event.symbol):\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.es19m20:\n self.assert_future_option_order_exercise(order_event, security, self.securities[self.expected_contract])\n elif security.symbol == self.expected_contract:\n # Expected contract is ES19H21 Call Option expiring ITM @ 3250\n self.assert_future_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n 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}\")\n\n def assert_future_option_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security):\n expected_liquidation_time_utc = datetime(2020, 6, 20, 4, 0, 0)\n\n if order_event.direction == OrderDirection.SELL and future.holdings.quantity != 0:\n # We expect the contract to have been liquidated immediately\n raise AssertionError(f\"Did not liquidate existing holdings for Symbol {future.symbol}\")\n if order_event.direction == OrderDirection.SELL and order_event.utc_time.replace(tzinfo=None) != expected_liquidation_time_utc:\n 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)}\")\n\n # No way to detect option exercise orders or any other kind of special orders\n # other than matching strings, for now.\n if \"Option Exercise\" in order_event.message:\n if order_event.fill_price != 3200.0:\n raise AssertionError(\"Option did not exercise at expected strike price (3200)\")\n\n if future.holdings.quantity != 1:\n # Here, we expect to have some holdings in the underlying, but not in the future option anymore.\n raise AssertionError(f\"Exercised option contract, but we have no holdings for Future {future.symbol}\")\n\n if option_contract.holdings.quantity != 0:\n raise AssertionError(f\"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}\")\n\n def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after a filled option exercise\")\n\n if \"Exercise\" in order_event.message and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after exercising option contract {option.symbol}\")\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting that universe symbols selection can be done by returning the symbol IDs in the selection function", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass SelectUniverseSymbolsFromIDRegressionAlgorithm(QCAlgorithm):\n '''\n Regression algorithm asserting that universe symbols selection can be done by returning the symbol IDs in the selection function\n '''\n\n def initialize(self):\n self.set_start_date(2014, 3, 24)\n self.set_end_date(2014, 3, 26)\n self.set_cash(100000)\n\n self._securities = []\n self.universe_settings.resolution = Resolution.DAILY\n self.add_universe(self.select_symbol)\n\n def select_symbol(self, fundamental):\n symbols = [x.symbol for x in fundamental]\n\n if not symbols:\n return []\n\n self.log(f\"Symbols: {', '.join([str(s) for s in symbols])}\")\n # Just for testing, but more filtering could be done here as shown below:\n #symbols = [x.symbol for x in fundamental if x.asset_classification.morningstar_sector_code == MorningstarSectorCode.TECHNOLOGY]\n\n history = self.history(symbols, datetime(1998, 1, 1), self.time, Resolution.DAILY)\n\n all_time_highs = history['high'].unstack(0).max()\n last_closes = history['close'].unstack(0).iloc[-1]\n security_ids = (last_closes / all_time_highs).sort_values().index[-5:]\n\n return security_ids\n\n def on_securities_changed(self, changes):\n self._securities.extend(changes.added_securities)\n\n def on_end_of_algorithm(self):\n if not self._securities:\n raise AssertionError(\"No securities were selected\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm asserting that the consolidators are removed from the SubscriptionManager.\nThis makes sure that we don't lose references to python consolidators when\nthey are wrapped in a DataConsolidatorPythonWrapper.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ManuallyRemovedConsolidatorsAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n\n self.consolidators = []\n\n self.spy = self.add_equity(\"SPY\").symbol\n\n # Case 1: consolidator registered through a RegisterIndicator() call,\n # which will wrap the consolidator instance in a DataConsolidatorPythonWrapper\n consolidator = self.resolve_consolidator(self.spy, Resolution.MINUTE)\n self.consolidators.append(consolidator)\n\n indicator_name = self.create_indicator_name(self.spy, \"close\", Resolution.MINUTE)\n identity = Identity(indicator_name)\n self.indicator = self.register_indicator(self.spy, identity, consolidator)\n\n # Case 2: consolidator registered directly through the SubscriptionManager\n consolidator = self.resolve_consolidator(self.spy, Resolution.MINUTE)\n self.consolidators.append(consolidator)\n self.subscription_manager.add_consolidator(self.spy, consolidator)\n\n # Case 3: custom python consolidator not derived from IDataConsolidator\n consolidator = CustomQuoteBarConsolidator(timedelta(hours=1))\n self.consolidators.append(consolidator)\n self.subscription_manager.add_consolidator(self.spy, consolidator)\n\n def on_end_of_algorithm(self) -> None:\n # Remove the first consolidator\n\n for i in range(3):\n consolidator = self.consolidators[i]\n self.remove_consolidator(consolidator, expected_consolidator_count=2 - i)\n\n def remove_consolidator(self, consolidator: IDataConsolidator, expected_consolidator_count: int) -> None:\n self.subscription_manager.remove_consolidator(self.spy, consolidator)\n\n consolidator_count = sum(s.consolidators.count for s in self.subscription_manager.subscriptions)\n if consolidator_count != expected_consolidator_count:\n raise AssertionError(f\"Unexpected number of consolidators after removal. \"\n f\"Expected: {expected_consolidator_count}. Actual: {consolidator_count}\")\n\nclass CustomQuoteBarConsolidator(PythonConsolidator):\n '''A custom quote bar consolidator that inherits from PythonConsolidator and implements\n the IDataConsolidator interface, it must implement all of IDataConsolidator. Reference\n PythonConsolidator.cs and DataConsolidatorPythonWrapper.PY for more information.\n\n This class shows how to implement a consolidator from scratch in Python, this gives us more\n freedom to determine the behavior of the consolidator but can't leverage any of the built in\n functions of an inherited class.\n\n For this example we implemented a Quotebar from scratch'''\n\n def __init__(self, period):\n\n #IDataConsolidator required vars for all consolidators\n self.consolidated = None #Most recently consolidated piece of data.\n self.working_data = None #Data being currently consolidated\n self.input_type = QuoteBar #The type consumed by this consolidator\n self.output_type = QuoteBar #The type produced by this consolidator\n\n #Consolidator Variables\n self.period = period\n\n def update(self, data):\n '''Updates this consolidator with the specified data'''\n\n #If we don't have bar yet, create one\n if self.working_data is None:\n self.working_data = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size,\n data.ask,data.last_ask_size,self.period)\n\n #Update bar using QuoteBar's update()\n self.working_data.update(data.value, data.bid.close, data.ask.close, 0,\n data.last_bid_size, data.last_ask_size)\n\n def scan(self, time):\n '''Scans this consolidator to see if it should emit a bar due to time passing'''\n\n if self.period is not None and self.working_data is not None:\n if time - self.working_data.time >= self.period:\n\n #Trigger the event handler with a copy of self and the data\n self.on_data_consolidated(self, self.working_data)\n\n #Set the most recent consolidated piece of data and then clear the working_data\n self.consolidated = self.working_data\n self.working_data = None\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: def initialize(self) -> None:", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nfrom collections import deque\nfrom math import isclose\n\nclass CustomIndicatorWithExtensionAlgorithm(QCAlgorithm):\n def initialize(self) -> None:\n self.set_start_date(2013, 10, 9)\n self.set_end_date(2013, 10, 9)\n\n self._spy = self.add_equity(\"SPY\", Resolution.MINUTE).symbol\n\n self._sma_values = []\n self._period = 10\n\n self._sma = self.sma(self._spy, self._period, Resolution.MINUTE)\n self._sma.updated += self.on_sma_updated\n\n self._custom_sma = CustomSimpleMovingAverage(\"My SMA\", self._period)\n self._ext = IndicatorExtensions.of(self._custom_sma, self._sma)\n self._ext.updated += self.on_indicator_extension_updated\n\n self._sma_minus_custom = IndicatorExtensions.minus(self._sma, self._custom_sma)\n self._sma_minus_custom.updated += self.on_minus_updated\n\n self._sma_was_updated = False\n self._custom_sma_was_updated = False\n self._sma_minus_custom_was_updated = False\n\n def on_sma_updated(self, sender: object, updated: IndicatorDataPoint) -> None:\n self._sma_was_updated = True\n\n if self._sma.is_ready:\n self._sma_values.append(self._sma.current.value)\n\n def on_indicator_extension_updated(self, sender: object, updated: IndicatorDataPoint) -> None:\n self._custom_sma_was_updated = True\n\n sma_last_values = self._sma_values[-self._period:]\n expected = sum(sma_last_values) / len(sma_last_values)\n\n if not isclose(expected, self._custom_sma.value):\n raise AssertionError(f\"Expected the custom SMA to calculate the moving average of the last {self._period} values of the SMA. \"\n f\"Current expected: {expected}. Actual {self._custom_sma.value}.\")\n\n self.debug(f\"{self._sma.current.value} :: {self._custom_sma.value} :: {updated}\")\n\n def on_minus_updated(self, sender: object, updated: IndicatorDataPoint) -> None:\n self._sma_minus_custom_was_updated = True\n\n expected = self._sma.current.value - self._custom_sma.value\n\n if not isclose(expected, self._sma_minus_custom.current.value):\n raise AssertionError(f\"Expected the composite minus indicator to calculate the difference between the SMA and custom SMA indicators. \"\n f\"Expected: {expected}. Actual {self._sma_minus_custom.current.value}.\")\n\n def on_end_of_algorithm(self) -> None:\n if not (self._sma_was_updated and self._custom_sma_was_updated and self._sma_minus_custom_was_updated):\n raise AssertionError(\"Expected all indicators to have been updated.\")\n\n# Custom indicator\nclass CustomSimpleMovingAverage(PythonIndicator):\n def __init__(self, name: str, period: int) -> None:\n self.name = name\n self.value = 0\n self.warm_up_period = period\n self._queue = deque(maxlen=period)\n\n def update(self, input: BaseData) -> bool:\n self._queue.appendleft(input.value)\n count = len(self._queue)\n self.value = sum(self._queue) / count\n\n return count == self._queue.maxlen\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example of custom volatility model", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomVolatilityModelAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2015,7,15) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.equity = self.add_equity(\"SPY\", Resolution.DAILY)\n self.equity.set_volatility_model(CustomVolatilityModel(10))\n\n\n def on_data(self, data):\n if not self.portfolio.invested and self.equity.volatility_model.volatility > 0:\n self.set_holdings(\"SPY\", 1)\n\n\n# Python implementation of StandardDeviationOfReturnsVolatilityModel\n# Computes the annualized sample standard deviation of daily returns as the volatility of the security\n# https://github.com/QuantConnect/Lean/blob/master/Common/Securities/Volatility/StandardDeviationOfReturnsVolatilityModel.cs\nclass CustomVolatilityModel():\n def __init__(self, periods):\n self.last_update = datetime.min\n self.last_price = 0\n self.needs_update = False\n self.period_span = timedelta(1)\n self.window = RollingWindow(periods)\n\n # Volatility is a mandatory attribute\n self.volatility = 0\n\n # Updates this model using the new price information in the specified security instance\n # Update is a mandatory method\n def update(self, security, data):\n time_since_last_update = data.end_time - self.last_update\n if time_since_last_update >= self.period_span and data.price > 0:\n if self.last_price > 0:\n self.window.add(float(data.price / self.last_price) - 1.0)\n self.needs_update = self.window.is_ready\n self.last_update = data.end_time\n self.last_price = data.price\n\n if self.window.count < 2:\n self.volatility = 0\n return\n\n if self.needs_update:\n self.needs_update = False\n std = np.std([ x for x in self.window ])\n self.volatility = std * np.sqrt(252.0)\n\n # Returns history requirements for the volatility model expressed in the form of history request\n # GetHistoryRequirements is a mandatory method\n def get_history_requirements(self, security, utc_time):\n # For simplicity's sake, we will not set a history requirement \n return None\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of how to estimate constituents of QC500 index based on the company fundamentals\nThe algorithm creates a default tradable and liquid universe containing 500 US equities\nwhich are chosen at the first trading day of each month.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ConstituentsQC500GeneratorAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.universe_settings.resolution = Resolution.DAILY\n\n self.set_start_date(2018, 1, 1) # Set Start Date\n self.set_end_date(2019, 1, 1) # Set End Date\n self.set_cash(100000) # Set Strategy Cash\n\n # Add QC500 Universe\n self.add_universe(self.universe.qc_500)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm illustrating how to get a security's industry-standard identifier from its `Symbol`", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndustryStandardSecurityIdentifiersRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2014, 6, 5)\n self.set_end_date(2014, 6, 5)\n\n equity = self.add_equity(\"AAPL\").symbol\n\n cusip = equity.cusip\n composite_figi = equity.composite_figi\n sedol = equity.sedol\n isin = equity.isin\n cik = equity.cik\n\n self.check_symbol_representation(cusip, \"CUSIP\")\n self.check_symbol_representation(composite_figi, \"Composite FIGI\")\n self.check_symbol_representation(sedol, \"SEDOL\")\n self.check_symbol_representation(isin, \"ISIN\")\n self.check_symbol_representation(f\"{cik}\", \"CIK\")\n\n # Check Symbol API vs QCAlgorithm API\n self.check_ap_is_symbol_representations(cusip, self.cusip(equity), \"CUSIP\")\n self.check_ap_is_symbol_representations(composite_figi, self.composite_figi(equity), \"Composite FIGI\")\n self.check_ap_is_symbol_representations(sedol, self.sedol(equity), \"SEDOL\")\n self.check_ap_is_symbol_representations(isin, self.isin(equity), \"ISIN\")\n self.check_ap_is_symbol_representations(f\"{cik}\", f\"{self.cik(equity)}\", \"CIK\")\n\n self.log(f\"\\n_aapl CUSIP: {cusip}\"\n f\"\\n_aapl Composite FIGI: {composite_figi}\"\n f\"\\n_aapl SEDOL: {sedol}\"\n f\"\\n_aapl ISIN: {isin}\"\n f\"\\n_aapl CIK: {cik}\")\n\n def check_symbol_representation(self, symbol: str, standard: str) -> None:\n if not symbol:\n raise AssertionError(f\"{standard} symbol representation is null or empty\")\n\n def check_ap_is_symbol_representations(self, symbol_api_symbol: str, algorithm_api_symbol: str, standard: str) -> None:\n if symbol_api_symbol != algorithm_api_symbol:\n raise AssertionError(f\"Symbol API {standard} symbol representation ({symbol_api_symbol}) does not match \"\n f\"QCAlgorithm API {standard} symbol representation ({algorithm_api_symbol})\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm shows how you can handle universe selection in anyway you like,\nat any time you like. This algorithm has a list of 10 stocks that it rotates\nthrough every hour.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass UserDefinedUniverseAlgorithm(QCAlgorithm):\n\n\tdef initialize(self) -> None:\n\t\tself.set_cash(100000)\n\t\tself.set_start_date(2015, 1, 1)\n\t\tself.set_end_date(2015, 12, 1)\n\t\tself._symbols = [\"SPY\", \"GOOG\", \"IBM\", \"AAPL\", \"MSFT\", \"CSCO\", \"ADBE\", \"WMT\"]\n\n\t\tself.universe_settings.resolution = Resolution.HOUR\n\t\tself.add_universe('my_universe_name', Resolution.HOUR, self.selection)\n\n\tdef selection(self, time: datetime) -> list[str]:\n\t\tindex = time.hour % len(self._symbols)\n\t\treturn [self._symbols[index]]\n\n\tdef on_securities_changed(self, changes: SecurityChanges) -> None:\n\t\tfor removed in changes.removed_securities:\n\t\t\tif removed.invested:\n\t\t\t\tself.liquidate(removed.symbol)\n\n\t\tfor added in changes.added_securities:\n\t\t\tself.set_holdings(added.symbol, 1/len(changes.added_securities))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to assert the behavior of .", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm\nfrom Alphas.HistoricalReturnsAlphaModel import HistoricalReturnsAlphaModel\n\nclass HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):\n\n def initialize(self):\n super().initialize()\n self.set_alpha(HistoricalReturnsAlphaModel())\n\n def on_end_of_algorithm(self):\n expected = 78\n if self.insights.total_count != expected:\n raise AssertionError(f\"The total number of insights should be {expected}. Actual: {self.insights.total_count}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Test algorithm using 'QCAlgorithm.add_alpha_model()'", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AddAlphaModelAlgorithm(QCAlgorithm):\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self.universe_settings.resolution = Resolution.DAILY\n\n spy = Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n fb = Symbol.create(\"FB\", SecurityType.EQUITY, Market.USA)\n ibm = Symbol.create(\"IBM\", SecurityType.EQUITY, Market.USA)\n\n # set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel([ spy, fb, ibm ]))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n\n self.add_alpha(OneTimeAlphaModel(spy))\n self.add_alpha(OneTimeAlphaModel(fb))\n self.add_alpha(OneTimeAlphaModel(ibm))\n\nclass OneTimeAlphaModel(AlphaModel):\n def __init__(self, symbol):\n self.symbol = symbol\n self.triggered = False\n\n def update(self, algorithm, data):\n insights = []\n if not self.triggered:\n self.triggered = True\n insights.append(Insight.price(\n self.symbol,\n Resolution.DAILY,\n 1,\n InsightDirection.DOWN))\n return insights\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Test algorithm using 'ConfidenceWeightedPortfolioConstructionModel' and 'ConstantAlphaModel'\ngenerating a constant 'Insight' with a 0.25 confidence", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ConfidenceWeightedFrameworkAlgorithm(QCAlgorithm):\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.MINUTE\n\n # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.\n # Commented so regression algorithm is more sensitive\n #self.settings.minimum_order_margin_portfolio_percentage = 0.005\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n symbols = [ Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA) ]\n\n # set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel(symbols))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, 0.25))\n self.set_portfolio_construction(ConfidenceWeightedPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n\n def on_end_of_algorithm(self):\n # holdings value should be 0.25 - to avoid price fluctuation issue we compare with 0.28 and 0.23\n if (self.portfolio.total_holdings_value > self.portfolio.total_portfolio_value * 0.28\n or self.portfolio.total_holdings_value < self.portfolio.total_portfolio_value * 0.23):\n raise ValueError(\"Unexpected Total Holdings Value: \" + str(self.portfolio.total_holdings_value))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Custom Consolidator Regression Algorithm shows some examples of how to build custom", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomConsolidatorRegressionAlgorithm(QCAlgorithm):\n '''Custom Consolidator Regression Algorithm shows some examples of how to build custom \n consolidators in Python.'''\n\n def initialize(self):\n self.set_start_date(2013,10,4) \n self.set_end_date(2013,10,11) \n self.set_cash(100000) \n self.add_equity(\"SPY\", Resolution.MINUTE)\n\n #Create 5 day QuoteBarConsolidator; set consolidated function; add to subscription manager\n five_day_consolidator = QuoteBarConsolidator(timedelta(days=5))\n five_day_consolidator.data_consolidated += self.on_quote_bar_data_consolidated\n self.subscription_manager.add_consolidator(\"SPY\", five_day_consolidator)\n\n #Create a 3:10PM custom quote bar consolidator\n timed_consolidator = DailyTimeQuoteBarConsolidator(time(hour=15, minute=10))\n timed_consolidator.data_consolidated += self.on_quote_bar_data_consolidated\n self.subscription_manager.add_consolidator(\"SPY\", timed_consolidator)\n\n #Create our entirely custom 2 day quote bar consolidator\n self.custom_consolidator = CustomQuoteBarConsolidator(timedelta(days=2))\n self.custom_consolidator.data_consolidated += (self.on_quote_bar_data_consolidated)\n self.subscription_manager.add_consolidator(\"SPY\", self.custom_consolidator)\n\n #Create an indicator and register a consolidator to it\n self.moving_average = SimpleMovingAverage(5)\n self.custom_consolidator2 = CustomQuoteBarConsolidator(timedelta(hours=1))\n self.register_indicator(\"SPY\", self.moving_average, self.custom_consolidator2)\n\n\n def on_quote_bar_data_consolidated(self, sender, bar):\n '''Function assigned to be triggered by consolidators.\n Designed to post debug messages to show how the examples work, including\n which consolidator is posting, as well as its values.\n\n If using an inherited class and not overwriting OnDataConsolidated\n we expect to see the super C# class as the sender type.\n\n Using sender.period only works when all consolidators have a Period value.\n '''\n \n consolidator_info = str(type(sender)) + str(sender.period)\n \n self.debug(\"Bar Type: \" + consolidator_info)\n self.debug(\"Bar Range: \" + bar.time.ctime() + \" - \" + bar.end_time.ctime())\n self.debug(\"Bar value: \" + str(bar.close))\n \n def on_data(self, slice):\n test = slice.get_values()\n\n if self.custom_consolidator.consolidated and slice.contains_key(\"SPY\"):\n data = slice['SPY']\n \n if self.moving_average.is_ready:\n if data.value > self.moving_average.current.price:\n self.set_holdings(\"SPY\", .5)\n else :\n self.set_holdings(\"SPY\", 0)\n \n\n\nclass DailyTimeQuoteBarConsolidator(QuoteBarConsolidator):\n '''A custom QuoteBar consolidator that inherits from C# class QuoteBarConsolidator. \n\n This class shows an example of building on top of an existing consolidator class, it is important\n to note that this class can leverage the functions of QuoteBarConsolidator but its private fields\n (_period, _workingbar, etc.) are separate from this Python. For that reason if we want Scan() to work\n we must overwrite the function with our desired Scan function and trigger OnDataConsolidated().\n \n For this particular example we implemented the scan method to trigger a consolidated bar\n at close_time everyday'''\n\n def __init__(self, close_time):\n self.close_time = close_time\n self.working_bar = None\n \n def update(self, data):\n '''Updates this consolidator with the specified data'''\n\n #If we don't have bar yet, create one\n if self.working_bar is None:\n self.working_bar = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size,\n data.ask,data.last_ask_size)\n\n #Update bar using QuoteBarConsolidator's AggregateBar()\n self.aggregate_bar(self.working_bar, data)\n \n\n def scan(self, time):\n '''Scans this consolidator to see if it should emit a bar due yet'''\n\n if self.working_bar is None:\n return\n\n #If its our desired bar end time take the steps to \n if time.hour == self.close_time.hour and time.minute == self.close_time.minute:\n\n #Set end time\n self.working_bar.end_time = time\n\n #Emit event using QuoteBarConsolidator's OnDataConsolidated()\n self.on_data_consolidated(self.working_bar)\n\n #Reset the working bar to None\n self.working_bar = None\n\nclass CustomQuoteBarConsolidator(PythonConsolidator):\n '''A custom quote bar consolidator that inherits from PythonConsolidator and implements \n the IDataConsolidator interface, it must implement all of IDataConsolidator. Reference \n PythonConsolidator.cs and DataConsolidatorPythonWrapper.PY for more information.\n\n This class shows how to implement a consolidator from scratch in Python, this gives us more\n freedom to determine the behavior of the consolidator but can't leverage any of the built in\n functions of an inherited class.\n \n For this example we implemented a Quotebar from scratch'''\n\n def __init__(self, period):\n\n #IDataConsolidator required vars for all consolidators\n self.consolidated = None #Most recently consolidated piece of data.\n self.working_data = None #Data being currently consolidated\n self.input_type = QuoteBar #The type consumed by this consolidator\n self.output_type = QuoteBar #The type produced by this consolidator\n\n #Consolidator Variables\n self.period = period\n \n def update(self, data):\n '''Updates this consolidator with the specified data'''\n \n #If we don't have bar yet, create one\n if self.working_data is None:\n self.working_data = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size,\n data.ask,data.last_ask_size,self.period)\n\n #Update bar using QuoteBar's update()\n self.working_data.update(data.value, data.bid.close, data.ask.close, 0, \n data.last_bid_size, data.last_ask_size)\n\n def scan(self, time):\n '''Scans this consolidator to see if it should emit a bar due to time passing'''\n\n if self.period is not None and self.working_data is not None:\n if time - self.working_data.time >= self.period:\n\n #Trigger the event handler with a copy of self and the data\n self.on_data_consolidated(self, self.working_data)\n\n #Set the most recent consolidated piece of data and then clear the working_data\n self.consolidated = self.working_data\n self.working_data = None\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm which tests a fine fundamental filtered universe,\nrelated to GH issue 4127", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FineFundamentalFilteredUniverseRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2014, 10, 8)\n self.set_end_date(2014, 10, 13)\n\n self.universe_settings.resolution = Resolution.DAILY\n\n symbol = Symbol(SecurityIdentifier.generate_constituent_identifier(\"constituents-universe-qctest\", SecurityType.EQUITY, Market.USA), \"constituents-universe-qctest\")\n self.add_universe(ConstituentsUniverse(symbol, self.universe_settings), self.fine_selection_function)\n\n def fine_selection_function(self, fine):\n 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\" ]\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n if data.keys()[0].value != \"AAPL\":\n raise ValueError(f\"Unexpected symbol was added to the universe: {data.keys()[0]}\")\n self.set_holdings(data.keys()[0], 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: The demonstration algorithm shows some of the most common order methods when working with Crypto assets.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateCryptoAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2018, 4, 4) #Set Start Date\n self.set_end_date(2018, 4, 4) #Set End Date\n\n # Although typically real brokerages as GDAX only support a single account currency,\n # here we add both USD and EUR to demonstrate how to handle non-USD account currencies.\n # Set Strategy Cash (USD)\n self.set_cash(10000)\n\n # Set Strategy Cash (EUR)\n # EUR/USD conversion rate will be updated dynamically\n self.set_cash(\"EUR\", 10000)\n\n # Add some coins as initial holdings\n # When connected to a real brokerage, the amount specified in SetCash\n # will be replaced with the amount in your actual account.\n self.set_cash(\"BTC\", 1)\n self.set_cash(\"ETH\", 5)\n\n self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH)\n\n # You can uncomment the following lines when live trading with GDAX,\n # to ensure limit orders will only be posted to the order book and never executed as a taker (incurring fees).\n # Please note this statement has no effect in backtesting or paper trading.\n # self.default_order_properties = GDAXOrderProperties()\n # self.default_order_properties.post_only = True\n\n # Find more symbols here: http://quantconnect.com/data\n self.add_crypto(\"BTCUSD\", Resolution.MINUTE)\n self.add_crypto(\"ETHUSD\", Resolution.MINUTE)\n self.add_crypto(\"BTCEUR\", Resolution.MINUTE)\n symbol = self.add_crypto(\"LTCUSD\", Resolution.MINUTE).symbol\n\n # create two moving averages\n self.fast = self.ema(symbol, 30, Resolution.MINUTE)\n self.slow = self.ema(symbol, 60, Resolution.MINUTE)\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n\n # Note: all limit orders in this algorithm will be paying taker fees,\n # they shouldn't, but they do (for now) because of this issue:\n # https://github.com/QuantConnect/Lean/issues/1852\n\n if self.time.hour == 1 and self.time.minute == 0:\n # Sell all ETH holdings with a limit order at 1% above the current price\n limit_price = round(self.securities[\"ETHUSD\"].price * 1.01, 2)\n quantity = self.portfolio.cash_book[\"ETH\"].amount\n self.limit_order(\"ETHUSD\", -quantity, limit_price)\n\n elif self.time.hour == 2 and self.time.minute == 0:\n # Submit a buy limit order for BTC at 5% below the current price\n usd_total = self.portfolio.cash_book[\"USD\"].amount\n limit_price = round(self.securities[\"BTCUSD\"].price * 0.95, 2)\n # use only half of our total USD\n quantity = usd_total * 0.5 / limit_price\n self.limit_order(\"BTCUSD\", quantity, limit_price)\n\n elif self.time.hour == 2 and self.time.minute == 1:\n # Get current USD available, subtracting amount reserved for buy open orders\n usd_total = self.portfolio.cash_book[\"USD\"].amount\n usd_reserved = sum(x.quantity * x.limit_price for x\n in [x for x in self.transactions.get_open_orders()\n if x.direction == OrderDirection.BUY\n and x.type == OrderType.LIMIT\n and (x.symbol.value == \"BTCUSD\" or x.symbol.value == \"ETHUSD\")])\n usd_available = usd_total - usd_reserved\n self.debug(\"usd_available: {}\".format(usd_available))\n\n # Submit a marketable buy limit order for ETH at 1% above the current price\n limit_price = round(self.securities[\"ETHUSD\"].price * 1.01, 2)\n\n # use all of our available USD\n quantity = usd_available / limit_price\n\n # this order will be rejected (for now) because of this issue:\n # https://github.com/QuantConnect/Lean/issues/1852\n self.limit_order(\"ETHUSD\", quantity, limit_price)\n\n # use only half of our available USD\n quantity = usd_available * 0.5 / limit_price\n self.limit_order(\"ETHUSD\", quantity, limit_price)\n\n elif self.time.hour == 11 and self.time.minute == 0:\n # Liquidate our BTC holdings (including the initial holding)\n self.set_holdings(\"BTCUSD\", 0)\n\n elif self.time.hour == 12 and self.time.minute == 0:\n # Submit a market buy order for 1 BTC using EUR\n self.buy(\"BTCEUR\", 1)\n\n # Submit a sell limit order at 10% above market price\n limit_price = round(self.securities[\"BTCEUR\"].price * 1.1, 2)\n self.limit_order(\"BTCEUR\", -1, limit_price)\n\n elif self.time.hour == 13 and self.time.minute == 0:\n # Cancel the limit order if not filled\n self.transactions.cancel_open_orders(\"BTCEUR\")\n\n elif self.time.hour > 13:\n # To include any initial holdings, we read the LTC amount from the cashbook\n # instead of using Portfolio[\"LTCUSD\"].quantity\n\n if self.fast > self.slow:\n if self.portfolio.cash_book[\"LTC\"].amount == 0:\n self.buy(\"LTCUSD\", 10)\n else:\n if self.portfolio.cash_book[\"LTC\"].amount > 0:\n self.liquidate(\"LTCUSD\")\n\n def on_order_event(self, order_event):\n self.debug(\"{} {}\".format(self.time, order_event.to_string()))\n\n def on_end_of_algorithm(self):\n self.log(\"{} - TotalPortfolioValue: {}\".format(self.time, self.portfolio.total_portfolio_value))\n self.log(\"{} - CashBook: {}\".format(self.time, self.portfolio.cash_book))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Framework algorithm that uses the PearsonCorrelationPairsTradingAlphaModel.\nThis model extendes BasePairsTradingAlphaModel and uses Pearson correlation\nto rank the pairs trading candidates and use the best candidate to trade.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Alphas.PearsonCorrelationPairsTradingAlphaModel import PearsonCorrelationPairsTradingAlphaModel\n\nclass PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm(QCAlgorithm):\n '''Framework algorithm that uses the PearsonCorrelationPairsTradingAlphaModel.\n This model extendes BasePairsTradingAlphaModel and uses Pearson correlation\n to rank the pairs trading candidates and use the best candidate to trade.'''\n\n def initialize(self):\n\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,11)\n\n symbols = [Symbol.create(ticker, SecurityType.EQUITY, Market.USA)\n for ticker in [\"SPY\", \"AIG\", \"BAC\", \"IBM\"]]\n\n # Manually add SPY and AIG when the algorithm starts\n self.set_universe_selection(ManualUniverseSelectionModel(symbols[:2]))\n\n # At midnight, add all securities every day except on the last data\n # With this procedure, the Alpha Model will experience multiple universe changes\n self.add_universe_selection(ScheduledUniverseSelectionModel(\n self.date_rules.every_day(), self.time_rules.midnight,\n lambda dt: symbols if dt.day <= (self.end_date - timedelta(1)).day else []))\n\n self.set_alpha(PearsonCorrelationPairsTradingAlphaModel(252, Resolution.DAILY))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(NullRiskManagementModel())\n\n def on_end_of_algorithm(self) -> None:\n # We have removed all securities from the universe. The Alpha Model should remove the consolidator\n consolidator_count = sum(s.consolidators.count for s in self.subscription_manager.subscriptions)\n if consolidator_count > 0:\n raise AssertionError(f\"The number of consolidator should be zero. Actual: {consolidator_count}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests In The Money (ITM) future option expiry for short calls.\nWe expect 3 orders from the algorithm, which are:\n\n * Initial entry, sell ES Call Option (expiring ITM)\n * Option assignment, sell 1 contract of the underlying (ES)\n * Future contract expiry, liquidation (buy 1 ES future)\n\nAdditionally, we test delistings for future options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionShortCallITMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 6, 30)\n\n self.es19m20 = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 6, 19)),\n Resolution.MINUTE).symbol\n\n # Select a future option expiring ITM, and adds it to the algorithm.\n self.es_option = self.add_future_option_contract(\n list(\n sorted(\n [x for x in self.option_chain(self.es19m20) if x.id.strike_price <= 3100.0 and x.id.option_right == OptionRight.CALL],\n key=lambda x: x.id.strike_price,\n reverse=True\n )\n )[0], Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3100.0, datetime(2020, 6, 19))\n if self.es_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)\n\n def scheduled_market_order(self):\n self.market_order(self.es_option, -1)\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2020, 6, 19):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2020, 6, 20):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if not self.securities.contains_key(order_event.symbol):\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.es19m20:\n self.assert_future_option_order_exercise(order_event, security, self.securities[self.expected_contract])\n\n elif security.symbol == self.expected_contract:\n self.assert_future_option_contract_order(order_event, security)\n\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n self.log(f\"{order_event}\")\n\n def assert_future_option_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security):\n if \"Assignment\" in order_event.message:\n if order_event.fill_price != 3100.0:\n raise AssertionError(\"Option was not assigned at expected strike price (3100)\")\n\n if order_event.direction != OrderDirection.SELL or future.holdings.quantity != -1:\n raise AssertionError(f\"Expected Qty: -1 futures holdings for assigned future {future.symbol}, found {future.holdings.quantity}\")\n\n return\n\n if order_event.direction == OrderDirection.BUY and future.holdings.quantity != 0:\n # We buy back the underlying at expiration, so we expect a neutral position then\n raise AssertionError(f\"Expected no holdings when liquidating future contract {future.symbol}\")\n\n def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != -1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n\n if order_event.is_assignment and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after option contract was assigned: {option.symbol}\")\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to add futures with daily resolution.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateFuturesDailyAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013, 10, 8)\n self.set_end_date(2014, 10, 10)\n self.set_cash(1000000)\n\n resolution = self.get_resolution()\n extended_market_hours = self.get_extended_market_hours()\n\n # Subscribe and set our expiry filter for the futures chain\n self.future_sp500 = self.add_future(Futures.Indices.SP_500_E_MINI, resolution, extended_market_hours=extended_market_hours)\n self.future_gold = self.add_future(Futures.Metals.GOLD, resolution, extended_market_hours=extended_market_hours)\n\n # set our expiry filter for this futures chain\n # SetFilter method accepts timedelta objects or integer for days.\n # The following statements yield the same filtering criteria\n self.future_sp500.set_filter(timedelta(0), timedelta(182))\n self.future_gold.set_filter(0, 182)\n\n def on_data(self,slice):\n if not self.portfolio.invested:\n for chain in slice.future_chains:\n # Get contracts expiring no earlier than in 90 days\n contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))\n\n # if there is any contract, trade the front contract\n if len(contracts) == 0: continue\n contract = sorted(contracts, key = lambda x: x.expiry)[0]\n\n # if found, trade it.\n self.market_order(contract.symbol, 1)\n # Same as above, check for cases like trading on a friday night.\n elif all(x.exchange.hours.is_open(self.time, True) for x in self.securities.values() if x.invested):\n self.liquidate()\n\n def on_securities_changed(self, changes: SecurityChanges) -> None:\n if len(changes.removed_securities) > 0 and \\\n self.portfolio.invested and \\\n all(x.exchange.hours.is_open(self.time, True) for x in self.securities.values() if x.invested):\n self.liquidate()\n\n def get_resolution(self):\n return Resolution.DAILY\n\n def get_extended_market_hours(self):\n return False\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regrssion algorithm to assert we can update indicators that inherit from IndicatorBase with RenkoBar's", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndicatorWithRenkoBarsRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 9)\n\n self.add_equity(\"SPY\")\n self.add_equity(\"AIG\")\n\n spy_renko_consolidator = RenkoConsolidator(0.1)\n spy_renko_consolidator.data_consolidated += self.on_spy_data_consolidated\n\n aig_renko_consolidator = RenkoConsolidator(0.05)\n aig_renko_consolidator.data_consolidated += self.on_aig_data_consolidated\n\n self.subscription_manager.add_consolidator(\"SPY\", spy_renko_consolidator)\n self.subscription_manager.add_consolidator(\"AIG\", aig_renko_consolidator)\n\n self._mi = MassIndex(\"MassIndex\", 9, 25)\n self._wasi = WilderAccumulativeSwingIndex(\"WilderAccumulativeSwingIndex\", 8)\n self._wsi = WilderSwingIndex(\"WilderSwingIndex\", 8)\n self._b = Beta(\"Beta\", 3, \"AIG\", \"SPY\")\n self._indicators = [self._mi, self._wasi, self._wsi, self._b]\n\n def on_spy_data_consolidated(self, sender: object, renko_bar: RenkoBar) -> None:\n self._mi.update(renko_bar)\n self._wasi.update(renko_bar)\n self._wsi.update(renko_bar)\n self._b.update(renko_bar)\n\n def on_aig_data_consolidated(self, sender: object, renko_bar: RenkoBar) -> None:\n self._b.update(renko_bar)\n\n def on_end_of_algorithm(self) -> None:\n for indicator in self._indicators:\n if not indicator.is_ready:\n raise AssertionError(f\"{indicator.name} indicator should be ready\")\n elif indicator.current.value == 0:\n raise AssertionError(f\"The current value of the {indicator.name} indicator should be different than zero\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Test algorithm using 'QCAlgorithm.add_universe_selection(IUniverseSelectionModel)'", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AddUniverseSelectionModelAlgorithm(QCAlgorithm):\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10,8) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self.universe_settings.resolution = Resolution.DAILY\n\n # set algorithm framework models\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n\n self.set_universe_selection(ManualUniverseSelectionModel([ Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA) ]))\n self.add_universe_selection(ManualUniverseSelectionModel([ Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA) ]))\n self.add_universe_selection(ManualUniverseSelectionModel(\n Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA), # duplicate will be ignored\n Symbol.create(\"FB\", SecurityType.EQUITY, Market.USA)))\n\n def on_end_of_algorithm(self):\n if self.universe_manager.count != 3:\n raise ValueError(\"Unexpected universe count\")\n if self.universe_manager.active_securities.count != 3:\n raise ValueError(\"Unexpected active securities\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm demonstrating the usage of the RSI indicator\nin combination with ETF constituents data to replicate the weighting\nof the ETF's assets in our own account.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ETFConstituentUniverseRSIAlphaModelAlgorithm(QCAlgorithm):\n ### \n ### Initialize the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.\n ### \n def initialize(self):\n self.set_start_date(2020, 12, 1)\n self.set_end_date(2021, 1, 31)\n self.set_cash(100000)\n\n self.set_alpha(ConstituentWeightedRsiAlphaModel())\n self.set_portfolio_construction(InsightWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n\n spy = self.add_equity(\"SPY\", Resolution.HOUR).symbol\n\n # We load hourly data for ETF constituents in this algorithm\n self.universe_settings.resolution = Resolution.HOUR\n self.settings.minimum_order_margin_portfolio_percentage = 0.01\n\n self.add_universe(self.universe.etf(spy, self.universe_settings, self.filter_etf_constituents))\n\n ### \n ### Filters ETF constituents\n ### \n ### ETF constituents\n ### ETF constituent Symbols that we want to include in the algorithm\n def filter_etf_constituents(self, constituents):\n return [i.symbol for i in constituents if i.weight is not None and i.weight >= 0.001]\n\n\nclass ConstituentWeightedRsiAlphaModel(AlphaModel):\n def __init__(self, max_trades=None):\n self.rsi_symbol_data = {}\n\n def update(self, algorithm: QCAlgorithm, data: Slice):\n algo_constituents = []\n for bar_symbol in data.bars.keys():\n if not algorithm.securities[bar_symbol].cache.has_data(ETFConstituentUniverse):\n continue\n\n constituent_data = algorithm.securities[bar_symbol].cache.get_data(ETFConstituentUniverse)\n algo_constituents.append(constituent_data)\n\n if len(algo_constituents) == 0 or len(data.bars) == 0:\n # Don't do anything if we have no data we can work with\n return []\n\n constituents = {i.symbol:i for i in algo_constituents}\n\n for bar in data.bars.values():\n if bar.symbol not in constituents:\n # Dealing with a manually added equity, which in this case is SPY\n continue\n\n if bar.symbol not in self.rsi_symbol_data:\n # First time we're initializing the RSI.\n # It won't be ready now, but it will be\n # after 7 data points\n constituent = constituents[bar.symbol]\n self.rsi_symbol_data[bar.symbol] = SymbolData(bar.symbol, algorithm, constituent, 7)\n\n all_ready = all([sd.rsi.is_ready for sd in self.rsi_symbol_data.values()])\n if not all_ready:\n # We're still warming up the RSI indicators.\n return []\n\n insights = []\n\n for symbol, symbol_data in self.rsi_symbol_data.items():\n average_loss = symbol_data.rsi.average_loss.current.value\n average_gain = symbol_data.rsi.average_gain.current.value\n\n # If we've lost more than gained, then we think it's going to go down more\n direction = InsightDirection.DOWN if average_loss > average_gain else InsightDirection.UP\n\n # Set the weight of the insight as the weight of the ETF's\n # holding. The InsightWeightingPortfolioConstructionModel\n # will rebalance our portfolio to have the same percentage\n # of holdings in our algorithm that the ETF has.\n insights.append(Insight.price(\n symbol,\n timedelta(days=1),\n direction,\n float(average_loss if direction == InsightDirection.DOWN else average_gain),\n weight=float(symbol_data.constituent.weight)\n ))\n \n return insights\n\n\nclass SymbolData:\n def __init__(self, symbol, algorithm, constituent, period):\n self.symbol = symbol\n self.constituent = constituent\n self.rsi = algorithm.rsi(symbol, period, MovingAverageType.EXPONENTIAL, Resolution.HOUR)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests using FutureOptions daily resolution", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionDailyRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 1, 7)\n self.set_end_date(2020, 1, 8)\n resolution = Resolution.DAILY\n\n # Add our underlying future contract\n self.es = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 3, 20)\n ),\n resolution).symbol\n\n # Attempt to fetch a specific ITM future option contract\n es_options = [\n self.add_future_option_contract(x, resolution).symbol\n for x in self.option_chain(self.es)\n if x.id.strike_price == 3200 and x.id.option_right == OptionRight.CALL\n ]\n self.es_option = es_options[0]\n\n # Validate it is the expected contract\n expected_contract = Symbol.create_option(self.es, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200, datetime(2020, 3, 20))\n if self.es_option != expected_contract:\n raise AssertionError(f\"Contract {self.es_option} was not the expected contract {expected_contract}\")\n\n # Schedule a purchase of this contract tomorrow at 10AM when the market is open\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.at(10,0,0), self.schedule_callback_buy)\n\n # Schedule liquidation at 2pm tomorrow when the market is open\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.at(14,0,0), self.schedule_callback_liquidate)\n\n def schedule_callback_buy(self):\n self.market_order(self.es_option, 1)\n\n def on_data(self, slice):\n # Assert we are only getting data at 4PM NY, for ES future market closes at 16pm NY\n if slice.time.hour != 17:\n raise AssertionError(f\"Expected data at 5PM each day; instead was {slice.time}\")\n\n def schedule_callback_liquidate(self):\n self.liquidate()\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Test algorithm using 'InsightWeightingPortfolioConstructionModel' and 'ConstantAlphaModel'\ngenerating a constant 'Insight' with a 0.25 weight", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nfrom Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel\nfrom Alphas.ConstantAlphaModel import ConstantAlphaModel\nfrom Portfolio.InsightWeightingPortfolioConstructionModel import InsightWeightingPortfolioConstructionModel\nfrom Execution.ImmediateExecutionModel import ImmediateExecutionModel\n\nclass InsightWeightingFrameworkAlgorithm(QCAlgorithm):\n\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.MINUTE\n\n # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.\n # Commented so regression algorithm is more sensitive\n #self.settings.minimum_order_margin_portfolio_percentage = 0.005\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n symbols = [ Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA) ]\n\n # set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel(symbols))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None, 0.25))\n self.set_portfolio_construction(InsightWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n\n def on_end_of_algorithm(self):\n # holdings value should be 0.25 - to avoid price fluctuation issue we compare with 0.28 and 0.23\n if (self.portfolio.total_holdings_value > self.portfolio.total_portfolio_value * 0.28\n or self.portfolio.total_holdings_value < self.portfolio.total_portfolio_value * 0.23):\n raise ValueError(\"Unexpected Total Holdings Value: \" + str(self.portfolio.total_holdings_value))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of how to access the statistics results from within an algorithm through the `Statistics` property.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nfrom System.Collections.Generic import Dictionary\n\nclass StatisticsResultsAlgorithm(QCAlgorithm):\n\n most_traded_security_statistic = \"Most Traded Security\"\n most_traded_security_trade_count_statistic = \"Most Traded Security Trade Count\"\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(100000)\n\n self.spy = self.add_equity(\"SPY\", Resolution.MINUTE).symbol\n self.ibm = self.add_equity(\"IBM\", Resolution.MINUTE).symbol\n\n self.fast_spy_ema = self.ema(self.spy, 30, Resolution.MINUTE)\n self.slow_spy_ema = self.ema(self.spy, 60, Resolution.MINUTE)\n\n self.fast_ibm_ema = self.ema(self.spy, 10, Resolution.MINUTE)\n self.slow_ibm_ema = self.ema(self.spy, 30, Resolution.MINUTE)\n\n self.trade_counts = {self.spy: 0, self.ibm: 0}\n\n def on_data(self, data: Slice):\n if not self.slow_spy_ema.is_ready: return\n\n if self.fast_spy_ema > self.slow_spy_ema:\n self.set_holdings(self.spy, 0.5)\n elif self.securities[self.spy].invested:\n self.liquidate(self.spy)\n\n if self.fast_ibm_ema > self.slow_ibm_ema:\n self.set_holdings(self.ibm, 0.2)\n elif self.securities[self.ibm].invested:\n self.liquidate(self.ibm)\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n # We can access the statistics summary at runtime\n statistics = self.statistics.summary\n statistics_str = \"\".join([f\"{kvp.key}: {kvp.value}\" for kvp in statistics])\n self.debug(f\"Statistics after fill:{statistics_str}\")\n\n # Access a single statistic\n self.log(f\"Total trades so far: {statistics[PerformanceMetrics.TOTAL_ORDERS]}\")\n self.log(f\"Sharpe Ratio: {statistics[PerformanceMetrics.SHARPE_RATIO]}\")\n\n # --------\n\n # We can also set custom summary statistics:\n\n if all(count == 0 for count in self.trade_counts.values()):\n if StatisticsResultsAlgorithm.most_traded_security_statistic in statistics:\n raise AssertionError(f\"Statistic {StatisticsResultsAlgorithm.most_traded_security_statistic} should not be set yet\")\n if StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic in statistics:\n raise AssertionError(f\"Statistic {StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic} should not be set yet\")\n else:\n # The current most traded security should be set in the summary\n most_trade_security, most_trade_security_trade_count = self.get_most_trade_security()\n self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count)\n\n # Update the trade count\n self.trade_counts[order_event.symbol] += 1\n\n # Set the most traded security\n most_trade_security, most_trade_security_trade_count = self.get_most_trade_security()\n self.set_summary_statistic(StatisticsResultsAlgorithm.most_traded_security_statistic, str(most_trade_security))\n self.set_summary_statistic(StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic, most_trade_security_trade_count)\n\n # Re-calculate statistics:\n statistics = self.statistics.summary\n\n # Let's keep track of our custom summary statistics after the update\n self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count)\n\n def on_end_of_algorithm(self):\n statistics = self.statistics.summary\n if StatisticsResultsAlgorithm.most_traded_security_statistic not in statistics:\n raise AssertionError(f\"Statistic {StatisticsResultsAlgorithm.most_traded_security_statistic} should be in the summary statistics\")\n if StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic not in statistics:\n raise AssertionError(f\"Statistic {StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic} should be in the summary statistics\")\n\n most_trade_security, most_trade_security_trade_count = self.get_most_trade_security()\n self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count)\n\n def check_most_traded_security_statistic(self, statistics: Dictionary[str, str], most_traded_security: Symbol, trade_count: int):\n most_traded_security_statistic = statistics[StatisticsResultsAlgorithm.most_traded_security_statistic]\n most_traded_security_trade_count_statistic = statistics[StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic]\n self.log(f\"Most traded security: {most_traded_security_statistic}\")\n self.log(f\"Most traded security trade count: {most_traded_security_trade_count_statistic}\")\n\n if most_traded_security_statistic != most_traded_security:\n raise AssertionError(f\"Most traded security should be {most_traded_security} but it is {most_traded_security_statistic}\")\n\n if most_traded_security_trade_count_statistic != str(trade_count):\n raise AssertionError(f\"Most traded security trade count should be {trade_count} but it is {most_traded_security_trade_count_statistic}\")\n\n def get_most_trade_security(self) -> tuple[Symbol, int]:\n most_trade_security = max(self.trade_counts, key=lambda symbol: self.trade_counts[symbol])\n most_trade_security_trade_count = self.trade_counts[most_trade_security]\n return most_trade_security, most_trade_security_trade_count\n\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm of using RiskParityPortfolioConstructionModel", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Portfolio.RiskParityPortfolioConstructionModel import *\n\nclass RiskParityPortfolioAlgorithm(QCAlgorithm):\n '''Example algorithm of using RiskParityPortfolioConstructionModel'''\n\n def initialize(self):\n self.set_start_date(2021, 2, 21) # Set Start Date\n self.set_end_date(2021, 3, 30)\n self.set_cash(100000) # Set Strategy Cash\n self.set_security_initializer(lambda security: security.set_market_price(self.get_last_known_price(security)))\n\n self.add_equity(\"SPY\", Resolution.DAILY)\n self.add_equity(\"AAPL\", Resolution.DAILY)\n\n self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))\n self.set_portfolio_construction(RiskParityPortfolioConstructionModel())\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Custom data universe selection regression algorithm asserting it's behavior. Similar to CustomDataUniverseRegressionAlgorithm but with a custom schedule", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomDataUniverseScheduledRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2014, 3, 24)\n self.set_end_date(2014, 3, 31)\n\n self.current_underlying_symbols = []\n self._selection_time = [datetime(2014, 3, 25), datetime(2014, 3, 27), datetime(2014, 3, 29)]\n self.universe_settings.resolution = Resolution.DAILY\n self.universe_settings.schedule.on(self.date_rules.on(self._selection_time))\n self.add_universe(CoarseFundamental, \"custom-data-universe\", self.universe_settings, self.selection)\n\n # This use case is also valid/same because it will use the algorithm settings by default\n # self.add_universe(CoarseFundamental, \"custom-data-universe\", self.selection)\n\n def selection(self, coarse):\n self.debug(f\"Universe selection called: {self.time} Count: {len(coarse)}\")\n\n expected_time = self._selection_time.pop(0)\n if expected_time != self.time:\n raise ValueError(f\"Unexpected selection time {self.time} expected {expected_time}\")\n\n # sort descending by daily dollar volume\n sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)\n\n # return the symbol objects of the top entries from our sorted collection\n underlying_symbols = [ x.symbol for x in sorted_by_dollar_volume[:10] ]\n custom_symbols = []\n for symbol in underlying_symbols:\n custom_symbols.append(Symbol.create_base(MyPyCustomData, symbol))\n return underlying_symbols + custom_symbols\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n custom_data = data.get(MyPyCustomData)\n if len(custom_data) > 0:\n for symbol in self.current_underlying_symbols:\n self.set_holdings(symbol, 1 / len(self.current_underlying_symbols))\n\n if len([x for x in custom_data.keys() if x.underlying == symbol]) == 0:\n raise ValueError(f\"Custom data was not found for symbol {symbol}\")\n # equity daily data arrives at 16 pm but custom data is set to arrive at midnight\n self.current_underlying_symbols = [symbol for symbol in data.keys() if symbol.security_type is SecurityType.EQUITY]\n\n def on_end_of_algorithm(self):\n if len(self._selection_time) != 0:\n raise ValueError(f\"Unexpected selection times, missing {len(self._selection_time)}\")\n\nclass MyPyCustomData(PythonData):\n\n def get_source(self, config, date, is_live_mode):\n source = f\"{Globals.data_folder}/equity/usa/daily/{LeanData.generate_zip_file_name(config.symbol, date, config.resolution, config.tick_type)}\"\n return SubscriptionDataSource(source)\n\n def reader(self, config, line, date, is_live_mode):\n csv = line.split(',')\n _scaleFactor = 1 / 10000\n\n custom = MyPyCustomData()\n custom.symbol = config.symbol\n custom.time = datetime.strptime(csv[0], '%Y%m%d %H:%M')\n custom.open = float(csv[1]) * _scaleFactor\n custom.high = float(csv[2]) * _scaleFactor\n custom.low = float(csv[3]) * _scaleFactor\n custom.close = float(csv[4]) * _scaleFactor\n custom.value = float(csv[4]) * _scaleFactor\n custom.period = Time.ONE_DAY\n custom.end_time = custom.time + custom.period\n\n return custom\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: A demonstration of consolidating futures data into larger bars for your algorithm.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateFuturesConsolidationAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(1000000)\n\n # Subscribe and set our expiry filter for the futures chain\n futureSP500 = self.add_future(Futures.Indices.SP_500_E_MINI)\n # set our expiry filter for this future chain\n # SetFilter method accepts timedelta objects or integer for days.\n # The following statements yield the same filtering criteria\n futureSP500.set_filter(0, 182)\n # future.set_filter(timedelta(0), timedelta(182))\n\n self.consolidators = dict()\n\n def on_data(self,slice):\n pass\n\n def on_data_consolidated(self, sender, quote_bar):\n self.log(\"OnDataConsolidated called on \" + str(self.time))\n self.log(str(quote_bar))\n \n def on_securities_changed(self, changes):\n for security in changes.added_securities:\n consolidator = QuoteBarConsolidator(timedelta(minutes=5))\n consolidator.data_consolidated += self.on_data_consolidated\n self.subscription_manager.add_consolidator(security.symbol, consolidator)\n self.consolidators[security.symbol] = consolidator\n \n for security in changes.removed_securities:\n consolidator = self.consolidators.pop(security.symbol)\n self.subscription_manager.remove_consolidator(security.symbol, consolidator)\n consolidator.data_consolidated -= self.on_data_consolidated\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration algorithm of indicators history window usage", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndicatorHistoryAlgorithm(QCAlgorithm):\n '''Demonstration algorithm of indicators history window usage.'''\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2013, 1, 1)\n self.set_end_date(2014, 12, 31)\n self.set_cash(25000)\n\n self._symbol = self.add_equity(\"SPY\", Resolution.DAILY).symbol\n\n self.bollinger_bands = self.bb(self._symbol, 20, 2.0, resolution=Resolution.DAILY)\n # Let's keep BB values for a 20 day period\n self.bollinger_bands.window.size = 20\n # Also keep the same period of data for the middle band\n self.bollinger_bands.middle_band.window.size = 20\n\n def on_data(self, slice: Slice):\n # Let's wait for our indicator to fully initialize and have a full window of history data\n if not self.bollinger_bands.window.is_ready: return\n\n # We can access the current and oldest (in our period) values of the indicator\n self.log(f\"Current BB value: {self.bollinger_bands[0].end_time} - {self.bollinger_bands[0].value}\")\n self.log(f\"Oldest BB value: {self.bollinger_bands[self.bollinger_bands.window.count - 1].end_time} - \"\n f\"{self.bollinger_bands[self.bollinger_bands.window.count - 1].value}\")\n\n # Let's log the BB values for the last 20 days, for demonstration purposes on how it can be enumerated\n for data_point in self.bollinger_bands:\n self.log(f\"BB @{data_point.end_time}: {data_point.value}\")\n\n # We can also do the same for internal indicators:\n middle_band = self.bollinger_bands.middle_band\n self.log(f\"Current BB Middle Band value: {middle_band[0].end_time} - {middle_band[0].value}\")\n self.log(f\"Oldest BB Middle Band value: {middle_band[middle_band.window.count - 1].end_time} - \"\n f\"{middle_band[middle_band.window.count - 1].value}\")\n for data_point in middle_band:\n self.log(f\"BB Middle Band @{data_point.end_time}: {data_point.value}\")\n\n # We are done now!\n self.quit()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template algorithm simply initializes the date range and cash", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass LimitFillRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\", Resolution.SECOND)\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n if data.contains_key(\"SPY\"):\n if self.is_round_hour(self.time):\n negative = 1 if self.time < (self.start_date + timedelta(days=2)) else -1\n self.limit_order(\"SPY\", negative*10, data[\"SPY\"].price)\n\n def is_round_hour(self, date_time):\n '''Verify whether datetime is round hour'''\n return date_time.minute == 0 and date_time.second == 0\n\n def on_order_event(self, order_event):\n self.debug(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting the behavior of auxiliary data history requests", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass HistoryAuxiliaryDataRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2021, 1, 1)\n self.set_end_date(2021, 1, 5)\n\n aapl = self.add_equity(\"AAPL\", Resolution.DAILY).symbol\n\n # multi symbol request\n spy = Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n multi_symbol_request = self.history(Dividend, [ aapl, spy ], 360, Resolution.DAILY)\n if len(multi_symbol_request) != 12:\n raise ValueError(f\"Unexpected multi symbol dividend count: {len(multi_symbol_request)}\")\n\n # continuous future mapping requests\n sp500 = Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME)\n continuous_future_open_interest_mapping = self.history(SymbolChangedEvent, sp500, datetime(2007, 1, 1), datetime(2012, 1, 1), data_mapping_mode = DataMappingMode.OPEN_INTEREST)\n if len(continuous_future_open_interest_mapping) != 9:\n raise ValueError(f\"Unexpected continuous future mapping event count: {len(continuous_future_open_interest_mapping)}\")\n continuous_future_last_trading_day_mapping = self.history(SymbolChangedEvent, sp500, datetime(2007, 1, 1), datetime(2012, 1, 1), data_mapping_mode = DataMappingMode.LAST_TRADING_DAY)\n if len(continuous_future_last_trading_day_mapping) != 9:\n raise ValueError(f\"Unexpected continuous future mapping event count: {len(continuous_future_last_trading_day_mapping)}\")\n\n dividend = self.history(Dividend, aapl, 360)\n self.debug(str(dividend))\n if len(dividend) != 6:\n raise ValueError(f\"Unexpected dividend count: {len(dividend)}\")\n for distribution in dividend.distribution:\n if distribution == 0:\n raise ValueError(f\"Unexpected distribution: {distribution}\")\n\n split = self.history(Split, aapl, 360)\n self.debug(str(split))\n if len(split) != 2:\n raise ValueError(f\"Unexpected split count: {len(split)}\")\n for splitfactor in split.splitfactor:\n if splitfactor == 0:\n raise ValueError(f\"Unexpected splitfactor: {splitfactor}\")\n\n symbol = Symbol.create(\"BTCUSD\", SecurityType.CRYPTO_FUTURE, Market.BINANCE)\n margin_interest = self.history(MarginInterestRate, symbol, 24 * 3, Resolution.HOUR)\n self.debug(str(margin_interest))\n if len(margin_interest) != 8:\n raise ValueError(f\"Unexpected margin interest count: {len(margin_interest)}\")\n for interestrate in margin_interest.interestrate:\n if interestrate == 0:\n raise ValueError(f\"Unexpected interestrate: {interestrate}\")\n\n # last trading date on 2007-05-18\n delisted_symbol = Symbol.create(\"AAA.1\", SecurityType.EQUITY, Market.USA)\n delistings = self.history(Delisting, delisted_symbol, datetime(2007, 5, 15), datetime(2007, 5, 21))\n self.debug(str(delistings))\n if len(delistings) != 2:\n raise ValueError(f\"Unexpected delistings count: {len(delistings)}\")\n if delistings.iloc[0].type != DelistingType.WARNING:\n raise ValueError(f\"Unexpected delisting: {delistings.iloc[0]}\")\n if delistings.iloc[1].type != DelistingType.DELISTED:\n raise ValueError(f\"Unexpected delisting: {delistings.iloc[1]}\")\n\n # get's remapped:\n # 2008-09-30 spwr -> spwra\n # 2011-11-17 spwra -> spwr\n remapped_symbol = Symbol.create(\"SPWR\", SecurityType.EQUITY, Market.USA)\n symbol_changed_events = self.history(SymbolChangedEvent, remapped_symbol, datetime(2007, 1, 1), datetime(2012, 1, 1))\n self.debug(str(symbol_changed_events))\n if len(symbol_changed_events) != 2:\n raise ValueError(f\"Unexpected SymbolChangedEvents count: {len(symbol_changed_events)}\")\n first_event = symbol_changed_events.iloc[0]\n if first_event.oldsymbol != \"SPWR\" or first_event.newsymbol != \"SPWRA\" or symbol_changed_events.index[0][1] != datetime(2008, 9, 30):\n raise ValueError(f\"Unexpected SymbolChangedEvents: {first_event}\")\n second_event = symbol_changed_events.iloc[1]\n if second_event.newsymbol != \"SPWR\" or second_event.oldsymbol != \"SPWRA\" or symbol_changed_events.index[1][1] != datetime(2011, 11, 17):\n raise ValueError(f\"Unexpected SymbolChangedEvents: {second_event}\")\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(\"AAPL\", 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm demonstrates how to submit orders to a Financial Advisor account group, allocation profile or a single managed account.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FinancialAdvisorDemoAlgorithm(QCAlgorithm):\n\n def initialize(self):\n # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must be initialized.\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self._symbol = self.add_equity(\"SPY\", Resolution.SECOND).symbol\n\n # The default order properties can be set here to choose the FA settings\n # to be automatically used in any order submission method (such as SetHoldings, Buy, Sell and Order)\n\n # Use a default FA Account Group with an Allocation Method\n self.default_order_properties = InteractiveBrokersOrderProperties()\n # account group created manually in IB/TWS\n self.default_order_properties.fa_group = \"TestGroupEQ\"\n # supported allocation methods are: EqualQuantity, NetLiq, AvailableEquity, PctChange\n self.default_order_properties.fa_method = \"EqualQuantity\"\n\n # set a default FA Allocation Profile\n # DefaultOrderProperties = InteractiveBrokersOrderProperties()\n # allocation profile created manually in IB/TWS\n # self.default_order_properties.fa_profile = \"TestProfileP\"\n\n # send all orders to a single managed account\n # DefaultOrderProperties = InteractiveBrokersOrderProperties()\n # a sub-account linked to the Financial Advisor master account\n # self.default_order_properties.account = \"DU123456\"\n\n def on_data(self, data):\n # on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n if not self.portfolio.invested:\n # when logged into IB as a Financial Advisor, this call will use order properties\n # set in the DefaultOrderProperties property of QCAlgorithm\n self.set_holdings(\"SPY\", 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Provides a regression baseline focused on updating orders", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom math import copysign\n\nclass UpdateOrderRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,1,1) #Set Start Date\n self.set_end_date(2015,1,1) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n\n self.security = self.add_equity(\"SPY\", Resolution.DAILY)\n\n self.last_month = -1\n self.quantity = 100\n self.delta_quantity = 10\n\n self.stop_percentage = 0.025\n self.stop_percentage_delta = 0.005\n self.limit_percentage = 0.025\n self.limit_percentage_delta = 0.005\n\n order_type_enum = [OrderType.MARKET, OrderType.LIMIT, OrderType.STOP_MARKET, OrderType.STOP_LIMIT, OrderType.MARKET_ON_OPEN, OrderType.MARKET_ON_CLOSE, OrderType.TRAILING_STOP]\n self.order_types_queue = CircularQueue[OrderType](order_type_enum)\n self.order_types_queue.circle_completed += self.on_circle_completed\n self.tickets = []\n\n\n def on_circle_completed(self, sender, event):\n '''Flip our signs when we've gone through all the order types'''\n self.quantity *= -1\n\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n if not data.bars.contains_key(\"SPY\"):\n return\n\n if self.time.month != self.last_month:\n # we'll submit the next type of order from the queue\n order_type = self.order_types_queue.dequeue()\n self.log(\"\\r\\n--------------MONTH: {0}:: {1}\".format(self.time.strftime(\"%B\"), order_type))\n self.last_month = self.time.month\n self.log(\"ORDER TYPE:: {0}\".format(order_type))\n is_long = self.quantity > 0\n stop_price = (1 + self.stop_percentage)*data[\"SPY\"].high if is_long else (1 - self.stop_percentage)*data[\"SPY\"].low\n limit_price = (1 - self.limit_percentage)*stop_price if is_long else (1 + self.limit_percentage)*stop_price\n\n if order_type == OrderType.LIMIT:\n limit_price = (1 + self.limit_percentage)*data[\"SPY\"].high if not is_long else (1 - self.limit_percentage)*data[\"SPY\"].low\n\n request = SubmitOrderRequest(order_type, self.security.symbol.security_type, \"SPY\", self.quantity, stop_price, limit_price, 0, 0.01, True,\n self.utc_time, str(int(order_type)))\n ticket = self.transactions.add_order(request)\n self.tickets.append(ticket)\n\n elif len(self.tickets) > 0:\n ticket = self.tickets[-1]\n\n if self.time.day > 8 and self.time.day < 14:\n if len(ticket.update_requests) == 0 and ticket.status is not OrderStatus.FILLED:\n self.log(\"TICKET:: {0}\".format(ticket))\n update_order_fields = UpdateOrderFields()\n update_order_fields.quantity = ticket.quantity + copysign(self.delta_quantity, self.quantity)\n update_order_fields.tag = \"Change quantity: {0}\".format(self.time.day)\n ticket.update(update_order_fields)\n\n elif self.time.day > 13 and self.time.day < 20:\n if len(ticket.update_requests) == 1 and ticket.status is not OrderStatus.FILLED:\n self.log(\"TICKET:: {0}\".format(ticket))\n update_order_fields = UpdateOrderFields()\n update_order_fields.limit_price = self.security.price*(1 - copysign(self.limit_percentage_delta, ticket.quantity))\n update_order_fields.stop_price = self.security.price*(1 + copysign(self.stop_percentage_delta, ticket.quantity)) if ticket.order_type != OrderType.TRAILING_STOP else None\n update_order_fields.tag = \"Change prices: {0}\".format(self.time.day)\n ticket.update(update_order_fields)\n else:\n if len(ticket.update_requests) == 2 and ticket.status is not OrderStatus.FILLED:\n self.log(\"TICKET:: {0}\".format(ticket))\n ticket.cancel(\"{0} and is still open!\".format(self.time.day))\n self.log(\"CANCELLED:: {0}\".format(ticket.cancel_request))\n\n\n def on_order_event(self, orderEvent):\n order = self.transactions.get_order_by_id(orderEvent.order_id)\n ticket = self.transactions.get_order_ticket(orderEvent.order_id)\n\n #order cancelations update CanceledTime\n if order.status == OrderStatus.CANCELED and order.canceled_time != orderEvent.utc_time:\n raise ValueError(\"Expected canceled order CanceledTime to equal canceled order event time.\")\n\n #fills update LastFillTime\n if (order.status == OrderStatus.FILLED or order.status == OrderStatus.PARTIALLY_FILLED) and order.last_fill_time != orderEvent.utc_time:\n raise ValueError(\"Expected filled order LastFillTime to equal fill order event time.\")\n\n # check the ticket to see if the update was successfully processed\n if len([ur for ur in ticket.update_requests if ur.response is not None and ur.response.is_success]) > 0 and order.created_time != self.utc_time and order.last_update_time is None:\n raise ValueError(\"Expected updated order LastUpdateTime to equal submitted update order event time\")\n\n if orderEvent.status == OrderStatus.FILLED:\n self.log(\"FILLED:: {0} FILL PRICE:: {1}\".format(self.transactions.get_order_by_id(orderEvent.order_id), orderEvent.fill_price))\n else:\n self.log(orderEvent.to_string())\n self.log(\"TICKET:: {0}\".format(ticket))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm for trading continuous future", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateFutureRolloverAlgorithm(QCAlgorithm):\n\n ### \n ### Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.\n ### \n def initialize(self):\n self.set_start_date(2013, 10, 8)\n self.set_end_date(2013, 12, 10)\n self.set_cash(1000000)\n\n self._symbol_data_by_symbol = {}\n \n futures = [\n Futures.Indices.SP_500_E_MINI\n ]\n\n for future in futures:\n # Requesting data\n continuous_contract = self.add_future(future,\n resolution = Resolution.DAILY,\n extended_market_hours = True,\n data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,\n data_mapping_mode = DataMappingMode.OPEN_INTEREST,\n contract_depth_offset = 0\n )\n \n symbol_data = SymbolData(self, continuous_contract)\n self._symbol_data_by_symbol[continuous_contract.symbol] = symbol_data\n\n ### \n ### on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n ### \n ### Slice object keyed by symbol containing the stock data\n def on_data(self, slice):\n for symbol, symbol_data in self._symbol_data_by_symbol.items():\n # Call SymbolData.update() method to handle new data slice received\n symbol_data.update(slice)\n \n # Check if information in SymbolData class and new slice data are ready for trading\n if not symbol_data.is_ready or not slice.bars.contains_key(symbol):\n return\n \n ema_current_value = symbol_data.EMA.current.value\n if ema_current_value < symbol_data.price and not symbol_data.is_long:\n self.market_order(symbol_data.mapped, 1)\n elif ema_current_value > symbol_data.price and not symbol_data.is_short:\n self.market_order(symbol_data.mapped, -1)\n \nclass SymbolData:\n \n ### \n ### Constructor to instantiate the information needed to be hold\n ### \n def __init__(self, algorithm, future):\n self._algorithm = algorithm\n self._future = future\n self.EMA = algorithm.ema(future.symbol, 20, Resolution.DAILY)\n self.price = 0\n self.is_long = False\n self.is_short = False\n\n self.reset()\n \n @property\n def symbol(self):\n return self._future.symbol\n \n @property\n def mapped(self):\n return self._future.mapped\n \n @property\n def is_ready(self):\n return self.mapped is not None and self.EMA.is_ready\n \n ### \n ### Handler of new slice of data received\n ### \n def update(self, slice):\n if slice.symbol_changed_events.contains_key(self.symbol):\n changed_event = slice.symbol_changed_events[self.symbol]\n old_symbol = changed_event.old_symbol\n new_symbol = changed_event.new_symbol\n tag = f\"Rollover - Symbol changed at {self._algorithm.time}: {old_symbol} -> {new_symbol}\"\n quantity = self._algorithm.portfolio[old_symbol].quantity\n\n # Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract\n self._algorithm.liquidate(old_symbol, tag = tag)\n self._algorithm.market_order(new_symbol, quantity, tag = tag)\n\n self.reset()\n \n self.price = slice.bars[self.symbol].price if slice.bars.contains_key(self.symbol) else self.price\n self.is_long = self._algorithm.portfolio[self.mapped].is_long\n self.is_short = self._algorithm.portfolio[self.mapped].is_short\n \n ### \n ### reset RollingWindow/indicator to adapt to newly mapped contract, then warm up the RollingWindow/indicator\n ### \n def reset(self):\n self.EMA.reset()\n self._algorithm.warm_up_indicator(self.symbol, self.EMA, Resolution.DAILY)\n \n ### \n ### disposal method to remove consolidator/update method handler, and reset RollingWindow/indicator to free up memory and speed\n ### \n def dispose(self):\n self.EMA.reset()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Continuous Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ContinuousFutureRegressionAlgorithm(QCAlgorithm):\n '''Basic template algorithm simply initializes the date range and cash'''\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013, 7, 1)\n self.set_end_date(2014, 1, 1)\n\n self._previous_mapped_contract_symbols = []\n self._last_date_log = -1\n self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI,\n data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,\n data_mapping_mode = DataMappingMode.LAST_TRADING_DAY,\n contract_depth_offset= 0)\n self._current_mapped_symbol = self._continuous_contract.symbol\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n currently_mapped_security = self.securities[self._continuous_contract.mapped]\n if len(data.keys()) != 1:\n raise ValueError(f\"We are getting data for more than one symbols! {','.join(data.keys())}\")\n\n for changed_event in data.symbol_changed_events.values():\n if changed_event.symbol == self._continuous_contract.symbol:\n self._previous_mapped_contract_symbols.append(self.symbol(changed_event.old_symbol))\n self.log(f\"SymbolChanged event: {changed_event}\")\n\n if self._current_mapped_symbol == self._continuous_contract.mapped:\n raise ValueError(f\"Continuous contract current symbol did not change! {self._continuous_contract.mapped}\")\n\n if self._last_date_log != self.time.month and currently_mapped_security.has_data:\n self._last_date_log = self.time.month\n\n self.log(f\"{self.time}- {currently_mapped_security.get_last_data()}\")\n if self.portfolio.invested:\n self.liquidate()\n else:\n # This works because we set this contract as tradable, even if it's a canonical security\n self.buy(currently_mapped_security.symbol, 1)\n\n if self.time.month == 1 and self.time.year == 2013:\n response = self.history( [ self._continuous_contract.symbol ], 60 * 24 * 90)\n if response.empty:\n raise ValueError(\"Unexpected empty history response\")\n\n self._current_mapped_symbol = self._continuous_contract.mapped\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n self.debug(\"Purchased Stock: {0}\".format(order_event.symbol))\n\n def on_securities_changed(self, changes):\n self.debug(f\"{self.time}-{changes}\")\n\n def on_end_of_algorithm(self):\n expected_mapping_counts = 2\n if len(self._previous_mapped_contract_symbols) != expected_mapping_counts:\n raise ValueError(f\"Unexpected symbol changed events: {len(self._previous_mapped_contract_symbols)}, was expecting {expected_mapping_counts}\")\n\n delisted_securities = [\n [security for security in self.securities.total if security.symbol == symbol][0]\n for symbol in self._previous_mapped_contract_symbols\n ]\n marked_delisted_securities = [security for security in delisted_securities if security.is_delisted and not security.is_tradable]\n if len(marked_delisted_securities) != len(delisted_securities):\n raise ValueError(f\"Not all delisted contracts are properly marked as delisted and non-tradable: \"\n f\"only {len(marked_delisted_securities)} are marked, was expecting {len(delisted_securities)}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to test we can specify a custom benchmark model, and override some of its methods", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom CustomBrokerageModelRegressionAlgorithm import CustomBrokerageModel\n\nclass CustomBenchmarkRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,11)\n self.set_brokerage_model(CustomBrokerageModelWithCustomBenchmark())\n self.add_equity(\"SPY\", Resolution.DAILY)\n self.update_request_submitted = False\n\n def on_data(self, slice):\n benchmark = self.benchmark.evaluate(self.time)\n if (self.time.day % 2 == 0) and (benchmark != 1):\n raise AssertionError(f\"Benchmark should be 1, but was {benchmark}\")\n\n if (self.time.day % 2 == 1) and (benchmark != 2):\n raise AssertionError(f\"Benchmark should be 2, but was {benchmark}\")\n\nclass CustomBenchmark:\n def evaluate(self, time):\n if time.day % 2 == 0:\n return 1\n else:\n return 2\n\nclass CustomBrokerageModelWithCustomBenchmark(CustomBrokerageModel):\n def get_benchmark(self, securities):\n return CustomBenchmark()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm demonstrates the various ways you can call the History function,\nwhat it returns, and what you can do with the returned values.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass HistoryAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013,10, 8) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\", Resolution.DAILY)\n IBM = self.add_data(CustomDataEquity, \"IBM\", Resolution.DAILY)\n # specifying the exchange will allow the history methods that accept a number of bars to return to work properly\n IBM.Exchange = EquityExchange()\n\n # we can get history in initialize to set up indicators and such\n self.daily_sma = SimpleMovingAverage(14)\n\n # get the last calendar year's worth of SPY data at the configured resolution (daily)\n trade_bar_history = self.history([self.securities[\"SPY\"].symbol], timedelta(365))\n self.assert_history_count(\"History([\\\"SPY\\\"], timedelta(365))\", trade_bar_history, 250)\n\n # get the last calendar day's worth of SPY data at the specified resolution\n trade_bar_history = self.history([\"SPY\"], timedelta(1), Resolution.MINUTE)\n self.assert_history_count(\"History([\\\"SPY\\\"], timedelta(1), Resolution.MINUTE)\", trade_bar_history, 390)\n\n # get the last 14 bars of SPY at the configured resolution (daily)\n trade_bar_history = self.history([\"SPY\"], 14)\n self.assert_history_count(\"History([\\\"SPY\\\"], 14)\", trade_bar_history, 14)\n\n # get the last 14 minute bars of SPY\n trade_bar_history = self.history([\"SPY\"], 14, Resolution.MINUTE)\n self.assert_history_count(\"History([\\\"SPY\\\"], 14, Resolution.MINUTE)\", trade_bar_history, 14)\n\n # get the historical data from last current day to this current day in minute resolution\n # with Fill Forward and Extended Market options\n interval_bar_history = self.history([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, True)\n self.assert_history_count(\"History([\\\"SPY\\\"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, True)\", interval_bar_history, 960)\n\n # get the historical data from last current day to this current day in minute resolution\n # with Extended Market option\n interval_bar_history = self.history([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, True)\n self.assert_history_count(\"History([\\\"SPY\\\"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, True)\", interval_bar_history, 919)\n\n # get the historical data from last current day to this current day in minute resolution\n # with Fill Forward option\n interval_bar_history = self.history([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, False)\n self.assert_history_count(\"History([\\\"SPY\\\"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, False)\", interval_bar_history, 390)\n\n # get the historical data from last current day to this current day in minute resolution\n interval_bar_history = self.history([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, False)\n self.assert_history_count(\"History([\\\"SPY\\\"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, False)\", interval_bar_history, 390)\n\n # we can loop over the return value from these functions and we get TradeBars\n # we can use these TradeBars to initialize indicators or perform other math\n for index, trade_bar in trade_bar_history.loc[\"SPY\"].iterrows():\n self.daily_sma.update(index, trade_bar[\"close\"])\n\n # get the last calendar year's worth of custom_data data at the configured resolution (daily)\n custom_data_history = self.history(CustomDataEquity, \"IBM\", timedelta(365))\n self.assert_history_count(\"History(CustomDataEquity, \\\"IBM\\\", timedelta(365))\", custom_data_history, 250)\n\n # get the last 10 bars of IBM at the configured resolution (daily)\n custom_data_history = self.history(CustomDataEquity, \"IBM\", 14)\n self.assert_history_count(\"History(CustomDataEquity, \\\"IBM\\\", 14)\", custom_data_history, 14)\n\n # we can loop over the return values from these functions and we'll get Custom data\n # this can be used in much the same way as the trade_bar_history above\n self.daily_sma.reset()\n for index, custom_data in custom_data_history.loc[\"IBM\"].iterrows():\n self.daily_sma.update(index, custom_data[\"value\"])\n\n # get the last 10 bars worth of Custom data for the specified symbols at the configured resolution (daily)\n all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14)\n self.assert_history_count(\"History(CustomDataEquity, self.securities.keys(), 14)\", all_custom_data, 14 * 2)\n\n # NOTE: Using different resolutions require that they are properly implemented in your data type. If your\n # custom data source has different resolutions, it would need to be implemented in the GetSource and \n # Reader methods properly.\n #custom_data_history = self.history(CustomDataEquity, \"IBM\", timedelta(7), Resolution.MINUTE)\n #custom_data_history = self.history(CustomDataEquity, \"IBM\", 14, Resolution.MINUTE)\n #all_custom_data = self.history(CustomDataEquity, timedelta(365), Resolution.MINUTE)\n #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14, Resolution.MINUTE)\n #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), timedelta(1), Resolution.MINUTE)\n #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14, Resolution.MINUTE)\n\n # get the last calendar year's worth of all custom_data data\n all_custom_data = self.history(CustomDataEquity, self.securities.keys(), timedelta(365))\n self.assert_history_count(\"History(CustomDataEquity, self.securities.keys(), timedelta(365))\", all_custom_data, 250 * 2)\n\n # we can also access the return value from the multiple symbol functions to request a single\n # symbol and then loop over it\n single_symbol_custom = all_custom_data.loc[\"IBM\"]\n self.assert_history_count(\"all_custom_data.loc[\\\"IBM\\\"]\", single_symbol_custom, 250)\n for custom_data in single_symbol_custom:\n # do something with 'IBM.custom_data_equity' custom_data data\n pass\n\n custom_data_spyvalues = all_custom_data.loc[\"IBM\"][\"value\"]\n self.assert_history_count(\"all_custom_data.loc[\\\"IBM\\\"][\\\"value\\\"]\", custom_data_spyvalues, 250)\n for value in custom_data_spyvalues:\n # do something with 'IBM.custom_data_equity' value data\n pass\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n\n def assert_history_count(self, method_call, trade_bar_history, expected):\n count = len(trade_bar_history.index)\n if count != expected:\n raise AssertionError(\"{} expected {}, but received {}\".format(method_call, expected, count))\n\n\nclass CustomDataEquity(PythonData):\n def get_source(self, config, date, is_live):\n zip_file_name = LeanData.generate_zip_file_name(config.Symbol, date, config.Resolution, config.TickType)\n source = Globals.data_folder + \"/equity/usa/daily/\" + zip_file_name\n return SubscriptionDataSource(source)\n\n def reader(self, config, line, date, is_live):\n if line == None:\n return None\n\n custom_data = CustomDataEquity()\n custom_data.symbol = config.symbol\n\n csv = line.split(\",\")\n custom_data.time = datetime.strptime(csv[0], '%Y%m%d %H:%M')\n custom_data.end_time = custom_data.time + timedelta(days=1)\n custom_data.value = float(csv[1])\n return custom_data\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm demonstrates extended market hours trading.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ExtendedMarketTradingRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.spy = self.add_equity(\"SPY\", Resolution.MINUTE, Market.USA, True, 1, True)\n\n self._last_action = None\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n if self._last_action is not None and self._last_action.date() == self.time.date():\n return\n\n spy_bar = data.bars['SPY']\n\n if not self.in_market_hours():\n self.limit_order(\"SPY\", 10, spy_bar.low)\n self._last_action = self.time\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n if self.in_market_hours():\n raise AssertionError(\"Order processed during market hours.\")\n\n def in_market_hours(self):\n now = self.time.time()\n open = time(9,30,0)\n close = time(16,0,0)\n return (open < now) and (close > now)\n\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example algorithm defines its own custom coarse/fine fundamental selection model\nwith sector weighted portfolio.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass SectorWeightingFrameworkAlgorithm(QCAlgorithm):\n '''This example algorithm defines its own custom coarse/fine fundamental selection model\n with sector weighted portfolio.'''\n\n def initialize(self):\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.DAILY\n\n self.set_start_date(2014, 4, 2)\n self.set_end_date(2014, 4, 6)\n self.set_cash(100000)\n\n # set algorithm framework models\n self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.select_coarse, self.select_fine))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))\n self.set_portfolio_construction(SectorWeightingPortfolioConstructionModel())\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n self.debug(f\"Order event: {order_event}. Holding value: {self.securities[order_event.symbol].holdings.absolute_holdings_value}\")\n\n def select_coarse(self, coarse):\n # IndustryTemplateCode of AAPL, IBM and GOOG is N, AIG is I, BAC is B. SPY have no fundamentals\n tickers = [\"AAPL\", \"AIG\", \"IBM\"] if self.time.date() < date(2014, 4, 4) else [ \"GOOG\", \"BAC\", \"SPY\" ]\n return [Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers]\n\n def select_fine(self, fine):\n return [f.symbol for f in fine]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm testing portfolio construction model control over rebalancing,\nspecifying a custom rebalance function that returns null in some cases, see GH 4075.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass PortfolioRebalanceOnCustomFuncRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.universe_settings.resolution = Resolution.DAILY\n\n # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.\n # Commented so regression algorithm is more sensitive\n #self.settings.minimum_order_margin_portfolio_percentage = 0.005\n\n self.set_start_date(2015, 1, 1)\n self.set_end_date(2018, 1, 1)\n\n self.settings.rebalance_portfolio_on_insight_changes = False\n self.settings.rebalance_portfolio_on_security_changes = False\n\n self.set_universe_selection(CustomUniverseSelectionModel(\"CustomUniverseSelectionModel\", lambda time: [ \"AAPL\", \"IBM\", \"FB\", \"SPY\", \"AIG\", \"BAC\", \"BNO\" ]))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, TimeSpan.from_minutes(20), 0.025, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(self.rebalance_function))\n self.set_execution(ImmediateExecutionModel())\n self.last_rebalance_time = self.start_date\n\n def rebalance_function(self, time):\n # for performance only run rebalance logic once a week, monday\n if time.weekday() != 0:\n return None\n\n if self.last_rebalance_time == self.start_date:\n # initial rebalance\n self.last_rebalance_time = time\n return time\n\n deviation = 0\n count = sum(1 for security in self.securities.values() if security.invested)\n if count > 0:\n self.last_rebalance_time = time\n portfolio_value_per_security = self.portfolio.total_portfolio_value / count\n for security in self.securities.values():\n if not security.invested:\n continue\n reserved_buying_power_for_current_position = (security.buying_power_model.get_reserved_buying_power_for_position(\n ReservedBuyingPowerForPositionParameters(security)).absolute_used_buying_power\n * security.buying_power_model.get_leverage(security)) # see GH issue 4107\n # we sum up deviation for each security\n deviation += (portfolio_value_per_security - reserved_buying_power_for_current_position) / portfolio_value_per_security\n\n # if securities are deviated 1.5% from their theoretical share of TotalPortfolioValue we rebalance\n if deviation >= 0.015:\n return time\n return None\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.SUBMITTED:\n if self.utc_time != self.last_rebalance_time or self.utc_time.weekday() != 0:\n raise ValueError(f\"{self.utc_time} {order_event.symbol}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm illustrating how to request history data for different data mapping modes.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass HistoryWithDifferentDataMappingModeRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 6)\n self.set_end_date(2014, 1, 1)\n self._continuous_contract_symbol = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.DAILY).symbol\n\n def on_end_of_algorithm(self):\n history_results = [\n self.history([self._continuous_contract_symbol], self.start_date, self.end_date, Resolution.DAILY, data_mapping_mode=data_mapping_mode)\n .droplevel(0, axis=0)\n .loc[self._continuous_contract_symbol]\n .close\n for data_mapping_mode in DataMappingMode\n ]\n\n if any(x.size != history_results[0].size for x in history_results):\n raise AssertionError(\"History results bar count did not match\")\n\n # Check that close prices at each time are different for different data mapping modes\n for j in range(history_results[0].size):\n close_prices = set(history_results[i][j] for i in range(len(history_results)))\n if len(close_prices) != len(DataMappingMode):\n raise AssertionError(\"History results close prices should have been different for each data mapping mode at each time\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to assert the behavior of .", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm\nfrom Risk.MaximumSectorExposureRiskManagementModel import MaximumSectorExposureRiskManagementModel\n\nclass MaximumSectorExposureRiskManagementModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):\n\n def initialize(self):\n super().initialize()\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.DAILY\n\n self.set_start_date(2014, 2, 1) #Set Start Date\n self.set_end_date(2014, 5, 1) #Set End Date\n\n # set algorithm framework models\n tickers = [ \"AAPL\", \"MSFT\", \"GOOG\", \"AIG\", \"BAC\" ]\n self.set_universe_selection(FineFundamentalUniverseSelectionModel(\n lambda coarse: [ x.symbol for x in coarse if x.symbol.value in tickers ],\n lambda fine: [ x.symbol for x in fine ]\n ))\n\n # define risk management model such that maximum weight of a single sector be 10%\n # Number of of trades changed from 34 to 30 when using the MaximumSectorExposureRiskManagementModel\n self.set_risk_management(MaximumSectorExposureRiskManagementModel(0.1))\n\n def on_end_of_algorithm(self):\n pass\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests In The Money (ITM) future option expiry for puts.\nWe expect 3 orders from the algorithm, which are:\n\n * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1)\n * Option exercise, receiving short ES future contracts (sell, qty -1)\n * Future contract liquidation, due to impending expiry (buy qty 1)\n\nAdditionally, we test delistings for future options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionPutITMExpiryRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 6, 30)\n\n self.es19m20 = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 6, 19)\n ),\n Resolution.MINUTE).symbol\n\n # Select a future option expiring ITM, and adds it to the algorithm.\n self.es_option = self.add_future_option_contract(\n list(\n sorted([x for x in self.option_chain(self.es19m20) if x.id.strike_price >= 3300.0 and x.id.option_right == OptionRight.PUT],\n key=lambda x: x.id.strike_price)\n )[0], Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3300.0, datetime(2020, 6, 19))\n if self.es_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.schedule_callback)\n\n def schedule_callback(self):\n self.market_order(self.es_option, 1)\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2020, 6, 19):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n elif delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2020, 6, 20):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if not self.securities.contains_key(order_event.symbol):\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.es19m20:\n self.assert_future_option_order_exercise(order_event, security, self.securities[self.expected_contract])\n elif security.symbol == self.expected_contract:\n # Expected contract is ES19M20 Call Option expiring ITM @ 3250\n self.assert_future_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n 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}\")\n\n def assert_future_option_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security):\n expected_liquidation_time_utc = datetime(2020, 6, 20, 4, 0, 0)\n\n if order_event.direction == OrderDirection.BUY and future.holdings.quantity != 0:\n # We expect the contract to have been liquidated immediately\n raise AssertionError(f\"Did not liquidate existing holdings for Symbol {future.symbol}\")\n if order_event.direction == OrderDirection.BUY and order_event.utc_time.replace(tzinfo=None) != expected_liquidation_time_utc:\n 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)}\")\n\n # No way to detect option exercise orders or any other kind of special orders\n # other than matching strings, for now.\n if \"Option Exercise\" in order_event.message:\n if order_event.fill_price != 3300.0:\n raise AssertionError(\"Option did not exercise at expected strike price (3300)\")\n\n if future.holdings.quantity != -1:\n # Here, we expect to have some holdings in the underlying, but not in the future option anymore.\n raise AssertionError(f\"Exercised option contract, but we have no holdings for Future {future.symbol}\")\n\n if option_contract.holdings.quantity != 0:\n raise AssertionError(f\"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}\")\n\n def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after a filled option exercise\")\n\n if \"Exercise\" in order_event.message and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after exercising option contract {option.symbol}\")\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: A demonstration of consolidating options data into larger bars for your algorithm.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateOptionsConsolidationAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(1000000)\n\n # Subscribe and set our filter for the options chain\n option = self.add_option('SPY')\n # set our strike/expiry filter for this option chain\n # SetFilter method accepts timedelta objects or integer for days.\n # The following statements yield the same filtering criteria\n option.set_filter(-2, +2, 0, 180)\n # option.set_filter(-2, +2, timedelta(0), timedelta(180))\n self.consolidators = dict()\n\n def on_quote_bar_consolidated(self, sender, quote_bar):\n self.log(\"OnQuoteBarConsolidated called on \" + str(self.time))\n self.log(str(quote_bar))\n\n def on_trade_bar_consolidated(self, sender, trade_bar):\n self.log(\"OnTradeBarConsolidated called on \" + str(self.time))\n self.log(str(trade_bar))\n\n def on_securities_changed(self, changes):\n for security in changes.added_securities:\n if security.type == SecurityType.EQUITY:\n trade_bar_consolidator = TradeBarConsolidator(timedelta(minutes=5))\n trade_bar_consolidator.data_consolidated += self.on_trade_bar_consolidated\n self.subscription_manager.add_consolidator(security.symbol, trade_bar_consolidator)\n self.consolidators[security.symbol] = trade_bar_consolidator\n else:\n quote_bar_consolidator = QuoteBarConsolidator(timedelta(minutes=5))\n quote_bar_consolidator.data_consolidated += self.on_quote_bar_consolidated\n self.subscription_manager.add_consolidator(security.symbol, quote_bar_consolidator)\n self.consolidators[security.symbol] = quote_bar_consolidator\n\n for security in changes.removed_securities:\n consolidator = self.consolidators.pop(security.symbol)\n self.subscription_manager.remove_consolidator(security.symbol, consolidator)\n\n if security.type == SecurityType.EQUITY:\n consolidator.data_consolidated -= self.on_trade_bar_consolidated\n else:\n consolidator.data_consolidated -= self.on_quote_bar_consolidated\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm demonstrating and ensuring that Bybit crypto brokerage model works as expected with custom data types", "output": "```python\n\n\nfrom datetime import time\nimport os\nfrom AlgorithmImports import *\n\nclass BybitCustomDataCryptoRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n self.set_start_date(2022, 12, 13)\n self.set_end_date(2022, 12, 13)\n\n self.set_account_currency(\"USDT\")\n self.set_cash(100000)\n\n self.set_brokerage_model(BrokerageName.BYBIT, AccountType.CASH)\n\n symbol = self.add_crypto(\"BTCUSDT\").symbol\n self._btc_usdt = self.add_data(CustomCryptoData, symbol, Resolution.MINUTE).symbol\n\n # create two moving averages\n self._fast = self.ema(self._btc_usdt, 30, Resolution.MINUTE)\n self._slow = self.ema(self._btc_usdt, 60, Resolution.MINUTE)\n\n def on_data(self, data: Slice) -> None:\n if not self._slow.is_ready:\n return\n\n if self._fast.current.value > self._slow.current.value:\n if self.transactions.orders_count == 0:\n self.buy(self._btc_usdt, 1)\n else:\n if self.transactions.orders_count == 1:\n self.liquidate(self._btc_usdt)\n\n def on_order_event(self, order_event: OrderEvent) -> None:\n self.debug(f\"{self.time} {order_event}\")\n\nclass CustomCryptoData(PythonData):\n def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:\n tick_type_string = Extensions.tick_type_to_lower(config.tick_type)\n formatted_date = date.strftime(\"%Y%m%d\")\n source = os.path.join(Globals.data_folder, \"crypto\", \"bybit\", \"minute\",\n config.symbol.value.lower(), f\"{formatted_date}_{tick_type_string}.zip\")\n\n return SubscriptionDataSource(source, SubscriptionTransportMedium.LOCAL_FILE, FileFormat.CSV)\n\n def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> BaseData:\n csv = line.split(',')\n\n data = CustomCryptoData()\n data.symbol = config.symbol\n\n data_datetime = datetime.combine(date.date(), time()) + timedelta(milliseconds=int(csv[0]))\n data.time = Extensions.convert_to(data_datetime, config.data_time_zone, config.exchange_time_zone)\n data.end_time = data.time + timedelta(minutes=1)\n\n data[\"Open\"] = float(csv[1])\n data[\"High\"] = float(csv[2])\n data[\"Low\"] = float(csv[3])\n data[\"Close\"] = float(csv[4])\n data[\"Volume\"] = float(csv[5])\n data.value = float(csv[4])\n\n return data\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This base algorithm demonstrates how to use OptionStrategies helper class to batch send orders for common strategies.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom QuantConnect.Securities.Positions import IPositionGroup\n\nclass OptionStrategyFactoryMethodsBaseAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n self.set_cash(1000000)\n\n option = self.add_option(\"GOOG\")\n self._option_symbol = option.symbol\n\n option.set_filter(-2, +2, 0, 180)\n\n self.set_benchmark(\"GOOG\")\n\n def on_data(self, slice):\n if not self.portfolio.invested:\n chain = slice.option_chains.get(self._option_symbol)\n if chain is not None:\n self.trade_strategy(chain, self._option_symbol)\n else:\n # Verify that the strategy was traded\n position_group = list(self.portfolio.positions.groups)[0]\n\n buying_power_model = position_group.buying_power_model\n if not isinstance(buying_power_model, OptionStrategyPositionGroupBuyingPowerModel):\n raise AssertionError(\"Expected position group buying power model type: OptionStrategyPositionGroupBuyingPowerModel. \"\n f\"Actual: {type(position_group.buying_power_model).__name__}\")\n\n self.assert_strategy_position_group(position_group, self._option_symbol)\n\n # Now we should be able to close the position\n self.liquidate_strategy()\n\n # We can quit now, no more testing required\n self.quit()\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(\"Expected no holdings at end of algorithm\")\n\n orders_count = len(list(self.transactions.get_orders(lambda order: order.status == OrderStatus.FILLED)))\n if orders_count != self.expected_orders_count():\n raise AssertionError(f\"Expected {self.expected_orders_count()} orders to have been submitted and filled, \"\n f\"half for buying the strategy and the other half for the liquidation. Actual {orders_count}\")\n\n def expected_orders_count(self) -> int:\n raise NotImplementedError(\"ExpectedOrdersCount method is not implemented\")\n\n def trade_strategy(self, chain: OptionChain, option_symbol: Symbol) -> None:\n raise NotImplementedError(\"TradeStrategy method is not implemented\")\n\n def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol) -> None:\n raise NotImplementedError(\"AssertStrategyPositionGroup method is not implemented\")\n\n def liquidate_strategy(self) -> None:\n raise NotImplementedError(\"LiquidateStrategy method is not implemented\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example algorithm shows how to import and use Tiingo daily prices data.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom QuantConnect.Data.Custom.Tiingo import TiingoPrice\n\nclass TiingoPriceAlgorithm(QCAlgorithm):\n\n def initialize(self):\n # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.\n self.set_start_date(2017, 1, 1)\n self.set_end_date(2017, 12, 31)\n self.set_cash(100000)\n\n # Set your Tiingo API Token here\n Tiingo.set_auth_code(\"my-tiingo-api-token\")\n\n self._equity = self.add_equity(\"AAPL\").symbol\n self._aapl = self.add_data(TiingoPrice, self._equity, Resolution.DAILY).symbol\n\n self._ema_fast = self.ema(self._equity, 5)\n self._ema_slow = self.ema(self._equity, 10)\n\n\n def on_data(self, slice):\n # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n if not slice.contains_key(self._equity): return\n\n # Extract Tiingo data from the slice\n row = slice[self._equity]\n\n if not row:\n return\n\n if self._ema_fast.is_ready and self._ema_slow.is_ready:\n self.log(f\"{self.time} - {row.symbol.value} - {row.close} {row.value} {row.price} - EmaFast:{self._ema_fast} - EmaSlow:{self._ema_slow}\")\n\n # Simple EMA cross\n if not self.portfolio.invested and self._ema_fast > self._ema_slow:\n self.set_holdings(self._equity, 1)\n\n elif self.portfolio.invested and self._ema_fast < self._ema_slow:\n self.liquidate(self._equity)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm reproducing GH issue #5921. Asserting a security can be warmup correctly on initialize", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass SecuritySeederRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 8)\n self.set_end_date(2013,10,10)\n\n self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model,\n FuncSecuritySeeder(self.get_last_known_prices)))\n self.add_equity(\"SPY\", Resolution.MINUTE)\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n\n def on_securities_changed(self, changes):\n for added_security in changes.added_securities:\n if not added_security.has_data \\\n or added_security.ask_price == 0 \\\n or added_security.bid_price == 0 \\\n or added_security.bid_size == 0 \\\n or added_security.ask_size == 0 \\\n or added_security.price == 0 \\\n or added_security.volume == 0 \\\n or added_security.high == 0 \\\n or added_security.low == 0 \\\n or added_security.open == 0 \\\n or added_security.close == 0:\n raise ValueError(f\"Security {added_security.symbol} was not warmed up!\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of payments for cash dividends in backtesting. When data normalization mode is set\nto \"Raw\" the dividends are paid as cash directly into your portfolio.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass DividendAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(1998,1,1) #Set Start Date\n self.set_end_date(2006,1,21) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n equity = self.add_equity(\"MSFT\", Resolution.DAILY)\n equity.set_data_normalization_mode(DataNormalizationMode.RAW)\n\n # this will use the Tradier Brokerage open order split behavior\n # forward split will modify open order to maintain order value\n # reverse split open orders will be cancelled\n self.set_brokerage_model(BrokerageName.TRADIER_BROKERAGE)\n\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n bar = data[\"MSFT\"]\n if self.transactions.orders_count == 0:\n self.set_holdings(\"MSFT\", .5)\n # place some orders that won't fill, when the split comes in they'll get modified to reflect the split\n quantity = self.calculate_order_quantity(\"MSFT\", .25)\n self.debug(f\"Purchased Stock: {bar.price}\")\n self.stop_market_order(\"MSFT\", -quantity, bar.low/2)\n self.limit_order(\"MSFT\", -quantity, bar.high*2)\n\n if data.dividends.contains_key(\"MSFT\"):\n dividend = data.dividends[\"MSFT\"]\n self.log(f\"{self.time} >> DIVIDEND >> {dividend.symbol} - {dividend.distribution} - {self.portfolio.cash} - {self.portfolio['MSFT'].price}\")\n\n if data.splits.contains_key(\"MSFT\"):\n split = data.splits[\"MSFT\"]\n self.log(f\"{self.time} >> SPLIT >> {split.symbol} - {split.split_factor} - {self.portfolio.cash} - {self.portfolio['MSFT'].price}\")\n\n def on_order_event(self, order_event):\n # orders get adjusted based on split events to maintain order value\n order = self.transactions.get_order_by_id(order_event.order_id)\n self.log(f\"{self.time} >> ORDER >> {order}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests Out of The Money (OTM) index option expiry for calls.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, buy SPX Call Option (expiring OTM)\n - contract expires worthless, not exercised, so never opened a position in the underlying\n\n * Liquidation of worthless SPX call option (expiring OTM)\n\nAdditionally, we test delistings for index options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndexOptionCallOTMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 1, 31)\n\n self.spx = self.add_index(\"SPX\", Resolution.MINUTE).symbol\n\n # Select a index option call expiring OTM, and adds it to the algorithm.\n self.spx_options = list(self.option_chain(self.spx))\n self.spx_options = [i for i in self.spx_options if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1]\n self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price, reverse=True))[0]\n self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(\n self.spx,\n Market.USA,\n OptionStyle.EUROPEAN,\n OptionRight.PUT,\n 3200,\n datetime(2021, 1, 15)\n )\n\n if self.spx_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(\n self.date_rules.tomorrow,\n self.time_rules.after_market_open(self.spx, 1),\n lambda: self.market_order(self.spx_option, 1)\n )\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2021, 1, 15):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2021, 1, 16):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if order_event.symbol not in self.securities:\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.spx:\n raise AssertionError(\"Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM\")\n\n if security.symbol == self.expected_contract:\n self.assert_index_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:\n raise AssertionError(\"Holdings were found after a filled option exercise\")\n if order_event.direction == OrderDirection.SELL and not \"OTM\" in order_event.message:\n raise AssertionError(\"Contract did not expire OTM\")\n if \"Exercise\" in order_event.message:\n raise AssertionError(\"Exercised option, even though it expires OTM\")\n\n ### \n ### Ran at the end of the algorithm to ensure the algorithm has no holdings\n ### \n ### The algorithm has holdings\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm checks if all the option chain data coming to the algo is consistent with current securities manager state", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionChainConsistencyRegressionAlgorithm(QCAlgorithm):\n\n underlying_ticker = \"GOOG\"\n\n def initialize(self):\n\n self.set_cash(10000)\n self.set_start_date(2015,12,24)\n self.set_end_date(2015,12,24)\n\n self.equity = self.add_equity(self.underlying_ticker)\n self.option = self.add_option(self.underlying_ticker)\n\n # set our strike/expiry filter for this option chain\n self.option.set_filter(self.universe_func)\n\n self.set_benchmark(self.equity.symbol)\n\n def on_data(self, slice):\n if self.portfolio.invested: return\n for kvp in slice.option_chains:\n chain = kvp.value\n for o in chain:\n if not self.securities.contains_key(o.symbol):\n self.log(\"Inconsistency found: option chains contains contract {0} that is not available in securities manager and not available for trading\".format(o.symbol.value)) \n\n contracts = filter(lambda x: x.expiry.date() == self.time.date() and\n x.strike < chain.underlying.price and\n x.right == OptionRight.CALL, chain)\n\n sorted_contracts = sorted(contracts, key = lambda x: x.strike, reverse = True)\n\n if len(sorted_contracts) > 2:\n self.market_order(sorted_contracts[2].symbol, 1)\n self.market_on_close_order(sorted_contracts[2].symbol, -1)\n\n # set our strike/expiry filter for this option chain\n def universe_func(self, universe):\n return universe.include_weeklys().strikes(-2, 2).expiration(timedelta(0), timedelta(10))\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression Channel algorithm simply initializes the date range and cash", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass RegressionChannelAlgorithm(QCAlgorithm):\n\n def initialize(self):\n\n self.set_cash(100000)\n self.set_start_date(2009,1,1)\n self.set_end_date(2015,1,1)\n\n equity = self.add_equity(\"SPY\", Resolution.MINUTE)\n self._spy = equity.symbol\n self._holdings = equity.holdings\n self._rc = self.rc(self._spy, 30, 2, Resolution.DAILY)\n\n stock_plot = Chart(\"Trade Plot\")\n stock_plot.add_series(Series(\"Buy\", SeriesType.SCATTER, 0))\n stock_plot.add_series(Series(\"Sell\", SeriesType.SCATTER, 0))\n stock_plot.add_series(Series(\"UpperChannel\", SeriesType.LINE, 0))\n stock_plot.add_series(Series(\"LowerChannel\", SeriesType.LINE, 0))\n stock_plot.add_series(Series(\"Regression\", SeriesType.LINE, 0))\n self.add_chart(stock_plot)\n\n def on_data(self, data):\n if (not self._rc.is_ready) or (not data.contains_key(self._spy)): return\n if data[self._spy] is None: return\n value = data[self._spy].value\n if self._holdings.quantity <= 0 and value < self._rc.lower_channel.current.value:\n self.set_holdings(self._spy, 1)\n self.plot(\"Trade Plot\", \"Buy\", value)\n if self._holdings.quantity >= 0 and value > self._rc.upper_channel.current.value:\n self.set_holdings(self._spy, -1)\n self.plot(\"Trade Plot\", \"Sell\", value)\n\n def on_end_of_day(self, symbol):\n self.plot(\"Trade Plot\", \"UpperChannel\", self._rc.upper_channel.current.value)\n self.plot(\"Trade Plot\", \"LowerChannel\", self._rc.lower_channel.current.value)\n self.plot(\"Trade Plot\", \"Regression\", self._rc.linear_regression.current.value)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: his algorithm sends a list of portfolio targets to custom endpoint", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomSignalExportDemonstrationAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n ''' Initialize the date and add all equity symbols present in list _symbols '''\n\n self.set_start_date(2013, 10, 7) #Set Start Date\n self.set_end_date(2013, 10, 11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n # Our custom signal export accepts all asset types\n self.add_equity(\"SPY\", Resolution.SECOND)\n self.add_crypto(\"BTCUSD\", Resolution.SECOND)\n self.add_forex(\"EURUSD\", Resolution.SECOND)\n self.add_future_contract(Symbol.create_future(\"ES\", Market.CME, datetime(2023, 12, 15)))\n self.add_option_contract(Symbol.create_option(\"SPY\", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 130, datetime(2023, 9, 1)))\n\n # Set CustomSignalExport signal export provider.\n self.signal_export.add_signal_export_provider(CustomSignalExport())\n\n def on_data(self, data: Slice) -> None:\n '''Buy and hold EURUSD and SPY'''\n for ticker in [ \"SPY\", \"EURUSD\", \"BTCUSD\" ]:\n if not self.portfolio[ticker].invested and self.securities[ticker].has_data:\n self.set_holdings(ticker, 0.5)\n\nfrom requests import post\nclass CustomSignalExport:\n def send(self, parameters: SignalExportTargetParameters) -> bool:\n targets = [PortfolioTarget.percent(parameters.algorithm, x.symbol, x.quantity)\n for x in parameters.targets]\n data = [ {'symbol' : x.symbol.value, 'quantity': x.quantity} for x in targets ]\n response = post(\"http://localhost:5000/\", json = data)\n result = response.json()\n success = result.get('success', False)\n parameters.algorithm.log(f\"Send #{len(parameters.targets)} targets. Success: {success}\")\n return success\n\n def dispose(self):\n pass\n\n'''\n# To test the algorithm, you can create a simple Python Flask application (app.py) and run flask\n# $ flask --app app run\n\n# app.py:\nfrom flask import Flask, request, jsonify\nfrom json import loads\napp = Flask(__name__)\n@app.post('/')\ndef handle_positions():\n result = loads(request.data)\n print(result)\n return jsonify({'success': True,'message': f'{len(result)} positions received'})\nif __name__ == '__main__':\n app.run(debug=True)\n'''\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: In this algorithm we submit/update/cancel each order type", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OrderTicketDemoAlgorithm(QCAlgorithm):\n '''In this algorithm we submit/update/cancel each order type'''\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n equity = self.add_equity(\"SPY\")\n self.spy = equity.symbol\n\n self.__open_market_on_open_orders = []\n self.__open_market_on_close_orders = []\n self.__open_limit_orders = []\n self.__open_stop_market_orders = []\n self.__open_stop_limit_orders = []\n self.__open_trailing_stop_orders = []\n\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n # MARKET ORDERS\n self.market_orders()\n\n # LIMIT ORDERS\n self.limit_orders()\n\n # STOP MARKET ORDERS\n self.stop_market_orders()\n\n # STOP LIMIT ORDERS\n self.stop_limit_orders()\n\n # TRAILING STOP ORDERS\n self.trailing_stop_orders()\n\n # MARKET ON OPEN ORDERS\n self.market_on_open_orders()\n\n # MARKET ON CLOSE ORDERS\n self.market_on_close_orders()\n\n\n def market_orders(self):\n ''' MarketOrders are the only orders that are processed synchronously by default, so\n they'll fill by the next line of code. This behavior equally applies to live mode.\n You can opt out of this behavior by specifying the 'asynchronous' parameter as True.'''\n if self.time_is(7, 9, 31):\n self.log(\"Submitting MarketOrder\")\n\n # submit a market order to buy 10 shares, this function returns an OrderTicket object\n # we submit the order with asynchronous = False, so it block until it is filled\n new_ticket = self.market_order(self.spy, 10, asynchronous = False)\n if new_ticket.status != OrderStatus.FILLED:\n self.log(\"Synchronous market order was not filled synchronously!\")\n self.quit()\n\n # we can also submit the ticket asynchronously. In a backtest, we'll still perform the fill\n # before the next time events for your algorithm. here we'll submit the order asynchronously\n # and try to cancel it, sometimes it will, sometimes it will be filled first.\n new_ticket = self.market_order(self.spy, 10, asynchronous = True)\n response = new_ticket.cancel(\"Attempt to cancel async order\")\n if response.is_success:\n self.log(\"Successfully canceled async market order: {0}\".format(new_ticket.order_id))\n else:\n self.log(\"Unable to cancel async market order: {0}\".format(response.error_code))\n\n\n def limit_orders(self):\n '''LimitOrders are always processed asynchronously. Limit orders are used to\n set 'good' entry points for an order. For example, you may wish to go\n long a stock, but want a good price, so can place a LimitOrder to buy with\n a limit price below the current market price. Likewise the opposite is True\n when selling, you can place a LimitOrder to sell with a limit price above the\n current market price to get a better sale price.\n You can submit requests to update or cancel the LimitOrder at any time.\n The 'LimitPrice' for an order can be retrieved from the ticket using the\n OrderTicket.get(OrderField) method, for example:\n Code:\n current_limit_price = order_ticket.get(OrderField.LIMIT_PRICE)'''\n if self.time_is(7, 12, 0):\n self.log(\"Submitting LimitOrder\")\n\n # submit a limit order to buy 10 shares at .1% below the bar's close\n close = self.securities[self.spy.value].close\n new_ticket = self.limit_order(self.spy, 10, close * .999)\n self.__open_limit_orders.append(new_ticket)\n\n # submit another limit order to sell 10 shares at .1% above the bar's close\n new_ticket = self.limit_order(self.spy, -10, close * 1.001)\n self.__open_limit_orders.append(new_ticket)\n\n # when we submitted new limit orders we placed them into this list,\n # so while there's two entries they're still open and need processing\n if len(self.__open_limit_orders) == 2:\n open_orders = self.__open_limit_orders\n\n # check if either is filled and cancel the other\n long_order = open_orders[0]\n short_order = open_orders[1]\n if self.check_pair_orders_for_fills(long_order, short_order):\n self.__open_limit_orders = []\n return\n\n # if neither order has filled, bring in the limits by a penny\n new_long_limit = long_order.get(OrderField.LIMIT_PRICE) + 0.01\n new_short_limit = short_order.get(OrderField.LIMIT_PRICE) - 0.01\n self.log(\"Updating limits - Long: {0:.2f} Short: {1:.2f}\".format(new_long_limit, new_short_limit))\n\n update_order_fields = UpdateOrderFields()\n update_order_fields.limit_price = new_long_limit\n update_order_fields.tag = \"Update #{0}\".format(len(long_order.update_requests) + 1)\n long_order.update(update_order_fields)\n\n update_order_fields = UpdateOrderFields()\n update_order_fields.limit_price = new_short_limit\n update_order_fields.tag = \"Update #{0}\".format(len(short_order.update_requests) + 1)\n short_order.update(update_order_fields)\n\n\n def stop_market_orders(self):\n '''StopMarketOrders work in the opposite way that limit orders do.\n When placing a long trade, the stop price must be above current\n market price. In this way it's a 'stop loss' for a short trade.\n When placing a short trade, the stop price must be below current\n market price. In this way it's a 'stop loss' for a long trade.\n You can submit requests to update or cancel the StopMarketOrder at any time.\n The 'StopPrice' for an order can be retrieved from the ticket using the\n OrderTicket.get(OrderField) method, for example:\n Code:\n current_stop_price = order_ticket.get(OrderField.STOP_PRICE)'''\n if self.time_is(7, 12 + 4, 0):\n self.log(\"Submitting StopMarketOrder\")\n\n # a long stop is triggered when the price rises above the value\n # so we'll set a long stop .25% above the current bar's close\n close = self.securities[self.spy.value].close\n new_ticket = self.stop_market_order(self.spy, 10, close * 1.0025)\n self.__open_stop_market_orders.append(new_ticket)\n\n # a short stop is triggered when the price falls below the value\n # so we'll set a short stop .25% below the current bar's close\n new_ticket = self.stop_market_order(self.spy, -10, close * .9975)\n self.__open_stop_market_orders.append(new_ticket)\n\n # when we submitted new stop market orders we placed them into this list,\n # so while there's two entries they're still open and need processing\n if len(self.__open_stop_market_orders) == 2:\n # check if either is filled and cancel the other\n long_order = self.__open_stop_market_orders[0]\n short_order = self.__open_stop_market_orders[1]\n if self.check_pair_orders_for_fills(long_order, short_order):\n self.__open_stop_market_orders = []\n return\n\n # if neither order has filled, bring in the stops by a penny\n new_long_stop = long_order.get(OrderField.STOP_PRICE) - 0.01\n new_short_stop = short_order.get(OrderField.STOP_PRICE) + 0.01\n self.log(\"Updating stops - Long: {0:.2f} Short: {1:.2f}\".format(new_long_stop, new_short_stop))\n\n update_order_fields = UpdateOrderFields()\n update_order_fields.stop_price = new_long_stop\n update_order_fields.tag = \"Update #{0}\".format(len(long_order.update_requests) + 1)\n long_order.update(update_order_fields)\n\n update_order_fields = UpdateOrderFields()\n update_order_fields.stop_price = new_short_stop\n update_order_fields.tag = \"Update #{0}\".format(len(short_order.update_requests) + 1)\n short_order.update(update_order_fields)\n self.log(\"Updated price - Long: {0} Short: {1}\".format(long_order.get(OrderField.STOP_PRICE), short_order.get(OrderField.STOP_PRICE)))\n\n\n def stop_limit_orders(self):\n '''StopLimitOrders work as a combined stop and limit order. First, the\n price must pass the stop price in the same way a StopMarketOrder works,\n but then we're also guaranteed a fill price at least as good as the\n limit price. This order type can be beneficial in gap down scenarios\n where a StopMarketOrder would have triggered and given the not as beneficial\n gapped down price, whereas the StopLimitOrder could protect you from\n getting the gapped down price through prudent placement of the limit price.\n You can submit requests to update or cancel the StopLimitOrder at any time.\n The 'StopPrice' or 'LimitPrice' for an order can be retrieved from the ticket\n using the OrderTicket.get(OrderField) method, for example:\n Code:\n current_stop_price = order_ticket.get(OrderField.STOP_PRICE)\n current_limit_price = order_ticket.get(OrderField.LIMIT_PRICE)'''\n if self.time_is(8, 12, 1):\n self.log(\"Submitting StopLimitOrder\")\n\n # a long stop is triggered when the price rises above the\n # value so we'll set a long stop .25% above the current bar's\n # close now we'll also be setting a limit, this means we are\n # guaranteed to get at least the limit price for our fills,\n # so make the limit price a little higher than the stop price\n\n close = self.securities[self.spy.value].close\n new_ticket = self.stop_limit_order(self.spy, 10, close * 1.001, close - 0.03)\n self.__open_stop_limit_orders.append(new_ticket)\n\n # a short stop is triggered when the price falls below the\n # value so we'll set a short stop .25% below the current bar's\n # close now we'll also be setting a limit, this means we are\n # guaranteed to get at least the limit price for our fills,\n # so make the limit price a little softer than the stop price\n\n new_ticket = self.stop_limit_order(self.spy, -10, close * .999, close + 0.03)\n self.__open_stop_limit_orders.append(new_ticket)\n\n # when we submitted new stop limit orders we placed them into this list,\n # so while there's two entries they're still open and need processing\n if len(self.__open_stop_limit_orders) == 2:\n long_order = self.__open_stop_limit_orders[0]\n short_order = self.__open_stop_limit_orders[1]\n if self.check_pair_orders_for_fills(long_order, short_order):\n self.__open_stop_limit_orders = []\n return\n\n # if neither order has filled, bring in the stops/limits in by a penny\n\n new_long_stop = long_order.get(OrderField.STOP_PRICE) - 0.01\n new_long_limit = long_order.get(OrderField.LIMIT_PRICE) + 0.01\n new_short_stop = short_order.get(OrderField.STOP_PRICE) + 0.01\n new_short_limit = short_order.get(OrderField.LIMIT_PRICE) - 0.01\n self.log(\"Updating stops - Long: {0:.2f} Short: {1:.2f}\".format(new_long_stop, new_short_stop))\n self.log(\"Updating limits - Long: {0:.2f} Short: {1:.2f}\".format(new_long_limit, new_short_limit))\n\n update_order_fields = UpdateOrderFields()\n update_order_fields.stop_price = new_long_stop\n update_order_fields.limit_price = new_long_limit\n update_order_fields.tag = \"Update #{0}\".format(len(long_order.update_requests) + 1)\n long_order.update(update_order_fields)\n\n update_order_fields = UpdateOrderFields()\n update_order_fields.stop_price = new_short_stop\n update_order_fields.limit_price = new_short_limit\n update_order_fields.tag = \"Update #{0}\".format(len(short_order.update_requests) + 1)\n short_order.update(update_order_fields)\n\n\n def trailing_stop_orders(self):\n '''TrailingStopOrders work the same way as StopMarketOrders, except\n their stop price is adjusted to a certain amount, keeping it a certain\n fixed distance from/to the market price, depending on the order direction,\n which allows to preserve profits and protecting against losses.\n The stop price can be accessed just as with StopMarketOrders, and\n the trailing amount can be accessed with the OrderTicket.get(OrderField), for example:\n Code:\n current_trailing_amount = order_ticket.get(OrderField.STOP_PRICE)\n trailing_as_percentage = order_ticket.get[bool](OrderField.TRAILING_AS_PERCENTAGE)'''\n if self.time_is(7, 12, 0):\n self.log(\"Submitting TrailingStopOrder\")\n\n # a long stop is triggered when the price rises above the\n # value so we'll set a long stop .25% above the current bar's\n\n close = self.securities[self.spy.value].close\n stop_price = close * 1.0025\n new_ticket = self.trailing_stop_order(self.spy, 10, stop_price, trailing_amount=0.0025, trailing_as_percentage=True)\n self.__open_trailing_stop_orders.append(new_ticket)\n\n # a short stop is triggered when the price falls below the\n # value so we'll set a short stop .25% below the current bar's\n\n stop_price = close * .9975\n new_ticket = self.trailing_stop_order(self.spy, -10, stop_price, trailing_amount=0.0025, trailing_as_percentage=True)\n self.__open_trailing_stop_orders.append(new_ticket)\n\n # when we submitted new stop market orders we placed them into this list,\n # so while there's two entries they're still open and need processing\n elif len(self.__open_trailing_stop_orders) == 2:\n long_order = self.__open_trailing_stop_orders[0]\n short_order = self.__open_trailing_stop_orders[1]\n if self.check_pair_orders_for_fills(long_order, short_order):\n self.__open_trailing_stop_orders = []\n return\n\n # if neither order has filled in the last 5 minutes, bring in the trailing percentage by 0.01%\n if ((self.utc_time - long_order.time).total_seconds() / 60) % 5 != 0:\n return\n\n long_trailing_percentage = long_order.get(OrderField.TRAILING_AMOUNT)\n new_long_trailing_percentage = max(long_trailing_percentage - 0.0001, 0.0001)\n short_trailing_percentage = short_order.get(OrderField.TRAILING_AMOUNT)\n new_short_trailing_percentage = max(short_trailing_percentage - 0.0001, 0.0001)\n self.log(\"Updating trailing percentages - Long: {0:.3f} Short: {1:.3f}\".format(new_long_trailing_percentage, new_short_trailing_percentage))\n\n update_order_fields = UpdateOrderFields()\n # we could change the quantity, but need to specify it\n #Quantity =\n update_order_fields.trailing_amount = new_long_trailing_percentage\n update_order_fields.tag = \"Update #{0}\".format(len(long_order.update_requests) + 1)\n long_order.update(update_order_fields)\n\n update_order_fields = UpdateOrderFields()\n update_order_fields.trailing_amount = new_short_trailing_percentage\n update_order_fields.tag = \"Update #{0}\".format(len(short_order.update_requests) + 1)\n short_order.update(update_order_fields)\n\n\n def market_on_close_orders(self):\n '''MarketOnCloseOrders are always executed at the next market's closing price.\n The only properties that can be updated are the quantity and order tag properties.'''\n if self.time_is(9, 12, 0):\n self.log(\"Submitting MarketOnCloseOrder\")\n\n # open a new position or triple our existing position\n qty = self.portfolio[self.spy.value].quantity\n qty = 100 if qty == 0 else 2*qty\n\n new_ticket = self.market_on_close_order(self.spy, qty)\n self.__open_market_on_close_orders.append(new_ticket)\n\n if len(self.__open_market_on_close_orders) == 1 and self.time.minute == 59:\n ticket = self.__open_market_on_close_orders[0]\n # check for fills\n if ticket.status == OrderStatus.FILLED:\n self.__open_market_on_close_orders = []\n return\n\n quantity = ticket.quantity + 1\n self.log(\"Updating quantity - New Quantity: {0}\".format(quantity))\n\n # we can update the quantity and tag\n update_order_fields = UpdateOrderFields()\n update_order_fields.quantity = quantity\n update_order_fields.tag = \"Update #{0}\".format(len(ticket.update_requests) + 1)\n ticket.update(update_order_fields)\n\n if self.time_is(self.end_date.day, 12 + 3, 45):\n self.log(\"Submitting MarketOnCloseOrder to liquidate end of algorithm\")\n self.market_on_close_order(self.spy, -self.portfolio[self.spy.value].quantity, tag=\"Liquidate end of algorithm\")\n\n\n def market_on_open_orders(self):\n '''MarketOnOpenOrders are always executed at the next\n market's opening price. The only properties that can\n be updated are the quantity and order tag properties.'''\n if self.time_is(8, 14 + 2, 0):\n self.log(\"Submitting MarketOnOpenOrder\")\n\n # its EOD, let's submit a market on open order to short even more!\n new_ticket = self.market_on_open_order(self.spy, 50)\n self.__open_market_on_open_orders.append(new_ticket)\n\n if len(self.__open_market_on_open_orders) == 1 and self.time.minute == 59:\n ticket = self.__open_market_on_open_orders[0]\n\n # check for fills\n if ticket.status == OrderStatus.FILLED:\n self.__open_market_on_open_orders = []\n return\n\n quantity = ticket.quantity + 1\n self.log(\"Updating quantity - New Quantity: {0}\".format(quantity))\n\n # we can update the quantity and tag\n update_order_fields = UpdateOrderFields()\n update_order_fields.quantity = quantity\n update_order_fields.tag = \"Update #{0}\".format(len(ticket.update_requests) + 1)\n ticket.update(update_order_fields)\n\n\n def on_order_event(self, order_event):\n order = self.transactions.get_order_by_id(order_event.order_id)\n self.log(\"{0}: {1}: {2}\".format(self.time, order.type, order_event))\n\n if order_event.quantity == 0:\n raise AssertionError(\"OrderEvent quantity is Not expected to be 0, it should hold the current order Quantity\")\n\n if order_event.quantity != order.quantity:\n raise AssertionError(\"OrderEvent quantity should hold the current order Quantity\")\n\n if (type(order) is LimitOrder and order_event.limit_price == 0 or\n type(order) is StopLimitOrder and order_event.limit_price == 0):\n raise AssertionError(\"OrderEvent LimitPrice is Not expected to be 0 for LimitOrder and StopLimitOrder\")\n\n if type(order) is StopMarketOrder and order_event.stop_price == 0:\n raise AssertionError(\"OrderEvent StopPrice is Not expected to be 0 for StopMarketOrder\")\n\n # We can access the order ticket from the order event\n if order_event.ticket is None:\n raise AssertionError(\"OrderEvent Ticket was not set\")\n if order_event.order_id != order_event.ticket.order_id:\n raise AssertionError(\"OrderEvent.ORDER_ID and order_event.ticket.order_id do not match\")\n\n def check_pair_orders_for_fills(self, long_order, short_order):\n if long_order.status == OrderStatus.FILLED:\n self.log(\"{0}: Cancelling short order, long order is filled.\".format(short_order.order_type))\n short_order.cancel(\"Long filled.\")\n return True\n\n if short_order.status == OrderStatus.FILLED:\n self.log(\"{0}: Cancelling long order, short order is filled.\".format(long_order.order_type))\n long_order.cancel(\"Short filled\")\n return True\n\n return False\n\n\n def time_is(self, day, hour, minute):\n return self.time.day == day and self.time.hour == hour and self.time.minute == minute\n\n def on_end_of_algorithm(self):\n basic_order_ticket_filter = lambda x: x.symbol == self.spy\n\n filled_orders = self.transactions.get_orders(lambda x: x.status == OrderStatus.FILLED)\n order_tickets = self.transactions.get_order_tickets(basic_order_ticket_filter)\n open_orders = self.transactions.get_open_orders(lambda x: x.symbol == self.spy)\n open_order_tickets = self.transactions.get_open_order_tickets(basic_order_ticket_filter)\n remaining_open_orders = self.transactions.get_open_orders_remaining_quantity(basic_order_ticket_filter)\n\n # The type returned by self.transactions.get_orders() is iterable and not a list\n # that's why we use sum() to get the size of the iterable object type\n filled_orders_size = sum(1 for order in filled_orders)\n order_tickets_size = sum(1 for ticket in order_tickets)\n open_order_tickets_size = sum(1 for ticket in open_order_tickets)\n\n assert(filled_orders_size == 9 and order_tickets_size == 12), \"There were expected 9 filled orders and 12 order tickets\"\n assert(not (len(open_orders) or open_order_tickets_size)), \"No open orders or tickets were expected\"\n assert(not remaining_open_orders), \"No remaining quantity to be filled from open orders was expected\"\n\n spy_open_orders = self.transactions.get_open_orders(self.spy)\n spy_open_order_tickets = self.transactions.get_open_order_tickets(self.spy)\n spy_open_order_tickets_size = sum(1 for tickets in spy_open_order_tickets)\n spy_open_orders_remaining_quantity = self.transactions.get_open_orders_remaining_quantity(self.spy)\n\n assert(not (len(spy_open_orders) or spy_open_order_tickets_size)), \"No open orders or tickets were expected\"\n assert(not spy_open_orders_remaining_quantity), \"No remaining quantity to be filled from open orders was expected\"\n\n default_orders = self.transactions.get_orders()\n default_order_tickets = self.transactions.get_order_tickets()\n default_open_orders = self.transactions.get_open_orders()\n default_open_order_tickets = self.transactions.get_open_order_tickets()\n default_open_orders_remaining = self.transactions.get_open_orders_remaining_quantity()\n\n default_orders_size = sum(1 for order in default_orders)\n default_order_tickets_size = sum(1 for ticket in default_order_tickets)\n default_open_order_tickets_size = sum(1 for ticket in default_open_order_tickets)\n\n assert(default_orders_size == 12 and default_order_tickets_size == 12), \"There were expected 12 orders and 12 order tickets\"\n assert(not (len(default_open_orders) or default_open_order_tickets_size)), \"No open orders or tickets were expected\"\n assert(not default_open_orders_remaining), \"No remaining quantity to be filled from open orders was expected\"\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression test algorithm for scheduled universe selection GH 3890", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FundamentalCustomSelectionTimeRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self._month_start_selection = 0\n self._month_end_selection = 0\n self._specific_date_selection = 0\n self._symbol = Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n\n self.set_start_date(2014, 3, 25)\n self.set_end_date(2014, 5, 10)\n self.universe_settings.resolution = Resolution.DAILY\n\n # Test use case A\n self.add_universe(self.date_rules.month_start(), self.selection_function__month_start)\n\n # Test use case B\n other_settings = UniverseSettings(self.universe_settings)\n other_settings.schedule.on(self.date_rules.month_end())\n\n self.add_universe(FundamentalUniverse.usa(self.selection_function__month_end, other_settings))\n\n # Test use case C\n self.universe_settings.schedule.on(self.date_rules.on(datetime(2014, 5, 9)))\n self.add_universe(FundamentalUniverse.usa(self.selection_function__specific_date))\n\n def selection_function__specific_date(self, coarse):\n self._specific_date_selection += 1\n if self.time != datetime(2014, 5, 9):\n raise ValueError(\"SelectionFunction_SpecificDate unexpected selection: \" + str(self.time))\n return [ self._symbol ]\n\n def selection_function__month_start(self, coarse):\n self._month_start_selection += 1\n if self._month_start_selection == 1:\n if self.time != self.start_date:\n raise ValueError(\"Month Start Unexpected initial selection: \" + str(self.time))\n elif self.time != datetime(2014, 4, 1) and self.time != datetime(2014, 5, 1):\n raise ValueError(\"Month Start unexpected selection: \" + str(self.time))\n return [ self._symbol ]\n\n def selection_function__month_end(self, coarse):\n self._month_end_selection += 1\n if self._month_end_selection == 1:\n if self.time != self.start_date:\n raise ValueError(\"Month End unexpected initial selection: \" + str(self.time))\n elif self.time != datetime(2014, 3, 31) and self.time != datetime(2014, 4, 30):\n raise ValueError(\"Month End unexpected selection: \" + str(self.time))\n return [ self._symbol ]\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(self._symbol, 1)\n\n def on_end_of_algorithm(self):\n if self._month_end_selection != 3:\n raise ValueError(\"Month End unexpected selection count: \" + str(self._month_end_selection))\n if self._month_start_selection != 3:\n raise ValueError(\"Month Start unexpected selection count: \" + str(self._month_start_selection))\n if self._specific_date_selection != 1:\n raise ValueError(\"Specific date unexpected selection count: \" + str(self._month_start_selection))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic Template India Index Algorithm uses framework components to define the algorithm.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateIndiaIndexAlgorithm(QCAlgorithm):\n '''Basic template framework algorithm uses framework components to define the algorithm.'''\n\n def initialize(self):\n '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_account_currency(\"INR\") #Set Account Currency\n self.set_start_date(2019, 1, 1) #Set Start Date\n self.set_end_date(2019, 1, 5) #Set End Date\n self.set_cash(1000000) #Set Strategy Cash\n\n # Use indicator for signal; but it cannot be traded\n self.nifty = self.add_index(\"NIFTY50\", Resolution.MINUTE, Market.INDIA).symbol\n # Trade Index based ETF\n self.nifty_etf = self.add_equity(\"JUNIORBEES\", Resolution.MINUTE, Market.INDIA).symbol\n \n # Set Order Properties as per the requirements for order placement\n self.default_order_properties = IndiaOrderProperties(Exchange.NSE)\n\n # Define indicator\n self._ema_slow = self.ema(self.nifty, 80)\n self._ema_fast = self.ema(self.nifty, 200)\n\n self.debug(\"numpy test >>> print numpy.pi: \" + str(np.pi))\n\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n\n if not data.bars.contains_key(self.nifty) or not data.bars.contains_key(self.nifty_etf):\n return\n\n if not self._ema_slow.is_ready:\n return\n\n if self._ema_fast > self._ema_slow:\n if not self.portfolio.invested:\n self.market_ticket = self.market_order(self.nifty_etf, 1)\n else:\n self.liquidate()\n\n\n def on_end_of_algorithm(self):\n if self.portfolio[self.nifty].total_sale_volume > 0:\n raise AssertionError(\"Index is not tradable.\")\n\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm for asserting that tick history that includes multiple tick types (trade, quote) is correctly converted to a pandas\ndataframe without raising exceptions. The main exception in this case was a \"non-unique multi-index\" error due to trades adn quote ticks with\nduplicated timestamps.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass PandasDataFrameFromMultipleTickTypeTickHistoryRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013, 10, 8)\n self.set_end_date(2013, 10, 8)\n\n spy = self.add_equity(\"SPY\", Resolution.MINUTE).symbol\n\n subscriptions = [x for x in self.subscription_manager.subscriptions if x.symbol == spy]\n if len(subscriptions) != 2:\n raise AssertionError(f\"Expected 2 subscriptions, but found {len(subscriptions)}\")\n\n history = pd.DataFrame()\n try:\n history = self.history(Tick, spy, timedelta(days=1), Resolution.TICK)\n except Exception as e:\n raise AssertionError(f\"History call failed: {e}\")\n\n if history.shape[0] == 0:\n raise AssertionError(\"SPY tick history is empty\")\n\n if not np.array_equal(history.columns.to_numpy(), ['askprice', 'asksize', 'bidprice', 'bidsize', 'exchange', 'lastprice', 'quantity']):\n raise AssertionError(\"Unexpected columns in SPY tick history\")\n\n self.quit()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: In this example we look at the canonical 15/30 day moving average cross. This algorithm\nwill go long when the 15 crosses above the 30 and will liquidate when the 15 crosses\nback below the 30.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MovingAverageCrossAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2009, 1, 1) #Set Start Date\n self.set_end_date(2015, 1, 1) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\")\n\n # create a 15 day exponential moving average\n self.fast = self.ema(\"SPY\", 15, Resolution.DAILY)\n\n # create a 30 day exponential moving average\n self.slow = self.ema(\"SPY\", 30, Resolution.DAILY)\n\n self.previous = None\n\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n # a couple things to notice in this method:\n # 1. We never need to 'update' our indicators with the data, the engine takes care of this for us\n # 2. We can use indicators directly in math expressions\n # 3. We can easily plot many indicators at the same time\n\n # wait for our slow ema to fully initialize\n if not self.slow.is_ready:\n return\n\n # only once per day\n if self.previous is not None and self.previous.date() == self.time.date():\n return\n\n # define a small tolerance on our checks to avoid bouncing\n tolerance = 0.00015\n\n holdings = self.portfolio[\"SPY\"].quantity\n\n # we only want to go long if we're currently short or flat\n if holdings <= 0:\n # if the fast is greater than the slow, we'll go long\n if self.fast.current.value > self.slow.current.value *(1 + tolerance):\n self.log(\"BUY >> {0}\".format(self.securities[\"SPY\"].price))\n self.set_holdings(\"SPY\", 1.0)\n\n # we only want to liquidate if we're currently long\n # if the fast is less than the slow we'll liquidate our long\n if holdings > 0 and self.fast.current.value < self.slow.current.value:\n self.log(\"SELL >> {0}\".format(self.securities[\"SPY\"].price))\n self.liquidate(\"SPY\")\n\n self.previous = self.time\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template algorithm simply initializes the date range and cash. This is a skeleton\nframework you can use for designing an algorithm.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateAlgorithm(QCAlgorithm):\n '''Basic template algorithm simply initializes the date range and cash'''\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\", Resolution.MINUTE)\n self.debug(\"numpy test >>> print numpy.pi: \" + str(np.pi))\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests Out of The Money (OTM) future option expiry for short calls.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, sell ES Call Option (expiring OTM)\n - Profit the option premium, since the option was not assigned.\n\n * Liquidation of ES call OTM contract on the last trade date\n\nAdditionally, we test delistings for future options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionShortCallOTMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 6, 30)\n\n self.es19m20 = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 6, 19)),\n Resolution.MINUTE).symbol\n\n # Select a future option expiring ITM, and adds it to the algorithm.\n self.es_option = self.add_future_option_contract(\n list(\n sorted(\n [x for x in self.option_chain(self.es19m20) if x.id.strike_price >= 3400.0 and x.id.option_right == OptionRight.CALL],\n key=lambda x: x.id.strike_price\n )\n )[0], Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3400.0, datetime(2020, 6, 19))\n if self.es_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)\n\n def scheduled_market_order(self):\n self.market_order(self.es_option, -1)\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2020, 6, 19):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2020, 6, 20):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if not self.securities.contains_key(order_event.symbol):\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.es19m20:\n raise AssertionError(f\"Expected no order events for underlying Symbol {security.symbol}\")\n\n if security.symbol == self.expected_contract:\n self.assert_future_option_contract_order(order_event, security)\n\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n self.log(f\"{order_event}\")\n\n def assert_future_option_contract_order(self, order_event: OrderEvent, option_contract: Security):\n if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1:\n raise AssertionError(f\"No holdings were created for option contract {option_contract.symbol}\")\n\n if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:\n raise AssertionError(\"Expected no options holdings after closing position\")\n\n if order_event.is_assignment:\n raise AssertionError(f\"Assignment was not expected for {order_event.symbol}\")\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to assert the behavior of .", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm\nfrom Alphas.RsiAlphaModel import RsiAlphaModel\n\nclass RsiAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):\n\n def initialize(self):\n super().initialize()\n self.set_alpha(RsiAlphaModel())\n\n def on_end_of_algorithm(self):\n # We have removed all securities from the universe. The Alpha Model should remove the consolidator\n consolidator_count = sum([s.consolidators.count for s in self.subscription_manager.subscriptions])\n if consolidator_count > 0:\n raise AssertionError(f\"The number of consolidators should be zero. Actual: {consolidator_count}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm showcases some features of the IObjectStore feature.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom io import StringIO\n\nclass ObjectStoreExampleAlgorithm(QCAlgorithm):\n '''This algorithm showcases some features of the IObjectStore feature.\n One use case is to make consecutive backtests run faster by caching the results of\n potentially time consuming operations. In this example, we save the results of a\n history call. This pattern can be equally applied to a machine learning model being\n trained and then saving the model weights in the object store.\n '''\n spy_close_object_store_key = \"spy_close\"\n spy_close_history = RollingWindow(252)\n spy_close_ema10_history = RollingWindow(252)\n spy_close_ema50_history = RollingWindow(252)\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n\n self.SPY = self.add_equity(\"SPY\", Resolution.MINUTE).symbol\n\n self.spy_close = self.identity(self.SPY, Resolution.DAILY)\n self.spy_close_ema10 = IndicatorExtensions.ema(self.spy_close, 10)\n self.spy_close_ema50 = IndicatorExtensions.ema(self.spy_close, 50)\n\n # track last year of close and EMA10/EMA50\n self.spy_close.updated += lambda _, args: self.spy_close_history.add(args)\n self.spy_close_ema10.updated += lambda _, args: self.spy_close_ema10_history.add(args)\n self.spy_close_ema50.updated += lambda _, args: self.spy_close_ema50_history.add(args)\n\n if self.object_store.contains_key(self.spy_close_object_store_key):\n # our object store has our historical data saved, read the data\n # and push it through the indicators to warm everything up\n values = self.object_store.read(self.spy_close_object_store_key)\n self.debug(f'{self.spy_close_object_store_key} key exists in object store.')\n\n history = pd.read_csv(StringIO(values), header=None, index_col=0, squeeze=True)\n history.index = pd.to_datetime(history.index)\n for time, close in history.items():\n self.spy_close.update(time, close)\n\n else:\n self.debug(f'{self.spy_close_object_store_key} key does not exist in object store. Fetching history...')\n\n # if our object store doesn't have our data, fetch the history to initialize\n # we're pulling the last year's worth of SPY daily trade bars to fee into our indicators\n history = self.history(self.SPY, timedelta(365), Resolution.DAILY).close.unstack(0).squeeze()\n\n for time, close in history.items():\n self.spy_close.update(time, close)\n\n # save our warm up data so next time we don't need to issue the history request\n self.object_store.save(self.spy_close_object_store_key,\n '\\n'.join(reversed([f'{x.end_time},{x.value}' for x in self.spy_close_history])))\n\n # Can also use ObjectStore.save_bytes(key, byte[])\n # and to read ObjectStore.read_bytes(key) => byte[]\n\n # we can also get a file path for our data. some ML libraries require model\n # weights to be loaded directly from a file path. The object store can provide\n # a file path for any key by: ObjectStore.get_file_path(key) => string (file path)\n\n def on_data(self, slice):\n\n close = self.spy_close\n ema10 = self.spy_close_ema10\n ema50 = self.spy_close_ema50\n\n if ema10 > close and ema10 > ema50:\n self.set_holdings(self.SPY, 1)\n\n elif ema10 < close and ema10 < ema50:\n self.set_holdings(self.SPY, -1)\n\n elif ema10 < ema50 and self.portfolio[self.SPY].is_long:\n self.liquidate(self.SPY)\n\n elif ema10 > ema50 and self.portfolio[self.SPY].is_short:\n self.liquidate(self.SPY)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression test for consistency of hour data over a reverse split event in US equities.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass HourSplitRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2014, 6, 6)\n self.set_end_date(2014, 6, 9)\n self.set_cash(100000)\n self.set_benchmark(lambda x: 0)\n\n self._symbol = self.add_equity(\"AAPL\", Resolution.HOUR).symbol\n \n def on_data(self, slice):\n if slice.bars.count == 0: return\n if (not self.portfolio.invested) and self.time.date() == self.end_date.date():\n self.buy(self._symbol, 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to test zeroed benchmark through BrokerageModel override", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ZeroedBenchmarkRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_cash(100000)\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,8)\n\n # Add Equity\n self.add_equity(\"SPY\", Resolution.HOUR)\n\n # Use our Test Brokerage Model with zerod default benchmark\n self.set_brokerage_model(TestBrokerageModel())\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n\nclass TestBrokerageModel(DefaultBrokerageModel):\n\n def get_benchmark(self, securities):\n return FuncBenchmark(self.func)\n\n def func(self, datetime):\n return 0\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm sends a list of portfolio targets from algorithm's Portfolio\nto Collective2 API every time the ema indicators crosses between themselves.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass Collective2PortfolioSignalExportDemonstrationAlgorithm(QCAlgorithm):\n\n def initialize(self):\n ''' Initialize the date and add all equity symbols present in list _symbols '''\n\n self.set_start_date(2013, 10, 7) #Set Start Date\n self.set_end_date(2013, 10, 11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n # Symbols accepted by Collective2. Collective2 accepts stock, future, forex and US stock option symbols\n self.add_equity(\"GOOG\")\n self._symbols = [\n Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA, None, None),\n Symbol.create(\"EURUSD\", SecurityType.FOREX, Market.OANDA, None, None),\n Symbol.create_future(\"ES\", Market.CME, datetime(2023, 12, 15), None),\n Symbol.create_option(\"GOOG\", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 130, datetime(2023, 9, 1))\n ]\n for item in self._symbols:\n self.add_security(item)\n\n self.fast = self.ema(\"SPY\", 10)\n self.slow = self.ema(\"SPY\", 100)\n\n # Initialize these flags, to check when the ema indicators crosses between themselves\n self.ema_fast_is_not_set = True\n self.ema_fast_was_above = False\n\n # Collective2 APIv4 KEY: This value is provided by Collective2 in their webpage in your account section (See https://collective2.com/account-info)\n # See API documentation at https://trade.collective2.com/c2-api\n self.collective2_apikey = \"YOUR APIV4 KEY\"\n\n # Collective2 System ID: This value is found beside the system's name (strategy's name) on the main system page\n self.collective2_system_id = 0\n\n # Disable automatic exports as we manually set them\n self.signal_export.automatic_export_time_span = None\n\n # Set Collective2 signal export provider\n self.signal_export.add_signal_export_provider(Collective2SignalExport(self.collective2_apikey, self.collective2_system_id))\n\n self.first_call = True\n\n self.set_warm_up(100)\n\n def on_data(self, data):\n ''' Reduce the quantity of holdings for one security and increase the holdings to the another\n one when the EMA's indicators crosses between themselves, then send a signal to Collective2 API '''\n if self.is_warming_up: return\n\n # Place an order as soon as possible to send a signal.\n if self.first_call:\n self.set_holdings(\"SPY\", 0.1)\n self.signal_export.set_target_portfolio_from_portfolio()\n self.first_call = False\n\n fast = self.fast.current.value\n slow = self.slow.current.value\n\n # Set the value of flag _ema_fast_was_above, to know when the ema indicators crosses between themselves\n if self.ema_fast_is_not_set == True:\n if fast > slow *1.001:\n self.ema_fast_was_above = True\n else:\n self.ema_fast_was_above = False\n self.ema_fast_is_not_set = False\n\n # Check whether ema fast and ema slow crosses. If they do, set holdings to SPY\n # or reduce its holdings, and send signals to Collective2 API from your Portfolio\n if fast > slow * 1.001 and (not self.ema_fast_was_above):\n self.set_holdings(\"SPY\", 0.1)\n self.signal_export.set_target_portfolio_from_portfolio()\n elif fast < slow * 0.999 and (self.ema_fast_was_above):\n self.set_holdings(\"SPY\", 0.01)\n self.signal_export.set_target_portfolio_from_portfolio()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm reproducing data type bugs in the Consolidate API. Related to GH 4205.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom CustomDataRegressionAlgorithm import Bitcoin\n\nclass ConsolidateRegressionAlgorithm(QCAlgorithm):\n\n # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.\n def initialize(self):\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 1, 20)\n\n SP500 = Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME)\n symbol = list(self.futures_chain(SP500))[0]\n self._future = self.add_future_contract(symbol)\n\n tradable_dates_count = len(list(Time.each_tradeable_day_in_time_zone(self._future.exchange.hours,\n self.start_date,\n self.end_date,\n self._future.exchange.time_zone,\n False)))\n self._expected_consolidation_counts = []\n\n self.consolidate(symbol, Calendar.MONTHLY, lambda bar: self.update_monthly_consolidator(bar)) # shouldn't consolidate\n\n self.consolidate(symbol, Calendar.WEEKLY, TickType.TRADE, lambda bar: self.update_weekly_consolidator(bar))\n\n self.consolidate(symbol, Resolution.DAILY, lambda bar: self.update_trade_bar(bar, 0))\n self._expected_consolidation_counts.append(tradable_dates_count)\n\n self.consolidate(symbol, Resolution.DAILY, TickType.QUOTE, lambda bar: self.update_quote_bar(bar, 1))\n self._expected_consolidation_counts.append(tradable_dates_count)\n\n self.consolidate(symbol, timedelta(1), lambda bar: self.update_trade_bar(bar, 2))\n self._expected_consolidation_counts.append(tradable_dates_count - 1)\n\n self.consolidate(symbol, timedelta(1), TickType.QUOTE, lambda bar: self.update_quote_bar(bar, 3))\n self._expected_consolidation_counts.append(tradable_dates_count - 1)\n\n # sending None tick type\n self.consolidate(symbol, timedelta(1), None, lambda bar: self.update_trade_bar(bar, 4))\n self._expected_consolidation_counts.append(tradable_dates_count - 1)\n\n self.consolidate(symbol, Resolution.DAILY, None, lambda bar: self.update_trade_bar(bar, 5))\n self._expected_consolidation_counts.append(tradable_dates_count)\n\n self._consolidation_counts = [0] * len(self._expected_consolidation_counts)\n self._smas = [SimpleMovingAverage(10) for x in self._consolidation_counts]\n self._last_sma_updates = [datetime.min for x in self._consolidation_counts]\n self._monthly_consolidator_sma = SimpleMovingAverage(10)\n self._monthly_consolidation_count = 0\n self._weekly_consolidator_sma = SimpleMovingAverage(10)\n self._weekly_consolidation_count = 0\n self._last_weekly_sma_update = datetime.min\n\n # custom data\n self._custom_data_consolidator = 0\n custom_symbol = self.add_data(Bitcoin, \"BTC\", Resolution.DAILY).symbol\n self.consolidate(custom_symbol, timedelta(1), lambda bar: self.increment_counter(1))\n\n self._custom_data_consolidator2 = 0\n self.consolidate(custom_symbol, Resolution.DAILY, lambda bar: self.increment_counter(2))\n\n def increment_counter(self, id):\n if id == 1:\n self._custom_data_consolidator += 1\n if id == 2:\n self._custom_data_consolidator2 += 1\n\n def update_trade_bar(self, bar, position):\n self._smas[position].update(bar.end_time, bar.volume)\n self._last_sma_updates[position] = bar.end_time\n self._consolidation_counts[position] += 1\n\n def update_quote_bar(self, bar, position):\n self._smas[position].update(bar.end_time, bar.ask.high)\n self._last_sma_updates[position] = bar.end_time\n self._consolidation_counts[position] += 1\n\n def update_monthly_consolidator(self, bar):\n self._monthly_consolidator_sma.update(bar.end_time, bar.volume)\n self._monthly_consolidation_count += 1\n\n def update_weekly_consolidator(self, bar):\n self._weekly_consolidator_sma.update(bar.end_time, bar.volume)\n self._last_weekly_sma_update = bar.end_time\n self._weekly_consolidation_count += 1\n\n def on_end_of_algorithm(self):\n for i, expected_consolidation_count in enumerate(self._expected_consolidation_counts):\n consolidation_count = self._consolidation_counts[i]\n if consolidation_count != expected_consolidation_count:\n raise ValueError(f\"Unexpected consolidation count for index {i}: expected {expected_consolidation_count} but was {consolidation_count}\")\n\n expected_weekly_consolidations = (self.end_date - self.start_date).days // 7\n if self._weekly_consolidation_count != expected_weekly_consolidations:\n raise ValueError(f\"Expected {expected_weekly_consolidations} weekly consolidations but found {self._weekly_consolidation_count}\")\n\n if self._custom_data_consolidator == 0:\n raise ValueError(\"Custom data consolidator did not consolidate any data\")\n\n if self._custom_data_consolidator2 == 0:\n raise ValueError(\"Custom data consolidator 2 did not consolidate any data\")\n\n for i, sma in enumerate(self._smas):\n if sma.samples != self._expected_consolidation_counts[i]:\n raise AssertionError(f\"Expected {self._expected_consolidation_counts[i]} samples in each SMA but found {sma.samples} in SMA in index {i}\")\n\n last_update = self._last_sma_updates[i]\n if sma.current.time != last_update:\n raise AssertionError(f\"Expected SMA in index {i} to have been last updated at {last_update} but was {sma.current.time}\")\n\n if self._monthly_consolidation_count != 0 or self._monthly_consolidator_sma.samples != 0:\n raise AssertionError(\"Expected monthly consolidator to not have consolidated any data\")\n\n if self._weekly_consolidator_sma.samples != expected_weekly_consolidations:\n raise AssertionError(f\"Expected {expected_weekly_consolidations} samples in the weekly consolidator SMA but found {self._weekly_consolidator_sma.samples}\")\n\n if self._weekly_consolidator_sma.current.time != self._last_weekly_sma_update:\n raise AssertionError(f\"Expected weekly consolidator SMA to have been last updated at {self._last_weekly_sma_update} but was {self._weekly_consolidator_sma.current.time}\")\n\n # on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n def on_data(self, data):\n if not self.portfolio.invested and self._future.has_data:\n self.set_holdings(self._future.symbol, 0.5)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demostrates the use of for creating constant volume bar", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass VolumeRenkoConsolidatorAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(100000)\n\n self._sma = SimpleMovingAverage(10)\n self._tick_consolidated = False\n\n self._spy = self.add_equity(\"SPY\", Resolution.MINUTE).symbol\n self._tradebar_volume_consolidator = VolumeRenkoConsolidator(1000000)\n self._tradebar_volume_consolidator.data_consolidated += self.on_spy_data_consolidated\n\n self._ibm = self.add_equity(\"IBM\", Resolution.TICK).symbol\n self._tick_volume_consolidator = VolumeRenkoConsolidator(1000000)\n self._tick_volume_consolidator.data_consolidated += self.on_ibm_data_consolidated\n\n history = self.history[TradeBar](self._spy, 1000, Resolution.MINUTE)\n for bar in history:\n self._tradebar_volume_consolidator.update(bar)\n\n def on_spy_data_consolidated(self, sender, bar):\n self._sma.update(bar.end_time, bar.value)\n self.debug(f\"SPY {bar.time} to {bar.end_time} :: O:{bar.open} H:{bar.high} L:{bar.low} C:{bar.close} V:{bar.volume}\")\n if bar.volume != 1000000:\n raise AssertionError(\"Volume of consolidated bar does not match set value!\")\n\n def on_ibm_data_consolidated(self, sender, bar):\n self.debug(f\"IBM {bar.time} to {bar.end_time} :: O:{bar.open} H:{bar.high} L:{bar.low} C:{bar.close} V:{bar.volume}\")\n if bar.volume != 1000000:\n raise AssertionError(\"Volume of consolidated bar does not match set value!\")\n self._tick_consolidated = True\n\n def on_data(self, slice):\n # Update by TradeBar\n if slice.bars.contains_key(self._spy):\n self._tradebar_volume_consolidator.update(slice.bars[self._spy])\n\n # Update by Tick\n if slice.ticks.contains_key(self._ibm):\n for tick in slice.ticks[self._ibm]:\n self._tick_volume_consolidator.update(tick)\n\n if self._sma.is_ready and self._sma.current.value < self.securities[self._spy].price:\n self.set_holdings(self._spy, 1)\n else:\n self.set_holdings(self._spy, 0)\n \n def on_end_of_algorithm(self):\n if not self._tick_consolidated:\n raise AssertionError(\"Tick consolidator was never been called\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests option exercise and assignment functionality\nWe open two positions and go with them into expiration. We expect to see our long position exercised and short position assigned.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionSplitRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n\n # this test opens position in the first day of trading, lives through stock split (7 for 1),\n # and closes adjusted position on the second day\n\n self.set_cash(1000000)\n self.set_start_date(2014,6,6)\n self.set_end_date(2014,6,9)\n\n option = self.add_option(\"AAPL\")\n\n # set our strike/expiry filter for this option chain\n option.set_filter(self.universe_func)\n\n self.set_benchmark(\"AAPL\")\n self.contract = None\n\n def on_data(self, slice):\n if not self.portfolio.invested:\n if self.time.hour > 9 and self.time.minute > 0:\n for kvp in slice.option_chains:\n chain = kvp.value\n contracts = filter(lambda x: x.strike == 650 and x.right == OptionRight.CALL, chain)\n sorted_contracts = sorted(contracts, key = lambda x: x.expiry)\n\n if len(sorted_contracts) > 1:\n self.contract = sorted_contracts[1]\n self.buy(self.contract.symbol, 1)\n\n elif self.time.day > 6 and self.time.hour > 14 and self.time.minute > 0:\n self.liquidate()\n\n if self.portfolio.invested:\n options_hold = [x for x in self.portfolio.securities if x.value.holdings.absolute_quantity != 0]\n holdings = options_hold[0].value.holdings.absolute_quantity\n if self.time.day == 6 and holdings != 1:\n self.log(\"Expected position quantity of 1 but was {0}\".format(holdings))\n if self.time.day == 9 and holdings != 7:\n self.log(\"Expected position quantity of 7 but was {0}\".format(holdings))\n\n # set our strike/expiry filter for this option chain\n def universe_func(self, universe):\n return universe.include_weeklys().strikes(-2, 2).expiration(timedelta(0), timedelta(365*2))\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of how to define a universe using the fundamental data", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FundamentalRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2014, 3, 26)\n self.set_end_date(2014, 4, 7)\n\n self.universe_settings.resolution = Resolution.DAILY\n\n self._universe = self.add_universe(self.selection_function)\n\n # before we add any symbol\n self.assert_fundamental_universe_data()\n\n self.add_equity(\"SPY\")\n self.add_equity(\"AAPL\")\n\n # Request fundamental data for symbols at current algorithm time\n ibm = Symbol.create(\"IBM\", SecurityType.EQUITY, Market.USA)\n ibm_fundamental = self.fundamentals(ibm)\n if self.time != self.start_date or self.time != ibm_fundamental.end_time:\n raise ValueError(f\"Unexpected Fundamental time {ibm_fundamental.end_time}\")\n if ibm_fundamental.price == 0:\n raise ValueError(f\"Unexpected Fundamental IBM price!\")\n nb = Symbol.create(\"NB\", SecurityType.EQUITY, Market.USA)\n fundamentals = self.fundamentals([ nb, ibm ])\n if len(fundamentals) != 2:\n raise ValueError(f\"Unexpected Fundamental count {len(fundamentals)}! Expected 2\")\n\n # Request historical fundamental data for symbols\n history = self.history(Fundamental, timedelta(days=2))\n if len(history) != 4:\n raise ValueError(f\"Unexpected Fundamental history count {len(history)}! Expected 4\")\n\n for ticker in [ \"AAPL\", \"SPY\" ]:\n data = history.loc[ticker]\n if data[\"value\"][0] == 0:\n raise ValueError(f\"Unexpected {data} fundamental data\")\n if Object.reference_equals(data.earningreports.iloc[0], data.earningreports.iloc[1]):\n raise ValueError(f\"Unexpected fundamental data instance duplication\")\n if data.earningreports.iloc[0]._time_provider.get_utc_now() == data.earningreports.iloc[1]._time_provider.get_utc_now():\n raise ValueError(f\"Unexpected fundamental data instance duplication\")\n\n self.assert_fundamental_universe_data()\n\n self.changes = None\n self.number_of_symbols_fundamental = 2\n\n def assert_fundamental_universe_data(self):\n # Case A\n universe_data = self.history(self._universe.data_type, [self._universe.symbol], timedelta(days=2), flatten=True)\n self.assert_fundamental_history(universe_data, \"A\")\n\n # Case B (sugar on A)\n universe_data_per_time = self.history(self._universe, timedelta(days=2), flatten=True)\n self.assert_fundamental_history(universe_data_per_time, \"B\")\n\n # Case C: Passing through the unvierse type and symbol\n enumerable_of_data_dictionary = self.history[self._universe.data_type]([self._universe.symbol], 100)\n for selection_collection_for_a_day in enumerable_of_data_dictionary:\n self.assert_fundamental_enumerator(selection_collection_for_a_day[self._universe.symbol], \"C\")\n\n def assert_fundamental_history(self, df, case_name):\n dates = df.index.get_level_values('time').unique()\n if dates.shape[0] != 2:\n raise ValueError(f\"Unexpected Fundamental universe dates count {dates.shape[0]}! Expected 2\")\n\n for date in dates:\n sub_df = df.loc[date]\n if sub_df.shape[0] < 7000:\n raise ValueError(f\"Unexpected historical Fundamentals data count {sub_df.shape[0]} case {case_name}! Expected > 7000\")\n\n def assert_fundamental_enumerator(self, enumerable, case_name):\n data_point_count = 0\n for fundamental in enumerable:\n data_point_count += 1\n if type(fundamental) is not Fundamental:\n raise ValueError(f\"Unexpected Fundamentals data type {type(fundamental)} case {case_name}! {str(fundamental)}\")\n if data_point_count < 7000:\n raise ValueError(f\"Unexpected historical Fundamentals data count {data_point_count} case {case_name}! Expected > 7000\")\n\n # return a list of three fixed symbol objects\n def selection_function(self, fundamental):\n # sort descending by daily dollar volume\n sorted_by_dollar_volume = sorted([x for x in fundamental if x.price > 1],\n key=lambda x: x.dollar_volume, reverse=True)\n\n # sort descending by P/E ratio\n sorted_by_pe_ratio = sorted(sorted_by_dollar_volume, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)\n\n # take the top entries from our sorted collection\n return [ x.symbol for x in sorted_by_pe_ratio[:self.number_of_symbols_fundamental] ]\n\n def on_data(self, data):\n # if we have no changes, do nothing\n if self.changes is None: return\n\n # liquidate removed securities\n for security in self.changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n self.debug(\"Liquidated Stock: \" + str(security.symbol.value))\n\n # we want 50% allocation in each security in our universe\n for security in self.changes.added_securities:\n self.set_holdings(security.symbol, 0.02)\n\n self.changes = None\n\n # this event fires whenever we have changes to our universe\n def on_securities_changed(self, changes):\n self.changes = changes\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests that we receive the expected data when\nwe add future option contracts individually using ", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AddFutureOptionContractDataStreamingRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.on_data_reached = False\n self.invested = False\n self.symbols_received = []\n self.expected_symbols_received = []\n self.data_received = {}\n\n self.set_start_date(2020, 1, 4)\n self.set_end_date(2020, 1, 8)\n\n self.es20h20 = self.add_future_contract(\n Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 3, 20)),\n Resolution.MINUTE).symbol\n\n self.es19m20 = self.add_future_contract(\n Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 6, 19)),\n Resolution.MINUTE).symbol\n\n # Get option contract lists for 2020/01/05 (timedelta(days=1)) because Lean has local data for that date\n option_chains = list(self.option_chain_provider.get_option_contract_list(self.es20h20, self.time + timedelta(days=1)))\n option_chains += self.option_chain_provider.get_option_contract_list(self.es19m20, self.time + timedelta(days=1))\n\n for option_contract in option_chains:\n self.expected_symbols_received.append(self.add_future_option_contract(option_contract, Resolution.MINUTE).symbol)\n\n def on_data(self, data: Slice):\n if not data.has_data:\n return\n\n self.on_data_reached = True\n has_option_quote_bars = False\n\n for qb in data.quote_bars.values():\n if qb.symbol.security_type != SecurityType.FUTURE_OPTION:\n continue\n\n has_option_quote_bars = True\n\n self.symbols_received.append(qb.symbol)\n if qb.symbol not in self.data_received:\n self.data_received[qb.symbol] = []\n\n self.data_received[qb.symbol].append(qb)\n\n if self.invested or not has_option_quote_bars:\n return\n\n if data.contains_key(self.es20h20) and data.contains_key(self.es19m20):\n self.set_holdings(self.es20h20, 0.2)\n self.set_holdings(self.es19m20, 0.2)\n\n self.invested = True\n\n def on_end_of_algorithm(self):\n self.symbols_received = list(set(self.symbols_received))\n self.expected_symbols_received = list(set(self.expected_symbols_received))\n\n if not self.on_data_reached:\n raise AssertionError(\"OnData() was never called.\")\n if len(self.symbols_received) != len(self.expected_symbols_received):\n raise AssertionError(f\"Expected {len(self.expected_symbols_received)} option contracts Symbols, found {len(self.symbols_received)}\")\n\n missing_symbols = [expected_symbol.value for expected_symbol in self.expected_symbols_received if expected_symbol not in self.symbols_received]\n if any(missing_symbols):\n raise AssertionError(f'Symbols: \"{\", \".join(missing_symbols)}\" were not found in OnData')\n\n for expected_symbol in self.expected_symbols_received:\n data = self.data_received[expected_symbol]\n for data_point in data:\n data_point.end_time = datetime(1970, 1, 1)\n\n non_dupe_data_count = len(set(data))\n if non_dupe_data_count < 1000:\n raise AssertionError(f\"Received too few data points. Expected >=1000, found {non_dupe_data_count} for {expected_symbol}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Test algorithm generating insights with custom tags", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nfrom Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel\nfrom Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\nfrom Execution.ImmediateExecutionModel import ImmediateExecutionModel\n\nclass InsightTagAlphaRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,11)\n self.set_cash(100000)\n\n self.universe_settings.resolution = Resolution.DAILY\n\n self.spy = Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n self.fb = Symbol.create(\"FB\", SecurityType.EQUITY, Market.USA)\n self.ibm = Symbol.create(\"IBM\", SecurityType.EQUITY, Market.USA)\n\n # set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel([self.spy, self.fb, self.ibm]))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n\n self.add_alpha(OneTimeAlphaModel(self.spy))\n self.add_alpha(OneTimeAlphaModel(self.fb))\n self.add_alpha(OneTimeAlphaModel(self.ibm))\n\n self.insights_generated += self.on_insights_generated_verifier\n\n self._symbols_with_generated_insights = []\n\n def on_insights_generated_verifier(self, algorithm: IAlgorithm, insights_collection: GeneratedInsightsCollection) -> None:\n for insight in insights_collection.insights:\n if insight.tag != OneTimeAlphaModel.generate_insight_tag(insight.symbol):\n raise AssertionError(\"Unexpected insight tag was emitted\")\n\n self._symbols_with_generated_insights.append(insight.symbol)\n\n def on_end_of_algorithm(self) -> None:\n if len(self._symbols_with_generated_insights) != 3:\n raise AssertionError(\"Unexpected number of symbols with generated insights\")\n\n if not self.spy in self._symbols_with_generated_insights:\n raise AssertionError(\"SPY symbol was not found in symbols with generated insights\")\n\n if not self.fb in self._symbols_with_generated_insights:\n raise AssertionError(\"FB symbol was not found in symbols with generated insights\")\n\n if not self.ibm in self._symbols_with_generated_insights:\n raise AssertionError(\"IBM symbol was not found in symbols with generated insights\")\n\nclass OneTimeAlphaModel(AlphaModel):\n def __init__(self, symbol):\n self._symbol = symbol\n self.triggered = False\n\n def update(self, algorithm, data):\n insights = []\n if not self.triggered:\n self.triggered = True\n insights.append(Insight.price(\n self._symbol,\n Resolution.DAILY,\n 1,\n InsightDirection.DOWN,\n tag=OneTimeAlphaModel.generate_insight_tag(self._symbol)))\n return insights\n\n @staticmethod\n def generate_insight_tag(symbol: Symbol) -> str:\n return f\"Insight generated for {symbol}\"\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: In this algorithm we demonstrate how to perform some technical analysis as\npart of your coarse fundamental universe selection", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass EmaCrossUniverseSelectionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2010,1,1) #Set Start Date\n self.set_end_date(2015,1,1) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self.universe_settings.resolution = Resolution.DAILY\n self.universe_settings.leverage = 2\n\n self.coarse_count = 10\n self.averages = { }\n\n # this add universe method accepts two parameters:\n # - coarse selection function: accepts an IEnumerable and returns an IEnumerable\n self.add_universe(self.coarse_selection_function)\n\n\n # sort the data by daily dollar volume and take the top 'NumberOfSymbols'\n def coarse_selection_function(self, coarse):\n\n # We are going to use a dictionary to refer the object that will keep the moving averages\n for cf in coarse:\n if cf.symbol not in self.averages:\n self.averages[cf.symbol] = SymbolData(cf.symbol)\n\n # Updates the SymbolData object with current EOD price\n avg = self.averages[cf.symbol]\n avg.update(cf.end_time, cf.adjusted_price)\n\n # Filter the values of the dict: we only want up-trending securities\n values = list(filter(lambda x: x.is_uptrend, self.averages.values()))\n\n # Sorts the values of the dict: we want those with greater difference between the moving averages\n values.sort(key=lambda x: x.scale, reverse=True)\n\n for x in values[:self.coarse_count]:\n self.log('symbol: ' + str(x.symbol.value) + ' scale: ' + str(x.scale))\n\n # we need to return only the symbol objects\n return [ x.symbol for x in values[:self.coarse_count] ]\n\n # this event fires whenever we have changes to our universe\n def on_securities_changed(self, changes):\n # liquidate removed securities\n for security in changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n\n # we want 20% allocation in each security in our universe\n for security in changes.added_securities:\n self.set_holdings(security.symbol, 0.1)\n\n\nclass SymbolData(object):\n def __init__(self, symbol):\n self._symbol = symbol\n self.tolerance = 1.01\n self.fast = ExponentialMovingAverage(100)\n self.slow = ExponentialMovingAverage(300)\n self.is_uptrend = False\n self.scale = 0\n\n def update(self, time, value):\n if self.fast.update(time, value) and self.slow.update(time, value):\n fast = self.fast.current.value\n slow = self.slow.current.value\n self.is_uptrend = fast > slow * self.tolerance\n\n if self.is_uptrend:\n self.scale = (fast - slow) / ((fast + slow) / 2.0)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example algorithm defines its own custom coarse/fine fundamental selection model\nwith equally weighted portfolio and a maximum sector exposure.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\nfrom Alphas.ConstantAlphaModel import ConstantAlphaModel\nfrom Execution.ImmediateExecutionModel import ImmediateExecutionModel\nfrom Risk.MaximumSectorExposureRiskManagementModel import MaximumSectorExposureRiskManagementModel\n\nclass SectorExposureRiskFrameworkAlgorithm(QCAlgorithm):\n '''This example algorithm defines its own custom coarse/fine fundamental selection model\n\n def initialize(self):\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.DAILY\n\n self.set_start_date(2014, 3, 25)\n self.set_end_date(2014, 4, 7)\n self.set_cash(100000)\n\n # set algorithm framework models\n self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.select_coarse, self.select_fine))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_risk_management(MaximumSectorExposureRiskManagementModel())\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n self.debug(f\"Order event: {order_event}. Holding value: {self.securities[order_event.symbol].holdings.absolute_holdings_value}\")\n\n def select_coarse(self, coarse):\n tickers = [\"AAPL\", \"AIG\", \"IBM\"] if self.time.date() < date(2014, 4, 1) else [ \"GOOG\", \"BAC\", \"SPY\" ]\n return [Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers]\n\n def select_fine(self, fine):\n return [f.symbol for f in fine]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Tests the mapping of the ETF symbol that has a constituent universe attached to it and ensures\nthat data is loaded after the mapping event takes place.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ETFConstituentUniverseFilterFunctionRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2011, 2, 1)\n self.set_end_date(2011, 4, 4)\n self.set_cash(100000)\n\n self.filter_date_constituent_symbol_count = {}\n self.constituent_data_encountered = {}\n self.constituent_symbols = []\n self.mapping_event_occurred = False\n\n self.universe_settings.resolution = Resolution.HOUR\n\n self.aapl = Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA)\n self.qqq = self.add_equity(\"QQQ\", Resolution.DAILY).symbol\n\n self.add_universe(self.universe.etf(self.qqq, self.universe_settings, self.filter_etfs))\n\n def filter_etfs(self, constituents):\n constituent_symbols = [i.symbol for i in constituents]\n\n if self.aapl not in constituent_symbols:\n raise AssertionError(\"AAPL not found in QQQ constituents\")\n\n self.filter_date_constituent_symbol_count[self.utc_time.date()] = len(constituent_symbols)\n for symbol in constituent_symbols:\n self.constituent_symbols.append(symbol)\n\n self.constituent_symbols = list(set(self.constituent_symbols))\n return constituent_symbols\n\n def on_data(self, data):\n if len(data.symbol_changed_events) != 0:\n for symbol_changed in data.symbol_changed_events.values():\n if symbol_changed.symbol != self.qqq:\n raise AssertionError(f\"Mapped symbol is not QQQ. Instead, found: {symbol_changed.symbol}\")\n if symbol_changed.old_symbol != \"QQQQ\":\n raise AssertionError(f\"Old QQQ Symbol is not QQQQ. Instead, found: {symbol_changed.old_symbol}\")\n if symbol_changed.new_symbol != \"QQQ\":\n raise AssertionError(f\"New QQQ Symbol is not QQQ. Instead, found: {symbol_changed.new_symbol}\")\n\n self.mapping_event_occurred = True\n\n if self.qqq in data and len([i for i in data.keys()]) == 1:\n return\n\n if self.utc_time.date() not in self.constituent_data_encountered:\n self.constituent_data_encountered[self.utc_time.date()] = False\n \n if len([i for i in data.keys() if i in self.constituent_symbols]) != 0:\n self.constituent_data_encountered[self.utc_time.date()] = True\n\n if not self.portfolio.invested:\n self.set_holdings(self.aapl, 0.5)\n\n def on_end_of_algorithm(self):\n if len(self.filter_date_constituent_symbol_count) != 2:\n raise AssertionError(f\"ETF constituent filtering function was not called 2 times (actual: {len(self.filter_date_constituent_symbol_count)}\")\n\n if not self.mapping_event_occurred:\n raise AssertionError(\"No mapping/SymbolChangedEvent occurred. Expected for QQQ to be mapped from QQQQ -> QQQ\")\n\n for constituent_date, constituents_count in self.filter_date_constituent_symbol_count.items():\n if constituents_count < 25:\n raise AssertionError(f\"Expected 25 or more constituents in filter function on {constituent_date}, found {constituents_count}\")\n\n for constituent_date, constituent_encountered in self.constituent_data_encountered.items():\n if not constituent_encountered:\n raise AssertionError(f\"Received data in OnData(...) but it did not contain any constituent data on {constituent_date.strftime('%Y-%m-%d %H:%M:%S.%f')}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to assert the behavior of .", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm\nfrom Risk.MaximumUnrealizedProfitPercentPerSecurity import MaximumUnrealizedProfitPercentPerSecurity\n\nclass MaximumUnrealizedProfitPercentPerSecurityFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):\n\n def initialize(self):\n super().initialize()\n self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA)))\n\n self.set_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.004))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests In The Money (ITM) index option expiry for short calls.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, sell SPX Call Option (expiring ITM)\n * Option assignment\n\nAdditionally, we test delistings for index options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndexOptionShortCallITMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 1, 31)\n self.set_cash(1000000)\n\n self.portfolio.set_margin_call_model(MarginCallModel.NULL);\n\n # avoid getting assigned\n self.set_security_initializer(CompositeSecurityInitializer(self.security_initializer, FuncSecurityInitializer(self.custom_security_initializer)))\n\n self.spx = self.add_index(\"SPX\", Resolution.MINUTE).symbol\n\n # Select a index option expiring ITM, and adds it to the algorithm.\n self.spx_options = list(self.option_chain(self.spx))\n self.spx_option_filtered = [i for i in self.spx_options if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1]\n self.spx_option = list(sorted(self.spx_option_filtered, key=lambda x: x.id.strike_price, reverse=True))[0].symbol\n self.add_index_option_contract(self.spx_option, Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3200, datetime(2021, 1, 15))\n if self.spx_option != self.expected_contract:\n raise AssertionError(f\"Contract self.expected_contract was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1))\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2021, 1, 15):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2021, 1, 16):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n\n if order_event.symbol not in self.securities:\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.spx:\n self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_contract])\n elif security.symbol == self.expected_contract:\n self.assert_index_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security):\n if \"Assignment\" in order_event.message:\n if order_event.fill_price != 3200:\n raise AssertionError(\"Option was not assigned at expected strike price (3200)\")\n\n if order_event.direction != OrderDirection.SELL or index.holdings.quantity != 0:\n raise AssertionError(f\"Expected Qty: 0 index holdings for assigned index option {index.symbol}, found {index.holdings.quantity}\")\n\n def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != -1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n\n if order_event.is_assignment and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after option contract was assigned: {option.symbol}\")\n\n ### \n ### Ran at the end of the algorithm to ensure the algorithm has no holdings\n ### \n ### The algorithm has holdings\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}\")\n\n def custom_security_initializer(self, security):\n if Extensions.is_option(security.symbol.security_type):\n security.set_option_assignment_model(NullOptionAssignmentModel())\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests Out of The Money (OTM) index option expiry for short calls.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, sell SPX Call Option (expiring OTM)\n - Profit the option premium, since the option was not assigned.\n\n * Liquidation of SPX call OTM contract on the last trade date\n\nAdditionally, we test delistings for index options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndexOptionShortCallOTMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 1, 31)\n\n self.spx = self.add_index(\"SPX\", Resolution.MINUTE).symbol\n\n # Select a index option expiring ITM, and adds it to the algorithm.\n self.spx_options = list(self.option_chain(self.spx))\n self.spx_options = [i for i in self.spx_options if i.id.strike_price >= 4250 and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1]\n self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price))[0]\n self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 4250, datetime(2021, 1, 15))\n if self.spx_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1))\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2021, 1, 15):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2021, 1, 16):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if order_event.symbol not in self.securities:\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.spx:\n raise AssertionError(f\"Expected no order events for underlying Symbol {security.symbol}\")\n\n if security.symbol == self.expected_contract:\n self.assert_index_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n def assert_index_option_contract_order(self, order_event: OrderEvent, option_contract: Security):\n if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1:\n raise AssertionError(f\"No holdings were created for option contract {option_contract.symbol}\")\n if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:\n raise AssertionError(\"Expected no options holdings after closing position\")\n if order_event.is_assignment:\n raise AssertionError(f\"Assignment was not expected for {order_event.symbol}\")\n\n ### \n ### Ran at the end of the algorithm to ensure the algorithm has no holdings\n ### \n ### The algorithm has holdings\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: def initialize(self) -> None:", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateIndexOptionsAlgorithm(QCAlgorithm):\n def initialize(self) -> None:\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 2, 1)\n self.set_cash(1000000)\n\n self.spx = self.add_index(\"SPX\", Resolution.MINUTE).symbol\n spx_options = self.add_index_option(self.spx, Resolution.MINUTE)\n spx_options.set_filter(lambda x: x.calls_only())\n\n self.ema_slow = self.ema(self.spx, 80)\n self.ema_fast = self.ema(self.spx, 200)\n\n def on_data(self, data: Slice) -> None:\n if self.spx not in data.bars or not self.ema_slow.is_ready:\n return\n\n for chain in data.option_chains.values():\n for contract in chain.contracts.values():\n if self.portfolio.invested:\n continue\n\n if (self.ema_fast > self.ema_slow and contract.right == OptionRight.CALL) or \\\n (self.ema_fast < self.ema_slow and contract.right == OptionRight.PUT):\n\n self.liquidate(self.invert_option(contract.symbol))\n self.market_order(contract.symbol, 1)\n\n def on_end_of_algorithm(self) -> None:\n if self.portfolio[self.spx].total_sale_volume > 0:\n raise AssertionError(\"Index is not tradable.\")\n\n if self.portfolio.total_sale_volume == 0:\n raise AssertionError(\"Trade volume should be greater than zero by the end of this algorithm\")\n\n def invert_option(self, symbol: Symbol) -> Symbol:\n return Symbol.create_option(\n symbol.underlying,\n symbol.id.market,\n symbol.id.option_style,\n OptionRight.PUT if symbol.id.option_right == OptionRight.CALL else OptionRight.CALL,\n symbol.id.strike_price,\n symbol.id.date\n )\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm showing how to define a custom insight scoring function and using the insight manager", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass InsightScoringRegressionAlgorithm(QCAlgorithm):\n '''Regression algorithm showing how to define a custom insight evaluator'''\n\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,11)\n \n symbols = [ Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA) ]\n\n self.set_universe_selection(ManualUniverseSelectionModel(symbols))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY))\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))\n \n # we specify a custom insight evaluator\n self.insights.set_insight_score_function(CustomInsightScoreFunction(self.securities))\n\n def on_end_of_algorithm(self):\n all_insights = self.insights.get_insights(lambda insight: True)\n\n if len(all_insights) != 100 or len(self.insights.get_insights()) != 100:\n raise ValueError(f'Unexpected insight count found {all_insights.count}')\n\n if sum(1 for insight in all_insights if insight.score.magnitude == 0 or insight.score.direction == 0) < 5:\n raise ValueError(f'Insights not scored!')\n\n if sum(1 for insight in all_insights if insight.score.is_final_score) < 99:\n raise ValueError(f'Insights not finalized!')\n\nclass CustomInsightScoreFunction():\n\n def __init__(self, securities):\n self._securities = securities\n self._open_insights = {}\n\n def score(self, insight_manager, utc_time):\n open_insights = insight_manager.get_active_insights(utc_time)\n\n for insight in open_insights:\n self._open_insights[insight.id] = insight\n\n to_remove = []\n for open_insight in self._open_insights.values():\n security = self._securities[open_insight.symbol]\n open_insight.reference_value_final = security.price\n\n score = open_insight.reference_value_final - open_insight.reference_value\n open_insight.score.set_score(InsightScoreType.DIRECTION, score, utc_time)\n open_insight.score.set_score(InsightScoreType.MAGNITUDE, score * 2, utc_time)\n open_insight.estimated_value = score * 100\n\n if open_insight.is_expired(utc_time):\n open_insight.score.finalize(utc_time)\n to_remove.append(open_insight)\n\n # clean up\n for insight_to_remove in to_remove:\n self._open_insights.pop(insight_to_remove.id)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: The algorithm creates new indicator value with the existing indicator method by Indicator Extensions\nDemonstration of using the external custom data to request the IBM and SPY daily data", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom HistoryAlgorithm import *\n\nclass CustomDataIndicatorExtensionsAlgorithm(QCAlgorithm):\n\n # Initialize the data and resolution you require for your strategy\n def initialize(self):\n\n self.set_start_date(2014,1,1)\n self.set_end_date(2018,1,1)\n self.set_cash(25000)\n\n self.ibm = 'IBM'\n self.spy = 'SPY'\n\n # Define the symbol and \"type\" of our generic data\n self.add_data(CustomDataEquity, self.ibm, Resolution.DAILY)\n self.add_data(CustomDataEquity, self.spy, Resolution.DAILY)\n\n # Set up default Indicators, these are just 'identities' of the closing price\n self.ibm_sma = self.sma(self.ibm, 1, Resolution.DAILY)\n self.spy_sma = self.sma(self.spy, 1, Resolution.DAILY)\n\n # This will create a new indicator whose value is sma_s_p_y / sma_i_b_m\n self.ratio = IndicatorExtensions.over(self.spy_sma, self.ibm_sma)\n\n # Plot indicators each time they update using the PlotIndicator function\n self.plot_indicator(\"Ratio\", self.ratio)\n self.plot_indicator(\"Data\", self.ibm_sma, self.spy_sma)\n\n # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n def on_data(self, data):\n\n # Wait for all indicators to fully initialize\n if not (self.ibm_sma.is_ready and self.spy_sma.is_ready and self.ratio.is_ready): return\n if not self.portfolio.invested and self.ratio.current.value > 1:\n self.market_order(self.ibm, 100)\n elif self.ratio.current.value < 1:\n self.liquidate()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstrate the usage of the BrokerageModel property to help improve backtesting\naccuracy through simulation of a specific brokerage's rules around restrictions\non submitting orders as well as fee structure.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BrokerageModelAlgorithm(QCAlgorithm):\n def initialize(self):\n\n self.set_cash(100000) # Set Strategy Cash\n self.set_start_date(2013,10,7) # Set Start Date\n self.set_end_date(2013,10,11) # Set End Date\n self.add_equity(\"SPY\", Resolution.SECOND)\n \n # there's two ways to set your brokerage model. The easiest would be to call\n # self.set_brokerage_model( BrokerageName ) # BrokerageName is an enum\n # self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE)\n # self.set_brokerage_model(BrokerageName.DEFAULT)\n\n # the other way is to call SetBrokerageModel( IBrokerageModel ) with your\n # own custom model. I've defined a simple extension to the default brokerage\n # model to take into account a requirement to maintain 500 cash in the account at all times\n self.set_brokerage_model(MinimumAccountBalanceBrokerageModel(self,500.00))\n self.last = 1 \n \n def on_data(self, slice):\n # Simple buy and hold template\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", self.last)\n if self.portfolio[\"SPY\"].quantity == 0:\n # each time we fail to purchase we'll decrease our set holdings percentage\n self.debug(str(self.time) + \" - Failed to purchase stock\")\n self.last *= 0.95\n else:\n self.debug(\"{} - Purchased Stock @ SetHoldings( {} )\".format(self.time, self.last))\n\n\nclass MinimumAccountBalanceBrokerageModel(DefaultBrokerageModel):\n '''Custom brokerage model that requires clients to maintain a minimum cash balance'''\n def __init__(self, algorithm, minimum_account_balance):\n self.algorithm = algorithm\n self.minimum_account_balance = minimum_account_balance\n \n def can_submit_order(self,security, order, message):\n '''Prevent orders which would bring the account below a minimum cash balance'''\n message = None\n # we want to model brokerage requirement of minimum_account_balance cash value in account\n order_cost = order.get_value(security)\n cash = self.algorithm.portfolio.cash\n cash_after_order = cash - order_cost\n if cash_after_order < self.minimum_account_balance:\n # return a message describing why we're not allowing this order\n message = BrokerageMessageEvent(BrokerageMessageType.WARNING, \"InsufficientRemainingCapital\", \"Account must maintain a minimum of ${0} USD at all times. Order ID: {1}\".format(self.minimum_account_balance, order.id))\n self.algorithm.error(str(message))\n return False\n return True\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression test to check python indicator is keeping backwards compatibility\nwith indicators that do not set WarmUpPeriod or do not inherit from PythonIndicator class.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom collections import deque\n\nclass CustomWarmUpPeriodIndicatorAlgorithm(QCAlgorithm):\n def initialize(self) -> None:\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.add_equity(\"SPY\", Resolution.SECOND)\n\n # Create three python indicators\n # - custom_not_warm_up does not define WarmUpPeriod parameter\n # - custom_warm_up defines WarmUpPeriod parameter\n # - custom_not_inherit defines WarmUpPeriod parameter but does not inherit from PythonIndicator class\n # - csharp_indicator defines WarmUpPeriod parameter and represents the traditional LEAN C# indicator\n self._custom_not_warm_up = CSMANotWarmUp('custom_not_warm_up', 60)\n self._custom_warm_up = CSMAWithWarmUp('custom_warm_up', 60)\n self._custom_not_inherit = CustomSMA('custom_not_inherit', 60)\n self._csharp_indicator = SimpleMovingAverage('csharp_indicator', 60)\n\n # Register the daily data of \"SPY\" to automatically update the indicators\n self.register_indicator(\"SPY\", self._custom_warm_up, Resolution.MINUTE)\n self.register_indicator(\"SPY\", self._custom_not_warm_up, Resolution.MINUTE)\n self.register_indicator(\"SPY\", self._custom_not_inherit, Resolution.MINUTE)\n self.register_indicator(\"SPY\", self._csharp_indicator, Resolution.MINUTE)\n\n # Warm up custom_warm_up indicator\n self.warm_up_indicator(\"SPY\", self._custom_warm_up, Resolution.MINUTE)\n\n # Check custom_warm_up indicator has already been warmed up with the requested data\n assert(self._custom_warm_up.is_ready), \"custom_warm_up indicator was expected to be ready\"\n assert(self._custom_warm_up.samples == 60), \"custom_warm_up indicator was expected to have processed 60 datapoints already\"\n\n # Try to warm up custom_not_warm_up indicator. It's expected from LEAN to skip the warm up process\n # because this indicator doesn't define WarmUpPeriod parameter\n self.warm_up_indicator(\"SPY\", self._custom_not_warm_up, Resolution.MINUTE)\n\n # Check custom_not_warm_up indicator is not ready and is using the default WarmUpPeriod value\n assert(not self._custom_not_warm_up.is_ready), \"custom_not_warm_up indicator wasn't expected to be warmed up\"\n assert(self._custom_not_warm_up.warm_up_period == 0), \"custom_not_warm_up indicator WarmUpPeriod parameter was expected to be 0\"\n\n # Warm up custom_not_inherit indicator. Though it does not inherit from PythonIndicator class,\n # it defines WarmUpPeriod parameter so it's expected to be warmed up from LEAN\n self.warm_up_indicator(\"SPY\", self._custom_not_inherit, Resolution.MINUTE)\n\n # Check custom_not_inherit indicator has already been warmed up with the requested data\n assert(self._custom_not_inherit.is_ready), \"custom_not_inherit indicator was expected to be ready\"\n assert(self._custom_not_inherit.samples == 60), \"custom_not_inherit indicator was expected to have processed 60 datapoints already\"\n\n # Warm up csharp_indicator\n self.warm_up_indicator(\"SPY\", self._csharp_indicator, Resolution.MINUTE)\n\n # Check csharp_indicator indicator has already been warmed up with the requested data\n assert(self._csharp_indicator.is_ready), \"csharp_indicator indicator was expected to be ready\"\n assert(self._csharp_indicator.samples == 60), \"csharp_indicator indicator was expected to have processed 60 datapoints already\"\n\n def on_data(self, data: Slice) -> None:\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n\n if self.time.second == 0:\n # Compute the difference between indicators values\n diff = abs(self._custom_not_warm_up.current.value - self._custom_warm_up.current.value)\n diff += abs(self._custom_not_inherit.value - self._custom_not_warm_up.current.value)\n diff += abs(self._custom_not_inherit.value - self._custom_warm_up.current.value)\n diff += abs(self._csharp_indicator.current.value - self._custom_warm_up.current.value)\n diff += abs(self._csharp_indicator.current.value - self._custom_not_warm_up.current.value)\n diff += abs(self._csharp_indicator.current.value - self._custom_not_inherit.value)\n\n # Check custom_not_warm_up indicator is ready when the number of samples is bigger than its WarmUpPeriod parameter\n assert(self._custom_not_warm_up.is_ready == (self._custom_not_warm_up.samples >= 60)), \"custom_not_warm_up indicator was expected to be ready when the number of samples were bigger that its WarmUpPeriod parameter\"\n\n # Check their values are the same. We only need to check if custom_not_warm_up indicator is ready because the other ones has already been asserted to be ready\n assert(diff <= 1e-10 or (not self._custom_not_warm_up.is_ready)), f\"The values of the indicators are not the same. Indicators difference is {diff}\"\n \n# Python implementation of SimpleMovingAverage.\n# Represents the traditional simple moving average indicator (SMA) without Warm Up Period parameter defined\nclass CSMANotWarmUp(PythonIndicator):\n def __init__(self, name: str, period: int) -> None:\n super().__init__()\n self.name = name\n self.value = 0\n self._queue = deque(maxlen=period)\n\n # Update method is mandatory\n def update(self, input: IndicatorDataPoint) -> bool:\n self._queue.appendleft(input.value)\n count = len(self._queue)\n self.value = np.sum(self._queue) / count\n return count == self._queue.maxlen\n\n# Python implementation of SimpleMovingAverage.\n# Represents the traditional simple moving average indicator (SMA) With Warm Up Period parameter defined\nclass CSMAWithWarmUp(CSMANotWarmUp):\n def __init__(self, name: str, period: int) -> None:\n super().__init__(name, period)\n self.warm_up_period = period\n\n# Custom python implementation of SimpleMovingAverage.\n# Represents the traditional simple moving average indicator (SMA)\nclass CustomSMA():\n def __init__(self, name: str, period: int) -> None:\n self.name = name\n self.value = 0\n self._queue = deque(maxlen=period)\n self.warm_up_period = period\n self.is_ready = False\n self.samples = 0\n\n # Update method is mandatory\n def update(self, input: IndicatorDataPoint) -> bool:\n self.samples += 1\n self._queue.appendleft(input.value)\n count = len(self._queue)\n self.value = np.sum(self._queue) / count\n if count == self._queue.maxlen:\n self.is_ready = True\n return self.is_ready\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of using an external custom datasource. LEAN Engine is incredibly flexible and allows you to define your own data source.\nThis includes any data source which has a TIME and VALUE. These are the *only* requirements. To demonstrate this we're loading in \"Bitcoin\" data.", "output": "```python\n\n\nfrom AlgorithmImports import *\nimport pytz\n\nclass CustomDataBitcoinAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2011, 9, 13)\n self.set_end_date(datetime.now().date() - timedelta(1))\n self.set_cash(100000)\n\n # Define the symbol and \"type\" of our generic data:\n self.add_data(Bitcoin, \"BTC\")\n\n\n def on_data(self, data):\n if not data.contains_key(\"BTC\"): return\n\n close = data[\"BTC\"].close\n\n # If we don't have any weather \"SHARES\" -- invest\"\n if not self.portfolio.invested:\n # Weather used as a tradable asset, like stocks, futures etc.\n # It's only OK to use SetHoldings with crypto when using custom data. When trading with built-in crypto data, \n # use the cashbook. Reference https://github.com/QuantConnect/Lean/blob/master/Algorithm.python/BasicTemplateCryptoAlgorithm.py \n self.set_holdings(\"BTC\", 1) \n self.debug(\"Buying BTC 'Shares': BTC: {0}\".format(close))\n\n self.debug(\"Time: {0} {1}\".format(datetime.now(), close))\n\n\nclass Bitcoin(PythonData):\n '''Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data'''\n\n def get_source(self, config, date, is_live_mode):\n if is_live_mode:\n return SubscriptionDataSource(\"https://www.bitstamp.net/api/ticker/\", SubscriptionTransportMedium.REST)\n\n #return \"http://my-ftp-server.com/futures-data-\" + date.to_string(\"Ymd\") + \".zip\"\n # OR simply return a fixed small data file. Large files will slow down your backtest\n return SubscriptionDataSource(\"https://www.quantconnect.com/api/v2/proxy/quandl/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc&api_key=WyAazVXnq7ATy_fefTqm\", SubscriptionTransportMedium.REMOTE_FILE)\n\n\n def reader(self, config, line, date, is_live_mode):\n coin = Bitcoin()\n coin.symbol = config.symbol\n\n if is_live_mode:\n # Example Line Format:\n # {\"high\": \"441.00\", \"last\": \"421.86\", \"timestamp\": \"1411606877\", \"bid\": \"421.96\", \"vwap\": \"428.58\", \"volume\": \"14120.40683975\", \"low\": \"418.83\", \"ask\": \"421.99\"}\n try:\n live_btc = json.loads(line)\n\n # If value is zero, return None\n value = live_btc[\"last\"]\n if value == 0: return None\n\n coin.end_time = datetime.now(pytz.timezone(str(config.exchange_time_zone)))\n coin.value = value\n coin[\"Open\"] = float(live_btc[\"open\"])\n coin[\"High\"] = float(live_btc[\"high\"])\n coin[\"Low\"] = float(live_btc[\"low\"])\n coin[\"Close\"] = float(live_btc[\"last\"])\n coin[\"Ask\"] = float(live_btc[\"ask\"])\n coin[\"Bid\"] = float(live_btc[\"bid\"])\n coin[\"VolumeBTC\"] = float(live_btc[\"volume\"])\n coin[\"WeightedPrice\"] = float(live_btc[\"vwap\"])\n return coin\n except ValueError:\n # Do nothing, possible error in json decoding\n return None\n\n # Example Line Format:\n # Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price\n # 2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356\n if not (line.strip() and line[0].isdigit()): return None\n\n try:\n data = line.split(',')\n\n # If value is zero, return None\n value = data[4]\n if value == 0: return None\n\n coin.time = datetime.strptime(data[0], \"%Y-%m-%d\")\n coin.end_time = coin.time + timedelta(days=1)\n coin.value = value\n coin[\"Open\"] = float(data[1])\n coin[\"High\"] = float(data[2])\n coin[\"Low\"] = float(data[3])\n coin[\"Close\"] = float(data[4])\n coin[\"VolumeBTC\"] = float(data[5])\n coin[\"VolumeUSD\"] = float(data[6])\n coin[\"WeightedPrice\"] = float(data[7])\n return coin\n\n except ValueError:\n # Do nothing, possible error in json decoding\n return None\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm shows how to set a custom security initializer.\nA security initializer is run immediately after a new security object\nhas been created and can be used to security models and other settings,\nsuch as data normalization mode", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomSecurityInitializerAlgorithm(QCAlgorithm):\n\n def initialize(self):\n \n # set our initializer to our custom type\n self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE)\n \n func_security_seeder = FuncSecuritySeeder(self.custom_seed_function)\n self.set_security_initializer(CustomSecurityInitializer(self.brokerage_model, func_security_seeder, DataNormalizationMode.RAW))\n \n self.set_start_date(2013,10,1)\n self.set_end_date(2013,11,1)\n\n self.add_equity(\"SPY\", Resolution.HOUR)\n\n def on_data(self, data):\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n\n def custom_seed_function(self, security):\n\n resolution = Resolution.HOUR\n\n df = self.history(security.symbol, 1, resolution)\n if df.empty:\n return None\n\n last_bar = df.unstack(level=0).iloc[-1]\n date_time = last_bar.name.to_pydatetime()\n open = last_bar.open.values[0]\n high = last_bar.high.values[0]\n low = last_bar.low.values[0]\n close = last_bar.close.values[0]\n volume = last_bar.volume.values[0]\n return TradeBar(date_time, security.symbol, open, high, low, close, volume, Extensions.to_time_span(resolution))\n\n\nclass CustomSecurityInitializer(BrokerageModelSecurityInitializer):\n '''Our custom initializer that will set the data normalization mode.\n We sub-class the BrokerageModelSecurityInitializer so we can also\n take advantage of the default model/leverage setting behaviors'''\n\n def __init__(self, brokerage_model, security_seeder, data_normalization_mode):\n '''Initializes a new instance of the CustomSecurityInitializer class with the specified normalization mode\n brokerage_model -- The brokerage model used to get fill/fee/slippage/settlement models\n security_seeder -- The security seeder to be used\n data_normalization_mode -- The desired data normalization mode'''\n self.base = BrokerageModelSecurityInitializer(brokerage_model, security_seeder)\n self.data_normalization_mode = data_normalization_mode\n\n def initialize(self, security):\n '''Initializes the specified security by setting up the models\n security -- The security to be initialized\n seed_security -- True to seed the security, false otherwise'''\n # first call the default implementation\n self.base.initialize(security)\n\n # now apply our data normalization mode\n security.set_data_normalization_mode(self.data_normalization_mode)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration algorithm of time in force order settings.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass TimeInForceAlgorithm(QCAlgorithm):\n\n # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.\n def initialize(self):\n\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,11)\n self.set_cash(100000)\n\n # The default time in force setting for all orders is GoodTilCancelled (GTC),\n # uncomment this line to set a different time in force.\n # We currently only support GTC and DAY.\n # self.default_order_properties.time_in_force = TimeInForce.day\n\n self._symbol = self.add_equity(\"SPY\", Resolution.MINUTE).symbol\n\n self._gtc_order_ticket1 = None\n self._gtc_order_ticket2 = None\n self._day_order_ticket1 = None\n self._day_order_ticket2 = None\n self._gtd_order_ticket1 = None\n self._gtd_order_ticket2 = None\n self._expected_order_statuses = {}\n\n # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n # Arguments:\n # data: Slice object keyed by symbol containing the stock data\n def on_data(self, data):\n\n if not self._gtc_order_ticket1:\n # These GTC orders will never expire and will not be canceled automatically.\n\n self.default_order_properties.time_in_force = TimeInForce.GOOD_TIL_CANCELED\n\n # this order will not be filled before the end of the backtest\n self._gtc_order_ticket1 = self.limit_order(self._symbol, 10, 100)\n self._expected_order_statuses[self._gtc_order_ticket1.order_id] = OrderStatus.SUBMITTED\n\n # this order will be filled before the end of the backtest\n self._gtc_order_ticket2 = self.limit_order(self._symbol, 10, 160)\n self._expected_order_statuses[self._gtc_order_ticket2.order_id] = OrderStatus.FILLED\n\n if not self._day_order_ticket1:\n # These DAY orders will expire at market close,\n # if not filled by then they will be canceled automatically.\n\n self.default_order_properties.time_in_force = TimeInForce.DAY\n\n # this order will not be filled before market close and will be canceled\n self._day_order_ticket1 = self.limit_order(self._symbol, 10, 140)\n self._expected_order_statuses[self._day_order_ticket1.order_id] = OrderStatus.CANCELED\n\n # this order will be filled before market close\n self._day_order_ticket2 = self.limit_order(self._symbol, 10, 180)\n self._expected_order_statuses[self._day_order_ticket2.order_id] = OrderStatus.FILLED\n\n if not self._gtd_order_ticket1:\n # These GTD orders will expire on October 10th at market close,\n # if not filled by then they will be canceled automatically.\n\n self.default_order_properties.time_in_force = TimeInForce.GOOD_TIL_DATE(datetime(2013, 10, 10))\n\n # this order will not be filled before expiry and will be canceled\n self._gtd_order_ticket1 = self.limit_order(self._symbol, 10, 100)\n self._expected_order_statuses[self._gtd_order_ticket1.order_id] = OrderStatus.CANCELED\n\n # this order will be filled before expiry\n self._gtd_order_ticket2 = self.limit_order(self._symbol, 10, 160)\n self._expected_order_statuses[self._gtd_order_ticket2.order_id] = OrderStatus.FILLED\n\n # Order event handler. This handler will be called for all order events, including submissions, fills, cancellations.\n # This method can be called asynchronously, ensure you use proper locks on thread-unsafe objects\n def on_order_event(self, orderEvent):\n self.debug(f\"{self.time} {orderEvent}\")\n\n # End of algorithm run event handler. This method is called at the end of a backtest or live trading operation.\n def on_end_of_algorithm(self):\n for orderId, expectedStatus in self._expected_order_statuses.items():\n order = self.transactions.get_order_by_id(orderId)\n if order.status != expectedStatus:\n raise AssertionError(f\"Invalid status for order {orderId} - Expected: {expectedStatus}, actual: {order.status}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Black-Litterman framework algorithm\nUses the HistoricalReturnsAlphaModel and the BlackLittermanPortfolioConstructionModel\nto create an algorithm that rebalances the portfolio according to Black-Litterman portfolio optimization", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nfrom Alphas.HistoricalReturnsAlphaModel import HistoricalReturnsAlphaModel\nfrom Portfolio.BlackLittermanOptimizationPortfolioConstructionModel import *\nfrom Portfolio.UnconstrainedMeanVariancePortfolioOptimizer import UnconstrainedMeanVariancePortfolioOptimizer\nfrom Risk.NullRiskManagementModel import NullRiskManagementModel\n\nclass BlackLittermanPortfolioOptimizationFrameworkAlgorithm(QCAlgorithm):\n '''Black-Litterman Optimization algorithm.'''\n\n def initialize(self):\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.MINUTE\n\n # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.\n # Commented so regression algorithm is more sensitive\n #self.settings.minimum_order_margin_portfolio_percentage = 0.005\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self._symbols = [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in [ 'AIG', 'BAC', 'IBM', 'SPY' ] ]\n\n optimizer = UnconstrainedMeanVariancePortfolioOptimizer()\n\n # set algorithm framework models\n self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selector))\n self.set_alpha(HistoricalReturnsAlphaModel(resolution = Resolution.DAILY))\n self.set_portfolio_construction(BlackLittermanOptimizationPortfolioConstructionModel(optimizer = optimizer))\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(NullRiskManagementModel())\n\n def coarse_selector(self, coarse):\n # Drops SPY after the 8th\n last = 3 if self.time.day > 8 else len(self._symbols)\n\n return self._symbols[0:last]\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n self.debug(order_event)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.\nThis test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.\n\nAll orders are sent from the brokerage, none of them will be placed by the algorithm.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomBrokerageSideOrderHandlingRegressionAlgorithm(QCAlgorithm):\n '''Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.\n This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.\n\n All orders are sent from the brokerage, none of them will be placed by the algorithm.'''\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(100000)\n\n self.set_brokerage_message_handler(CustomBrokerageMessageHandler(self))\n\n self._spy = Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n\n def on_end_of_algorithm(self):\n # The security should have been added\n if not self.securities.contains_key(self._spy):\n raise AssertionError(\"Expected security to have been added\")\n\n if self.transactions.orders_count == 0:\n raise AssertionError(\"Expected orders to be added from brokerage side\")\n\n if len(list(self.portfolio.positions.groups)) != 1:\n raise AssertionError(\"Expected only one position\")\n\nclass CustomBrokerageMessageHandler(DefaultBrokerageMessageHandler):\n def __init__(self, algorithm):\n self._algorithm = algorithm\n\n def handle_message(self, message):\n self._algorithm.debug(f\"{self._algorithm.time} Event: {message.message}\")\n\n def handle_order(self, event_args):\n order = event_args.order\n if order.tag is None or not order.tag.isdigit():\n raise AssertionError(\"Expected all new brokerage-side orders to have a valid tag\")\n\n # We will only process orders with even tags\n return int(order.tag) % 2 == 0\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of how to chain a coarse and fine universe selection with an option chain universe selection model\nthat will add and remove an'OptionChainUniverse' for each symbol selected on fine", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CoarseFineOptionUniverseChainRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2014,6,4)\n # TWX is selected the 4th and 5th and aapl after that.\n # If the algo ends on the 6th, TWX subscriptions will not be removed before OnEndOfAlgorithm is called:\n # - 6th: AAPL is selected, TWX is removed but subscriptions are not removed because the securities are invested.\n # - TWX and its options are liquidated.\n # - 7th: Since options universe selection is daily now, TWX subscriptions are removed the next day (7th)\n self.set_end_date(2014,6,7)\n\n self.universe_settings.resolution = Resolution.MINUTE\n self._twx = Symbol.create(\"TWX\", SecurityType.EQUITY, Market.USA)\n self._aapl = Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA)\n self._last_equity_added = None\n self._changes = SecurityChanges.NONE\n self._option_count = 0\n\n universe = self.add_universe(self.coarse_selection_function, self.fine_selection_function)\n\n self.add_universe_options(universe, self.option_filter_function)\n\n def option_filter_function(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:\n universe.include_weeklys().front_month()\n\n contracts = list()\n for contract in universe:\n if len(contracts) == 5:\n break\n contracts.append(contract)\n return universe.contracts(contracts)\n\n def coarse_selection_function(self, coarse: list[CoarseFundamental]) -> list[Symbol]:\n if self.time <= datetime(2014,6,5):\n return [ self._twx ]\n return [ self._aapl ]\n\n def fine_selection_function(self, fine: list[FineFundamental]) -> list[Symbol]:\n if self.time <= datetime(2014,6,5):\n return [ self._twx ]\n return [ self._aapl ]\n\n def on_data(self, data: Slice) -> None:\n if self._changes == SecurityChanges.NONE or any(security.price == 0 for security in self._changes.added_securities):\n return\n\n # liquidate removed securities\n for security in self._changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n\n for security in self._changes.added_securities:\n if not security.symbol.has_underlying:\n self._last_equity_added = security.symbol\n else:\n # options added should all match prev added security\n if security.symbol.underlying != self._last_equity_added:\n raise ValueError(f\"Unexpected symbol added {security.symbol}\")\n self._option_count += 1\n\n self.set_holdings(security.symbol, 0.05)\n self._changes = SecurityChanges.NONE\n\n # this event fires whenever we have changes to our universe\n def on_securities_changed(self, changes: SecurityChanges) -> None:\n if self._changes == SecurityChanges.NONE:\n self._changes = changes\n return\n self._changes = self._changes + changes\n\n def on_end_of_algorithm(self) -> None:\n if self._option_count == 0:\n raise ValueError(\"Option universe chain did not add any option!\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Expiry Helper algorithm uses Expiry helper class in an Alpha Model", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ExpiryHelperAlphaModelFrameworkAlgorithm(QCAlgorithm):\n '''Expiry Helper framework algorithm uses Expiry helper class in an Alpha Model'''\n\n def initialize(self) -> None:\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.HOUR\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2014,1,1) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n symbols = [ Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA) ]\n\n # set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel(symbols))\n self.set_alpha(self.ExpiryHelperAlphaModel())\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))\n\n self.insights_generated += self.on_insights_generated\n\n def on_insights_generated(self, s: IAlgorithm, e: GeneratedInsightsCollection) -> None:\n for insight in e.insights:\n self.log(f\"{e.date_time_utc.isoweekday()}: Close Time {insight.close_time_utc} {insight.close_time_utc.isoweekday()}\")\n\n class ExpiryHelperAlphaModel(AlphaModel):\n _next_update = None\n _direction = InsightDirection.UP\n\n def update(self, algorithm: QCAlgorithm, data: Slice) -> list[Insight]:\n if self._next_update and self._next_update > algorithm.time:\n return []\n\n expiry = Expiry.END_OF_DAY\n\n # Use the Expiry helper to calculate a date/time in the future\n self._next_update = expiry(algorithm.time)\n\n weekday = algorithm.time.isoweekday()\n\n insights = []\n for symbol in data.bars.keys():\n # Expected CloseTime: next month on the same day and time\n if weekday == 1:\n insights.append(Insight.price(symbol, Expiry.ONE_MONTH, self._direction))\n # Expected CloseTime: next month on the 1st at market open time\n elif weekday == 2:\n insights.append(Insight.price(symbol, Expiry.END_OF_MONTH, self._direction))\n # Expected CloseTime: next Monday at market open time\n elif weekday == 3:\n insights.append(Insight.price(symbol, Expiry.END_OF_WEEK, self._direction))\n # Expected CloseTime: next day (Friday) at market open time\n elif weekday == 4:\n insights.append(Insight.price(symbol, Expiry.END_OF_DAY, self._direction))\n\n return insights\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm that validates that when using a continuous future (without a filter)\nthe option chains are correctly populated using the mapped symbol.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionContinuousFutureRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2020, 1, 4)\n self.set_end_date(2020, 1, 8)\n \n self.future = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, Market.CME)\n self.set_filter()\n \n self.add_future_option(self.future.symbol, lambda universe: universe.strikes(-1, 1))\n \n self._has_any_option_chain_for_mapped_symbol = False\n\n def set_filter(self):\n \"\"\"Set future filter - override in derived classes for filtered version\"\"\"\n pass\n\n def on_data(self, slice: Slice):\n if len(slice.option_chains) == 0:\n return\n\n self.validate_option_chains(slice)\n \n # OptionChain for mapped symbol\n chain = slice.option_chains[self.future.mapped]\n if chain is None or not any(chain):\n raise RegressionTestException(\"No option chain found for mapped symbol during algorithm execution\")\n\n # Mark that we successfully received a non-empty OptionChain for mapped symbol\n self._has_any_option_chain_for_mapped_symbol = True\n \n def validate_option_chains(self, slice: Slice):\n if len(slice.option_chains) != 1:\n raise RegressionTestException(\"Expected only one option chain for the mapped symbol\")\n\n def on_end_of_algorithm(self):\n if not self._has_any_option_chain_for_mapped_symbol:\n raise RegressionTestException(\"No non-empty option chain found for mapped symbol during algorithm execution\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Custom data universe selection regression algorithm asserting it's behavior. See GH issue #6396", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomDataUniverseRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2014, 3, 24)\n self.set_end_date(2014, 3, 31)\n\n self.current_underlying_symbols = set()\n self.universe_settings.resolution = Resolution.DAILY\n self.add_universe(CoarseFundamental, \"custom-data-universe\", self.selection)\n\n self._selection_time = [datetime(2014, 3, 24), datetime(2014, 3, 25), datetime(2014, 3, 26),\n datetime(2014, 3, 27), datetime(2014, 3, 28), datetime(2014, 3, 29)]\n\n def selection(self, coarse):\n self.debug(f\"Universe selection called: {self.time} Count: {len(coarse)}\")\n\n expected_time = self._selection_time.pop(0)\n if expected_time != self.time:\n raise ValueError(f\"Unexpected selection time {self.time} expected {expected_time}\")\n\n # sort descending by daily dollar volume\n sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)\n\n # return the symbol objects of the top entries from our sorted collection\n underlying_symbols = [ x.symbol for x in sorted_by_dollar_volume[:10] ]\n custom_symbols = []\n for symbol in underlying_symbols:\n custom_symbols.append(Symbol.create_base(MyPyCustomData, symbol))\n return underlying_symbols + custom_symbols\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n custom_data = data.get(MyPyCustomData)\n if len(custom_data) > 0:\n for symbol in sorted(self.current_underlying_symbols, key=lambda x: x.id.symbol):\n if not self.securities[symbol].has_data:\n continue\n self.set_holdings(symbol, 1 / len(self.current_underlying_symbols))\n\n if len([x for x in custom_data.keys() if x.underlying == symbol]) == 0:\n raise ValueError(f\"Custom data was not found for symbol {symbol}\")\n\n def on_end_of_algorithm(self):\n if len(self._selection_time) != 0:\n raise ValueError(f\"Unexpected selection times, missing {len(self._selection_time)}\")\n\n def OnSecuritiesChanged(self, changes):\n for security in changes.AddedSecurities:\n if security.symbol.security_type == SecurityType.BASE:\n continue\n self.current_underlying_symbols.add(security.Symbol)\n\n for security in changes.RemovedSecurities:\n if security.symbol.security_type == SecurityType.BASE:\n continue\n self.current_underlying_symbols.remove(security.Symbol)\n\nclass MyPyCustomData(PythonData):\n\n def get_source(self, config, date, is_live_mode):\n source = f\"{Globals.data_folder}/equity/usa/daily/{LeanData.generate_zip_file_name(config.symbol, date, config.resolution, config.tick_type)}\"\n return SubscriptionDataSource(source)\n\n def reader(self, config, line, date, is_live_mode):\n csv = line.split(',')\n _scaleFactor = 1 / 10000\n\n custom = MyPyCustomData()\n custom.symbol = config.symbol\n custom.time = datetime.strptime(csv[0], '%Y%m%d %H:%M')\n custom.open = float(csv[1]) * _scaleFactor\n custom.high = float(csv[2]) * _scaleFactor\n custom.low = float(csv[3]) * _scaleFactor\n custom.close = float(csv[4]) * _scaleFactor\n custom.value = float(csv[4]) * _scaleFactor\n custom.period = Time.ONE_DAY\n custom.end_time = custom.time + custom.period\n\n return custom\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template framework algorithm uses framework components to define the algorithm.\nLiquid ETF Competition template", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nfrom Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\nfrom Execution.ImmediateExecutionModel import ImmediateExecutionModel\n\nclass LiquidETFUniverseFrameworkAlgorithm(QCAlgorithm):\n '''Basic template framework algorithm uses framework components to define the algorithm.'''\n\n def initialize(self):\n # Set Start Date so that backtest has 5+ years of data\n self.set_start_date(2014, 11, 1)\n # No need to set End Date as the final submission will be tested\n # up until the review date\n\n # Set $1m Strategy Cash to trade significant AUM\n self.set_cash(1000000)\n\n # Add a relevant benchmark, with the default being SPY\n self.set_benchmark('SPY')\n\n # Use the Alpha Streams Brokerage Model, developed in conjunction with\n # funds to model their actual fees, costs, etc.\n # Please do not add any additional reality modelling, such as Slippage, Fees, Buying Power, etc.\n self.set_brokerage_model(AlphaStreamsBrokerageModel())\n\n # Use the LiquidETFUniverse with minute-resolution data\n self.universe_settings.resolution = Resolution.MINUTE\n self.set_universe_selection(LiquidETFUniverse())\n\n # Optional\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n\n # List of symbols we want to trade. Set it in OnSecuritiesChanged\n self._symbols = []\n\n def on_data(self, slice):\n\n if all([self.portfolio[x].invested for x in self._symbols]):\n return\n\n # Emit insights\n insights = [Insight.price(x, timedelta(1), InsightDirection.UP)\n for x in self._symbols if self.securities[x].price > 0]\n\n if len(insights) > 0:\n self.emit_insights(insights)\n\n def on_securities_changed(self, changes):\n\n # Set symbols as the Inverse Energy ETFs\n for security in changes.added_securities:\n if security.symbol in LiquidETFUniverse.ENERGY.inverse:\n self._symbols.append(security.symbol)\n\n # Print out the information about the groups\n self.log(f'Energy: {LiquidETFUniverse.ENERGY}')\n self.log(f'Metals: {LiquidETFUniverse.METALS}')\n self.log(f'Technology: {LiquidETFUniverse.TECHNOLOGY}')\n self.log(f'Treasuries: {LiquidETFUniverse.TREASURIES}')\n self.log(f'Volatility: {LiquidETFUniverse.VOLATILITY}')\n self.log(f'SP500Sectors: {LiquidETFUniverse.SP_500_SECTORS}')\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Show cases how to use the CompositeRiskManagementModel.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CompositeRiskManagementModelFrameworkAlgorithm(QCAlgorithm):\n '''Show cases how to use the CompositeRiskManagementModel.'''\n\n def initialize(self):\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.MINUTE\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n # set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel([Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)]))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n\n # define risk management model as a composite of several risk management models\n self.set_risk_management(CompositeRiskManagementModel(\n MaximumUnrealizedProfitPercentPerSecurity(0.01),\n MaximumDrawdownPercentPerSecurity(0.01)\n ))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Framework algorithm that uses the G10CurrencySelectionModel,\na Universe Selection Model that inherits from ManualUniverseSelectionModel", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel\n\nclass G10CurrencySelectionModel(ManualUniverseSelectionModel):\n '''Provides an implementation of IUniverseSelectionModel that simply subscribes to G10 currencies'''\n def __init__(self):\n '''Initializes a new instance of the G10CurrencySelectionModel class\n using the algorithm's security initializer and universe settings'''\n super().__init__([Symbol.create(x, SecurityType.FOREX, Market.OANDA)\n for x in [ \"EURUSD\",\n \"GBPUSD\",\n \"USDJPY\",\n \"AUDUSD\",\n \"NZDUSD\",\n \"USDCAD\",\n \"USDCHF\",\n \"USDNOK\",\n \"USDSEK\" ]])\n\nclass G10CurrencySelectionModelFrameworkAlgorithm(QCAlgorithm):\n '''Framework algorithm that uses the G10CurrencySelectionModel,\n a Universe Selection Model that inherits from ManualUniverseSelectionMode'''\n\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.MINUTE\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n # set algorithm framework models\n self.set_universe_selection(G10CurrencySelectionModel())\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n self.debug(\"Purchased Stock: {0}\".format(order_event.symbol))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm of using MeanReversionPortfolioConstructionModel", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Portfolio.MeanReversionPortfolioConstructionModel import *\n\nclass MeanReversionPortfolioAlgorithm(QCAlgorithm):\n '''Example algorithm of using MeanReversionPortfolioConstructionModel'''\n\n def initialize(self):\n # Set starting date, cash and ending date of the backtest\n self.set_start_date(2020, 9, 1)\n self.set_end_date(2021, 2, 28)\n self.set_cash(100000)\n\n self.set_security_initializer(lambda security: security.set_market_price(self.get_last_known_price(security)))\n \n # Subscribe to data of the selected stocks\n self._symbols = [self.add_equity(ticker, Resolution.DAILY).symbol for ticker in [\"SPY\", \"AAPL\"]]\n\n self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))\n self.set_portfolio_construction(MeanReversionPortfolioConstructionModel())\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests In The Money (ITM) future option calls across different strike prices.\nWe expect 6 orders from the algorithm, which are:\n\n * (1) Initial entry, buy ES Call Option (ES19M20 expiring ITM)\n * (2) Initial entry, sell ES Call Option at different strike (ES20H20 expiring ITM)\n * [2] Option assignment, opens a position in the underlying (ES20H20, Qty: -1)\n * [2] Future contract liquidation, due to impending expiry\n * [1] Option exercise, receive 1 ES19M20 future contract\n * [1] Liquidate ES19M20 contract, due to expiry\n\nAdditionally, we test delistings for future options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionBuySellCallIntradayRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 6, 30)\n\n self.es20h20 = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 3, 20)\n ),\n Resolution.MINUTE).symbol\n\n self.es19m20 = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 6, 19)\n ),\n Resolution.MINUTE).symbol\n\n # Select a future option expiring ITM, and adds it to the algorithm.\n self.es_options = [\n self.add_future_option_contract(i, Resolution.MINUTE).symbol\n for i in (list(self.option_chain(self.es19m20)) + list(self.option_chain(self.es20h20)))\n if i.id.strike_price == 3200.0 and i.id.option_right == OptionRight.CALL\n ]\n\n self.expected_contracts = [\n Symbol.create_option(self.es20h20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200.0, datetime(2020, 3, 20)),\n Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200.0, datetime(2020, 6, 19))\n ]\n\n for es_option in self.es_options:\n if es_option not in self.expected_contracts:\n raise AssertionError(f\"Contract {es_option} was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.schedule_callback_buy)\n\n def schedule_callback_buy(self):\n self.market_order(self.es_options[0], 1)\n self.market_order(self.es_options[1], -1)\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Strategy example using a portfolio of ETF Global Rotation", "output": "```python\n\n\nfrom AlgorithmImports import *\n\n\nclass ETFGlobalRotationAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_cash(25000)\n self.set_start_date(2007,1,1)\n self.last_rotation_time = datetime.min\n self.rotation_interval = timedelta(days=30)\n self.first = True\n\n # these are the growth symbols we'll rotate through\n growth_symbols =[\"MDY\", # US S&P mid cap 400\n \"IEV\", # i_shares S&P europe 350\n \"EEM\", # i_shared MSCI emerging markets\n \"ILF\", # i_shares S&P latin america\n \"EPP\" ] # i_shared MSCI Pacific ex-Japan\n\n # these are the safety symbols we go to when things are looking bad for growth\n safety_symbols = [\"EDV\", \"SHY\"] # \"EDV\" Vangaurd TSY 25yr, \"SHY\" Barclays Low Duration TSY\n # we'll hold some computed data in these guys\n self.symbol_data = []\n for symbol in list(set(growth_symbols) | set(safety_symbols)):\n self.add_security(SecurityType.EQUITY, symbol, Resolution.MINUTE)\n self.one_month_performance = self.mom(symbol, 30, Resolution.DAILY)\n self.three_month_performance = self.mom(symbol, 90, Resolution.DAILY)\n self.symbol_data.append((symbol, self.one_month_performance, self.three_month_performance))\n\n def on_data(self, data):\n # the first time we come through here we'll need to do some things such as allocation\n # and initializing our symbol data\n\n if self.first:\n self.first = False\n self.last_rotation_time = self.time\n return\n delta = self.time - self.last_rotation_time\n if delta > self.rotation_interval:\n self.last_rotation_time = self.time\n\n ordered_obj_scores = sorted(self.symbol_data, key=lambda x: Score(x[1].current.value,x[2].current.value).objective_score(), reverse=True)\n for x in ordered_obj_scores:\n self.log(\">>SCORE>>\" + x[0] + \">>\" + str(Score(x[1].current.value,x[2].current.value).objective_score()))\n # pick which one is best from growth and safety symbols\n best_growth = ordered_obj_scores[0]\n if Score(best_growth[1].current.value,best_growth[2].current.value).objective_score() > 0:\n if (self.portfolio[best_growth[0]].quantity == 0):\n self.log(\"PREBUY>>LIQUIDATE>>\")\n self.liquidate()\n self.log(\">>BUY>>\" + str(best_growth[0]) + \"@\" + str(100 * best_growth[1].current.value))\n qty = self.portfolio.margin_remaining / self.securities[best_growth[0]].close\n self.market_order(best_growth[0], int(qty))\n else:\n # if no one has a good objective score then let's hold cash this month to be safe\n self.log(\">>LIQUIDATE>>CASH\")\n self.liquidate()\n\nclass Score(object):\n\n def __init__(self,one_month_performance_value,three_month_performance_value):\n self.one_month_performance = one_month_performance_value\n self.three_month_performance = three_month_performance_value\n\n def objective_score(self):\n weight1 = 100\n weight2 = 75\n return (weight1 * self.one_month_performance + weight2 * self.three_month_performance) / (weight1 + weight2)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm illustrating the usage of the \nmethod to get a future chain.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FuturesChainFullDataRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 7)\n\n future = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE).symbol\n\n chain = self.futures_chain(future, flatten=True)\n\n # Demonstration using data frame:\n df = chain.data_frame\n\n for index, row in df.iterrows():\n if row['bidprice'] == 0 and row['askprice'] == 0 and row['volume'] == 0:\n raise AssertionError(\"FuturesChain() returned contract with no data.\");\n\n # Get contracts expiring within 6 months, with the latest expiration date, and lowest price\n contracts = df.loc[(df.expiry <= self.time + timedelta(days=180))]\n contracts = contracts.sort_values(['expiry', 'lastprice'], ascending=[False, True])\n self._future_contract = contracts.index[0]\n\n self.add_future_contract(self._future_contract)\n\n def on_data(self, data):\n # Do some trading with the selected contract for sample purposes\n if not self.portfolio.invested:\n self.set_holdings(self._future_contract, 0.5)\n else:\n self.liquidate()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to test we can specify a custom brokerage model, and override some of its methods", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomBrokerageModelRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,11)\n self.set_brokerage_model(CustomBrokerageModel())\n self.add_equity(\"SPY\", Resolution.DAILY)\n self.add_equity(\"AIG\", Resolution.DAILY)\n self.update_request_submitted = False\n\n if self.brokerage_model.default_markets[SecurityType.EQUITY] != Market.USA:\n raise AssertionError(f\"The default market for Equity should be {Market.USA}\")\n if self.brokerage_model.default_markets[SecurityType.CRYPTO] != Market.BINANCE:\n raise AssertionError(f\"The default market for Crypto should be {Market.BINANCE}\")\n\n def on_data(self, slice):\n if not self.portfolio.invested:\n self.market_order(\"SPY\", 100.0)\n self.aig_ticket = self.market_order(\"AIG\", 100.0)\n\n def on_order_event(self, order_event):\n spy_ticket = self.transactions.get_order_ticket(order_event.order_id)\n if self.update_request_submitted == False:\n update_order_fields = UpdateOrderFields()\n update_order_fields.quantity = spy_ticket.quantity + 10\n spy_ticket.update(update_order_fields)\n self.spy_ticket = spy_ticket\n self.update_request_submitted = True\n\n def on_end_of_algorithm(self):\n submit_expected_message = \"BrokerageModel declared unable to submit order: [2] Information - Code: - Symbol AIG can not be submitted\"\n if self.aig_ticket.submit_request.response.error_message != submit_expected_message:\n raise AssertionError(f\"Order with ID: {self.aig_ticket.order_id} should not have submitted symbol AIG\")\n update_expected_message = \"OrderID: 1 Information - Code: - This order can not be updated\"\n if self.spy_ticket.update_requests[0].response.error_message != update_expected_message:\n raise AssertionError(f\"Order with ID: {self.spy_ticket.order_id} should have been updated\")\n\nclass CustomBrokerageModel(DefaultBrokerageModel):\n default_markets = { SecurityType.EQUITY: Market.USA, SecurityType.CRYPTO : Market.BINANCE }\n\n def can_submit_order(self, security: Security, order: Order, message: BrokerageMessageEvent):\n if security.symbol.value == \"AIG\":\n message = BrokerageMessageEvent(BrokerageMessageType.INFORMATION, \"\", \"Symbol AIG can not be submitted\")\n return False, message\n return True, None\n\n def can_update_order(self, security: Security, order: Order, request: UpdateOrderRequest, message: BrokerageMessageEvent):\n message = BrokerageMessageEvent(BrokerageMessageType.INFORMATION, \"\", \"This order can not be updated\")\n return False, message\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests In The Money (ITM) index option calls across different strike prices.\nWe expect 4* orders from the algorithm, which are:\n\n * (1) Initial entry, buy SPX Call Option (SPXF21 expiring ITM)\n * (2) Initial entry, sell SPX Call Option at different strike (SPXF21 expiring ITM)\n * [2] Option assignment, settle into cash\n * [1] Option exercise, settle into cash\n\nAdditionally, we test delistings for index options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.\n\n* Assignments are counted as orders", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndexOptionBuySellCallIntradayRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 1, 31)\n\n spx = self.add_index(\"SPX\", Resolution.MINUTE).symbol\n\n # Select a index option expiring ITM, and adds it to the algorithm.\n spx_options = list(sorted([\n self.add_index_option_contract(i, Resolution.MINUTE).symbol \\\n for i in self.option_chain(spx)\\\n if (i.id.strike_price == 3700 or i.id.strike_price == 3800) and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1],\n key=lambda x: x.id.strike_price\n ))\n\n expectedContract3700 = Symbol.create_option(\n spx,\n Market.USA,\n OptionStyle.EUROPEAN,\n OptionRight.CALL,\n 3700,\n datetime(2021, 1, 15)\n )\n\n expectedContract3800 = Symbol.create_option(\n spx,\n Market.USA,\n OptionStyle.EUROPEAN,\n OptionRight.CALL,\n 3800,\n datetime(2021, 1, 15)\n )\n\n if len(spx_options) != 2:\n raise AssertionError(f\"Expected 2 index options symbols from chain provider, found {spx_options.count}\")\n\n if spx_options[0] != expectedContract3700:\n raise AssertionError(f\"Contract {expectedContract3700} was not found in the chain, found instead: {spx_options[0]}\")\n\n if spx_options[1] != expectedContract3800:\n raise AssertionError(f\"Contract {expectedContract3800} was not found in the chain, found instead: {spx_options[1]}\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(spx, 1), lambda: self.after_market_open_trade(spx_options))\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.noon, lambda: self.liquidate())\n\n def after_market_open_trade(self, spx_options):\n self.market_order(spx_options[0], 1)\n self.market_order(spx_options[1], -1)\n\n ### \n ### Ran at the end of the algorithm to ensure the algorithm has no holdings\n ### \n ### The algorithm has holdings\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm demonstrating use of map files with custom data", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomDataUsingMapFileRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.\n self.set_start_date(2013, 6, 27)\n self.set_end_date(2013, 7, 2)\n\n self.initial_mapping = False\n self.execution_mapping = False\n self.foxa = Symbol.create(\"FOXA\", SecurityType.EQUITY, Market.USA)\n self._symbol = self.add_data(CustomDataUsingMapping, self.foxa).symbol\n\n for config in self.subscription_manager.subscription_data_config_service.get_subscription_data_configs(self._symbol):\n if config.resolution != Resolution.MINUTE:\n raise ValueError(\"Expected resolution to be set to Minute\")\n\n def on_data(self, slice):\n date = self.time.date()\n if slice.symbol_changed_events.contains_key(self._symbol):\n mapping_event = slice.symbol_changed_events[self._symbol]\n self.log(\"{0} - Ticker changed from: {1} to {2}\".format(str(self.time), mapping_event.old_symbol, mapping_event.new_symbol))\n\n if date == datetime(2013, 6, 27).date():\n # we should Not receive the initial mapping event\n if mapping_event.new_symbol != \"NWSA\" or mapping_event.old_symbol != \"FOXA\":\n raise AssertionError(\"Unexpected mapping event mapping_event\")\n self.initial_mapping = True\n\n if date == datetime(2013, 6, 29).date():\n if mapping_event.new_symbol != \"FOXA\" or mapping_event.old_symbol != \"NWSA\":\n raise AssertionError(\"Unexpected mapping event mapping_event\")\n self.set_holdings(self._symbol, 1)\n self.execution_mapping = True\n\n def on_end_of_algorithm(self):\n if self.initial_mapping:\n raise AssertionError(\"The ticker generated the initial rename event\")\n if not self.execution_mapping:\n raise AssertionError(\"The ticker did not rename throughout the course of its life even though it should have\")\n\nclass CustomDataUsingMapping(PythonData):\n '''Test example custom data showing how to enable the use of mapping.\n Implemented as a wrapper of existing NWSA->FOXA equity'''\n\n def get_source(self, config, date, is_live_mode):\n return TradeBar().get_source(SubscriptionDataConfig(config, CustomDataUsingMapping,\n # create a new symbol as equity so we find the existing data files\n Symbol.create(config.mapped_symbol, SecurityType.EQUITY, config.market)),\n date,\n is_live_mode)\n\n def reader(self, config, line, date, is_live_mode):\n return TradeBar.parse_equity(config, line, date)\n\n def requires_mapping(self):\n '''True indicates mapping should be done'''\n return True\n\n def is_sparse_data(self):\n '''Indicates that the data set is expected to be sparse'''\n return True\n\n def default_resolution(self):\n '''Gets the default resolution for this data and security type'''\n return Resolution.MINUTE\n\n def supported_resolutions(self):\n '''Gets the supported resolution for this data and security type'''\n return [ Resolution.MINUTE ]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: A demonstration algorithm to check there can be placed an order of a pair not present\nin the brokerage using the conversion between stablecoins", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass StableCoinsRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2018, 5, 1)\n self.set_end_date(2018, 5, 2)\n self.set_cash(\"USDT\", 200000000)\n self.set_brokerage_model(BrokerageName.BINANCE, AccountType.CASH)\n self.add_crypto(\"BTCUSDT\", Resolution.HOUR, Market.BINANCE)\n\n def on_data(self, data):\n if not self.portfolio.invested:\n self.set_holdings(\"BTCUSDT\", 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Adds a universe with a custom data type and retrieves historical data\nwhile preserving the custom data type.", "output": "```python\n\n\nfrom datetime import timedelta\nfrom AlgorithmImports import *\n\nclass PersistentCustomDataUniverseRegressionAlgorithm(QCAlgorithm):\n\n def Initialize(self):\n self.set_start_date(2018, 6, 1)\n self.set_end_date(2018, 6, 19)\n\n universe = self.add_universe(StockDataSource, \"my-stock-data-source\", Resolution.DAILY, self.universe_selector)\n self._universe_symbol = universe.symbol\n self.retrieve_historical_data()\n self._data_received = False\n\n def universe_selector(self, data):\n return [x.symbol for x in data]\n \n def retrieve_historical_data(self):\n history = list(self.history[StockDataSource](self._universe_symbol, datetime(2018, 1, 1), datetime(2018, 6, 1), Resolution.DAILY))\n if (len(history) == 0):\n raise AssertionError(f\"No historical data received for symbol {self._universe_symbol}.\")\n\n # Ensure all values are of type StockDataSource\n for item in history:\n if not isinstance(item, StockDataSource):\n raise AssertionError(f\"Unexpected data type in history. Expected StockDataSource but received {type(item).__name__}.\")\n \n def OnData(self, slice: Slice):\n if self._universe_symbol not in slice:\n raise AssertionError(f\"No data received for the universe symbol: {self._universe_symbol}.\")\n if (not self._data_received):\n self.retrieve_historical_data()\n self._data_received = True\n \n def OnEndOfAlgorithm(self) -> None:\n if not self._data_received:\n raise AssertionError(\"No data was received after the universe selection.\")\n\nclass StockDataSource(PythonData):\n\n def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live: bool) -> SubscriptionDataSource:\n source = \"../../../Tests/TestData/daily-stock-picker-backtest.csv\"\n return SubscriptionDataSource(source)\n\n def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live: bool) -> BaseData:\n if not (line.strip() and line[0].isdigit()): return None\n\n stocks = StockDataSource()\n stocks.symbol = config.symbol\n\n try:\n csv = line.split(',')\n stocks.time = datetime.strptime(csv[0], \"%Y%m%d\")\n stocks.end_time = stocks.time + self.period\n stocks[\"Symbols\"] = csv[1:]\n\n except ValueError:\n return None\n\n return stocks\n @property\n def period(self) -> timedelta:\n return timedelta(days=1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm asserting that when setting custom models for canonical securities, a one-time warning is sent\ninforming the user that the contracts models are different (not the custom ones).", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionModelsConsistencyRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n security = self.initialize_algorithm()\n self.set_models(security)\n\n # Using a custom security initializer derived from BrokerageModelSecurityInitializer\n # to check that the models are correctly set in the security even when the\n # security initializer is derived from said class in Python\n self.set_security_initializer(CustomSecurityInitializer(self.brokerage_model, SecuritySeeder.NULL))\n\n self.set_benchmark(lambda x: 0)\n\n def initialize_algorithm(self) -> Security:\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n\n equity = self.add_equity(\"GOOG\", leverage=4)\n option = self.add_option(equity.symbol)\n option.set_filter(lambda u: u.strikes(-2, +2).expiration(0, 180))\n\n return option\n\n def set_models(self, security: Security) -> None:\n security.set_fill_model(CustomFillModel())\n security.set_fee_model(CustomFeeModel())\n security.set_buying_power_model(CustomBuyingPowerModel())\n security.set_slippage_model(CustomSlippageModel())\n security.set_volatility_model(CustomVolatilityModel())\n\nclass CustomSecurityInitializer(BrokerageModelSecurityInitializer):\n def __init__(self, brokerage_model: IBrokerageModel, security_seeder: ISecuritySeeder):\n super().__init__(brokerage_model, security_seeder)\n\nclass CustomFillModel(FillModel):\n pass\n\nclass CustomFeeModel(FeeModel):\n pass\n\nclass CustomBuyingPowerModel(BuyingPowerModel):\n pass\n\nclass CustomSlippageModel(ConstantSlippageModel):\n def __init__(self):\n super().__init__(0)\n\nclass CustomVolatilityModel(BaseVolatilityModel):\n pass\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic algorithm demonstrating how to place LimitIfTouched orders.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom collections import deque\n\nclass LimitIfTouchedRegressionAlgorithm(QCAlgorithm):\n\n asynchronous_orders = False\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(100000)\n self.add_equity(\"SPY\")\n\n self.expected_events = deque([\n \"Time: 10/10/2013 13:31:00 OrderID: 72 EventID: 399 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: $144.6434 LimitPrice: $144.3551 TriggerPrice: $143.61 OrderFee: 1 USD\",\n \"Time: 10/10/2013 15:57:00 OrderID: 73 EventID: 156 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: $145.6636 LimitPrice: $145.6434 TriggerPrice: $144.89 OrderFee: 1 USD\",\n \"Time: 10/11/2013 15:37:00 OrderID: 74 EventID: 380 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: $146.7185 LimitPrice: $146.6723 TriggerPrice: $145.92 OrderFee: 1 USD\"\n ])\n\n def on_data(self, data):\n if data.contains_key(\"SPY\"):\n if len(self.transactions.get_open_orders()) == 0:\n self._negative = 1 if self.time.day < 9 else -1\n order_request = SubmitOrderRequest(OrderType.LIMIT_IF_TOUCHED, SecurityType.EQUITY, \"SPY\",\n self._negative * 10, 0,\n data[\"SPY\"].price - self._negative,\n data[\"SPY\"].price - 0.25 * self._negative, self.utc_time,\n f\"LIT - Quantity: {self._negative * 10}\",\n asynchronous=self.asynchronous_orders)\n self._request = self.transactions.add_order(order_request)\n return\n\n if self._request is not None:\n if self._request.quantity == 1:\n self.transactions.cancel_open_orders()\n self._request = None\n return\n\n new_quantity = int(self._request.quantity - self._negative)\n self._request.update_quantity(new_quantity, f\"LIT - Quantity: {new_quantity}\")\n self._request.update_trigger_price(Extensions.round_to_significant_digits(self._request.get(OrderField.TRIGGER_PRICE), 5))\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n expected = self.expected_events.popleft()\n if str(order_event) != expected:\n raise AssertionError(f\"order_event {order_event.id} differed from {expected}. Actual {order_event}\")\n\n def on_end_of_algorithm(self):\n for ticket in self.transactions.get_order_tickets():\n if ticket.submit_request.asynchronous != self.asynchronous_orders:\n raise AssertionError(\"Expected all orders to have the same asynchronous flag as the algorithm.\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm is expected to fail and verifies that a training event\ncreated in Initialize will get run AND it will cause the algorithm to fail if it\nexceeds the \"algorithm-manager-time-loop-maximum\" config value, which the regression\ntest sets to 0.5 minutes.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom time import sleep\n\nclass TrainingInitializeRegressionAlgorithm(QCAlgorithm):\n '''Example algorithm showing how to use QCAlgorithm.train method'''\n\n def initialize(self):\n\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n\n self.add_equity(\"SPY\", Resolution.DAILY)\n\n # this should cause the algorithm to fail\n # the regression test sets the time limit to 30 seconds and there's one extra\n # minute in the bucket, so a two minute sleep should result in RuntimeError\n self.train(lambda: sleep(150))\n\n # DateRules.tomorrow combined with TimeRules.midnight enforces that this event schedule will\n # have exactly one time, which will fire between the first data point and the next day at\n # midnight. So after the first data point, it will run this event and sleep long enough to\n # exceed the static max algorithm time loop time and begin to consume from the leaky bucket\n # the regression test sets the \"algorithm-manager-time-loop-maximum\" value to 30 seconds\n self.train(self.date_rules.tomorrow, self.time_rules.midnight, lambda: sleep(60))\n # this will consume the single 'minute' available in the leaky bucket\n # and the regression test will confirm that the leaky bucket is empty\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to add and trade SPX index weekly options", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateSPXWeeklyIndexOptionsAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 1, 10)\n self.set_cash(1000000)\n\n # regular option SPX contracts\n self.spx_options = self.add_index_option(\"SPX\")\n self.spx_options.set_filter(lambda u: (u.strikes(0, 1).expiration(0, 30)))\n\n # weekly option SPX contracts\n spxw = self.add_index_option(\"SPX\", \"SPXW\")\n # set our strike/expiry filter for this option chain\n spxw.set_filter(lambda u: (u.strikes(0, 1)\n # single week ahead since there are many SPXW contracts and we want to preserve performance\n .expiration(0, 7)\n .include_weeklys()))\n\n self.spxw_option = spxw.symbol\n\n def on_data(self,slice):\n if self.portfolio.invested: return\n\n chain = slice.option_chains.get(self.spxw_option)\n if not chain:\n return\n\n # we sort the contracts to find at the money (ATM) contract with closest expiration\n contracts = sorted(sorted(sorted(chain, \\\n key = lambda x: x.expiry), \\\n key = lambda x: abs(chain.underlying.price - x.strike)), \\\n key = lambda x: x.right, reverse=True)\n\n # if found, buy until it expires\n if len(contracts) == 0: return\n symbol = contracts[0].symbol\n self.market_order(symbol, 1)\n\n def on_order_event(self, order_event):\n self.debug(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to add options for a given underlying equity security.\nIt also shows how you can prefilter contracts easily based on strikes and expirations, and how you\ncan inspect the option chain to pick a specific option contract to trade.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateOptionsDailyAlgorithm(QCAlgorithm):\n underlying_ticker = \"AAPL\"\n\n def initialize(self):\n self.set_start_date(2015, 12, 15)\n self.set_end_date(2016, 2, 1)\n self.set_cash(100000)\n self.option_expired = False\n\n equity = self.add_equity(self.underlying_ticker, Resolution.DAILY)\n option = self.add_option(self.underlying_ticker, Resolution.DAILY)\n self.option_symbol = option.symbol\n\n # set our strike/expiry filter for this option chain\n option.set_filter(lambda u: (u.calls_only().expiration(0, 60)))\n\n # use the underlying equity as the benchmark\n self.set_benchmark(equity.symbol)\n\n def on_data(self,slice):\n if self.portfolio.invested: return\n\n chain = slice.option_chains.get(self.option_symbol)\n if not chain:\n return\n\n # Grab us the contract nearest expiry\n contracts = sorted(chain, key = lambda x: x.expiry)\n\n # if found, trade it\n if len(contracts) == 0: return\n symbol = contracts[0].symbol\n self.market_order(symbol, 1)\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n\n # Check for our expected OTM option expiry\n if \"OTM\" in order_event.message:\n\n # Assert it is at midnight 1/16 (5AM UTC)\n if order_event.utc_time.month != 1 and order_event.utc_time.day != 16 and order_event.utc_time.hour != 5:\n raise AssertionError(f\"Expiry event was not at the correct time, {order_event.utc_time}\")\n\n self.option_expired = True\n\n def on_end_of_algorithm(self):\n # Assert we had our option expire and fill a liquidation order\n if not self.option_expired:\n raise AssertionError(\"Algorithm did not process the option expiration like expected\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests Out of The Money (OTM) index option expiry for short calls.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, sell SPX Call Option (expiring OTM)\n - Profit the option premium, since the option was not assigned.\n\n * Liquidation of SPX call OTM contract on the last trade date\n\nAdditionally, we test delistings for index options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndexOptionShortCallOTMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 1, 31)\n\n self.spx = self.add_index(\"SPX\", Resolution.MINUTE).symbol\n\n # Select a index option expiring ITM, and adds it to the algorithm.\n self.spx_options = list(self.option_chain(self.spx))\n self.spx_options = [i for i in self.spx_options if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1]\n self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price, reverse=True))[0]\n self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.PUT, 3200, datetime(2021, 1, 15))\n if self.spx_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1))\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2021, 1, 15):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2021, 1, 16):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if order_event.symbol not in self.securities:\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.spx:\n raise AssertionError(f\"Expected no order events for underlying Symbol {security.symbol}\")\n\n if security.symbol == self.expected_contract:\n self.assert_index_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n def assert_index_option_contract_order(self, order_event: OrderEvent, option_contract: Security):\n if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1:\n raise AssertionError(f\"No holdings were created for option contract {option_contract.symbol}\")\n if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:\n raise AssertionError(\"Expected no options holdings after closing position\")\n if order_event.is_assignment:\n raise AssertionError(f\"Assignment was not expected for {order_event.symbol}\")\n\n ### \n ### Ran at the end of the algorithm to ensure the algorithm has no holdings\n ### \n ### The algorithm has holdings\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: def initialize(self) -> None:", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateIndexAlgorithm(QCAlgorithm):\n def initialize(self) -> None:\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 1, 18)\n self.set_cash(1000000)\n\n # Use indicator for signal; but it cannot be traded\n self.spx = self.add_index(\"SPX\", Resolution.MINUTE).symbol\n\n # Trade on SPX ITM calls\n self.spx_option = Symbol.create_option(\n self.spx,\n Market.USA,\n OptionStyle.EUROPEAN,\n OptionRight.CALL,\n 3200,\n datetime(2021, 1, 15)\n )\n\n self.add_index_option_contract(self.spx_option, Resolution.MINUTE)\n\n self.ema_slow = self.ema(self.spx, 80)\n self.ema_fast = self.ema(self.spx, 200)\n\n def on_data(self, data: Slice):\n if self.spx not in data.bars or self.spx_option not in data.bars:\n return\n\n if not self.ema_slow.is_ready:\n return\n\n if self.ema_fast > self.ema_slow:\n self.set_holdings(self.spx_option, 1)\n else:\n self.liquidate()\n\n def on_end_of_algorithm(self) -> None:\n if self.portfolio[self.spx].total_sale_volume > 0:\n raise AssertionError(\"Index is not tradable.\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests In The Money (ITM) index option expiry for calls.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, buy SPX Call Option (expiring ITM)\n * Option exercise, settles into cash\n\nAdditionally, we test delistings for index options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndexOptionCallITMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 1, 31)\n self.set_cash(100000)\n\n self.spx = self.add_index(\"SPX\", Resolution.MINUTE).symbol\n\n # Select an index option expiring ITM, and adds it to the algorithm.\n self.spx_options = list(self.option_chain(self.spx))\n 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]\n self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price, reverse=True))[0]\n self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol\n\n self.expected_option_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3200, datetime(2021, 1, 15))\n if self.spx_option != self.expected_option_contract:\n raise AssertionError(f\"Contract {self.expected_option_contract} was not found in the chain\")\n\n self.schedule.on(\n self.date_rules.tomorrow,\n self.time_rules.after_market_open(self.spx, 1),\n lambda: self.market_order(self.spx_option, 1)\n )\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2021, 1, 15):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2021, 1, 16):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if order_event.symbol not in self.securities:\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.spx:\n self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_option_contract])\n elif security.symbol == self.expected_option_contract:\n self.assert_index_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n 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}\")\n\n def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security):\n # No way to detect option exercise orders or any other kind of special orders\n # other than matching strings, for now.\n if \"Option Exercise\" in order_event.message:\n if order_event.fill_price != 3200:\n raise AssertionError(\"Option did not exercise at expected strike price (3200)\")\n\n if option_contract.holdings.quantity != 0:\n raise AssertionError(f\"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}\")\n\n def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after a filled option exercise\")\n if \"Exercise\" in order_event.message and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after exercising option contract {option.symbol}\")\n\n ### \n ### Ran at the end of the algorithm to ensure the algorithm has no holdings\n ### \n ### The algorithm has holdings\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic algorithm using SetAccountCurrency", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicSetAccountCurrencyAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2018, 4, 4) #Set Start Date\n self.set_end_date(2018, 4, 4) #Set End Date\n self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH)\n self.set_account_currency_and_amount()\n\n self._btc_eur = self.add_crypto(\"BTCEUR\").symbol\n\n def set_account_currency_and_amount(self):\n # Before setting any cash or adding a Security call SetAccountCurrency\n self.set_account_currency(\"EUR\")\n self.set_cash(100000) #Set Strategy Cash\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(self._btc_eur, 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Custom data universe selection regression algorithm asserting it's behavior. See GH issue #6396", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass NoUniverseSelectorRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2014, 3, 24)\n self.set_end_date(2014, 3, 31)\n\n self.universe_settings.resolution = Resolution.DAILY\n self.add_universe(CoarseFundamental)\n self.changes = None\n\n def on_data(self, data):\n # if we have no changes, do nothing\n if not self.changes: return\n\n # liquidate removed securities\n for security in self.changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n\n active_and_with_data_securities = sum(x.value.has_data for x in self.active_securities)\n # we want 1/N allocation in each security in our universe\n for security in self.changes.added_securities:\n if security.has_data:\n self.set_holdings(security.symbol, 1 / active_and_with_data_securities)\n self.changes = None\n\n def on_securities_changed(self, changes):\n self.changes = changes\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting we can specify a custom portfolio\noptimizer with a MeanVarianceOptimizationPortfolioConstructionModel", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom MeanVarianceOptimizationFrameworkAlgorithm import MeanVarianceOptimizationFrameworkAlgorithm\n\nclass CustomPortfolioOptimizerRegressionAlgorithm(MeanVarianceOptimizationFrameworkAlgorithm):\n def initialize(self):\n super().initialize()\n self.set_portfolio_construction(MeanVarianceOptimizationPortfolioConstructionModel(timedelta(days=1), PortfolioBias.LONG_SHORT, 1, 63, Resolution.DAILY, 0.02, CustomPortfolioOptimizer()))\n\nclass CustomPortfolioOptimizer:\n def optimize(self, historical_returns, expected_returns, covariance):\n return [0.5]*(np.array(historical_returns)).shape[1]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic algorithm demonstrating how to place stop limit orders.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass StopLimitOrderRegressionAlgorithm(QCAlgorithm):\n '''Basic algorithm demonstrating how to place stop limit orders.'''\n\n tolerance = 0.001\n fast_period = 30\n slow_period = 60\n asynchronous_orders = False\n\n def initialize(self):\n self.set_start_date(2013, 1, 1)\n self.set_end_date(2017, 1, 1)\n self.set_cash(100000)\n\n self._symbol = self.add_equity(\"SPY\", Resolution.DAILY).symbol\n\n self._fast = self.ema(self._symbol, self.fast_period, Resolution.DAILY)\n self._slow = self.ema(self._symbol, self.slow_period, Resolution.DAILY)\n\n self._buy_order_ticket: OrderTicket = None\n self._sell_order_ticket: OrderTicket = None\n self._previous_slice: Slice = None\n\n def on_data(self, slice: Slice):\n if not self.is_ready():\n return\n\n security = self.securities[self._symbol]\n if self._buy_order_ticket is None and self.trend_is_up():\n self._buy_order_ticket = self.stop_limit_order(self._symbol, 100, stop_price=security.high * 1.10, limit_price=security.high * 1.11, asynchronous=self.asynchronous_orders)\n elif self._buy_order_ticket.status == OrderStatus.FILLED and self._sell_order_ticket is None and self.trend_is_down():\n self._sell_order_ticket = self.stop_limit_order(self._symbol, -100, stop_price=security.low * 0.99, limit_price=security.low * 0.98, asynchronous=self.asynchronous_orders)\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status == OrderStatus.FILLED:\n order = self.transactions.get_order_by_id(order_event.order_id)\n if not order.stop_triggered:\n raise AssertionError(\"StopLimitOrder StopTriggered should haven been set if the order filled.\")\n\n if order_event.direction == OrderDirection.BUY:\n limit_price = self._buy_order_ticket.get(OrderField.LIMIT_PRICE)\n if order_event.fill_price > limit_price:\n raise AssertionError(f\"Buy stop limit order should have filled with price less than or equal to the limit price {limit_price}. \"\n f\"Fill price: {order_event.fill_price}\")\n else:\n limit_price = self._sell_order_ticket.get(OrderField.LIMIT_PRICE)\n if order_event.fill_price < limit_price:\n raise AssertionError(f\"Sell stop limit order should have filled with price greater than or equal to the limit price {limit_price}. \"\n f\"Fill price: {order_event.fill_price}\")\n\n def on_end_of_algorithm(self):\n for ticket in self.transactions.get_order_tickets():\n if ticket.submit_request.asynchronous != self.asynchronous_orders:\n raise AssertionError(\"Expected all orders to have the same asynchronous flag as the algorithm.\")\n\n def is_ready(self):\n return self._fast.is_ready and self._slow.is_ready\n\n def trend_is_up(self):\n return self.is_ready() and self._fast.current.value > self._slow.current.value * (1 + self.tolerance)\n\n def trend_is_down(self):\n return self.is_ready() and self._fast.current.value < self._slow.current.value * (1 + self.tolerance)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm used to verify that get_data(type) correctly retrieves\nthe latest custom data stored in the security cache.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom CustomDataRegressionAlgorithm import Bitcoin\n\nclass CustomDataSecurityCacheGetDataRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n self.set_start_date(2020,1,5)\n self.set_end_date(2020,1,10)\n\n self.add_data(Bitcoin, \"BTC\", Resolution.DAILY)\n\n seeder = FuncSecuritySeeder(self.get_last_known_prices)\n self.set_security_initializer(lambda x: seeder.seed_security(x))\n\n def on_data(self, data: Slice) -> None:\n bitcoin = self.securities['BTC'].cache.get_data(Bitcoin)\n if bitcoin is None:\n raise RegressionTestException(\"Expected Bitcoin data in cache, but none was found\")\n if bitcoin.value == 0:\n raise RegressionTestException(\"Expected Bitcoin value to be non-zero\")\n \n bitcoin_from_slice = list(data.get(Bitcoin).values())[0]\n if bitcoin_from_slice != bitcoin:\n raise RegressionTestException(\"Expected cached Bitcoin to match the one from Slice\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm illustrating the usage of the method\nto get multiple future option chains.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionChainsMultipleFullDataRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 1, 6)\n self.set_end_date(2020, 1, 6)\n\n es_future_contract = self.add_future_contract(\n Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 3, 20)),\n Resolution.MINUTE).symbol\n\n gc_future_contract = self.add_future_contract(\n Symbol.create_future(Futures.Metals.GOLD, Market.COMEX, datetime(2020, 4, 28)),\n Resolution.MINUTE).symbol\n\n chains = self.option_chains([es_future_contract, gc_future_contract], flatten=True)\n\n self._es_option_contract = self.get_contract(chains, es_future_contract)\n self._gc_option_contract = self.get_contract(chains, gc_future_contract)\n\n self.add_future_option_contract(self._es_option_contract)\n self.add_future_option_contract(self._gc_option_contract)\n\n def get_contract(self, chains: OptionChains, underlying: Symbol) -> Symbol:\n df = chains.data_frame\n\n # Index by the requested underlying, by getting all data with canonicals which underlying is the requested underlying symbol:\n canonicals = df.index.get_level_values('canonical')\n condition = [canonical for canonical in canonicals if canonical.underlying == underlying]\n contracts = df.loc[condition]\n\n # Get contracts expiring within 4 months, with the latest expiration date, highest strike and lowest price\n contracts = contracts.loc[(df.expiry <= self.time + timedelta(days=120))]\n contracts = contracts.sort_values(['expiry', 'strike', 'lastprice'], ascending=[False, False, True])\n\n return contracts.index[0][1]\n\n def on_data(self, data):\n # Do some trading with the selected contract for sample purposes\n if not self.portfolio.invested:\n self.set_holdings(self._es_option_contract, 0.25)\n self.set_holdings(self._gc_option_contract, 0.25)\n else:\n self.liquidate()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm sends a list of portfolio targets to Collective2 API every time the ema indicators crosses between themselves.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass Collective2SignalExportDemonstrationAlgorithm(QCAlgorithm):\n\n def initialize(self):\n ''' Initialize the date and add all equity symbols present in list _symbols '''\n\n self.set_start_date(2013, 10, 7) #Set Start Date\n self.set_end_date(2013, 10, 11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n # Symbols accepted by Collective2. Collective2 accepts stock, future, forex and US stock option symbols\n self.add_equity(\"GOOG\")\n self._symbols = [\n Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA),\n Symbol.create(\"EURUSD\", SecurityType.FOREX, Market.OANDA),\n Symbol.create_future(\"ES\", Market.CME, datetime(2023, 12, 15)),\n Symbol.create_option(\"GOOG\", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 130, datetime(2023, 9, 1))\n ]\n self.targets = []\n\n # Create a new PortfolioTarget for each symbol, assign it an initial amount of 0.05 and save it in self.targets list\n for item in self._symbols:\n symbol = self.add_security(item).symbol\n if symbol.security_type == SecurityType.EQUITY or symbol.security_type == SecurityType.FOREX:\n self.targets.append(PortfolioTarget(symbol, 0.05))\n else:\n self.targets.append(PortfolioTarget(symbol, 1))\n\n self.fast = self.ema(\"SPY\", 10)\n self.slow = self.ema(\"SPY\", 100)\n\n # Initialize these flags, to check when the ema indicators crosses between themselves\n self.ema_fast_is_not_set = True\n self.ema_fast_was_above = False\n\n # Set Collective2 export provider\n # Collective2 APIv4 KEY: This value is provided by Collective2 in your account section (See https://collective2.com/account-info)\n # See API documentation at https://trade.collective2.com/c2-api\n self.collective2_apikey = \"YOUR APIV4 KEY\"\n\n # Collective2 System ID: This value is found beside the system's name (strategy's name) on the main system page\n self.collective2_system_id = 0\n\n # Disable automatic exports as we manually set them\n self.signal_export.automatic_export_time_span = None\n\n # If using the Collective2 white-label API, you can specify it in the constructor with the optional parameter `use_white_label_api`:\n # e.g. Collective2SignalExport(self.collective2_apikey, self.collective2_system_id, use_white_label_api=True)\n # The API url can also be overridden by setting the Destination property:\n # e.g. Collective2SignalExport(self.collective2_apikey, self.collective2_system_id) { Destination = new Uri(\"your url\") }\n self.signal_export.add_signal_export_provider(Collective2SignalExport(self.collective2_apikey, self.collective2_system_id))\n\n self.first_call = True\n\n self.set_warm_up(100)\n\n def on_data(self, data):\n ''' Reduce the quantity of holdings for one security and increase the holdings to the another\n one when the EMA's indicators crosses between themselves, then send a signal to Collective2 API '''\n if self.is_warming_up: return\n\n # Place an order as soon as possible to send a signal.\n if self.first_call:\n self.set_holdings(\"SPY\", 0.1)\n self.targets[0] = PortfolioTarget(self.portfolio[\"SPY\"].symbol, 0.1)\n self.signal_export.set_target_portfolio(self.targets)\n self.first_call = False\n\n fast = self.fast.current.value\n slow = self.slow.current.value\n\n # Set the value of flag _ema_fast_was_above, to know when the ema indicators crosses between themselves\n if self.ema_fast_is_not_set == True:\n if fast > slow *1.001:\n self.ema_fast_was_above = True\n else:\n self.ema_fast_was_above = False\n self.ema_fast_is_not_set = False\n\n # Check whether ema fast and ema slow crosses. If they do, set holdings to SPY\n # or reduce its holdings, change its value in self.targets list and send signals\n # to Collective2 API from self.targets\n if fast > slow * 1.001 and (not self.ema_fast_was_above):\n self.set_holdings(\"SPY\", 0.1)\n self.targets[0] = PortfolioTarget(self.portfolio[\"SPY\"].symbol, 0.1)\n self.signal_export.set_target_portfolio(self.targets)\n elif fast < slow * 0.999 and (self.ema_fast_was_above):\n self.set_holdings(\"SPY\", 0.01)\n self.targets[0] = PortfolioTarget(self.portfolio[\"SPY\"].symbol, 0.01)\n self.signal_export.set_target_portfolio(self.targets)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm demonstrating how to get order events in custom execution models\nand asserting that they match the algorithm's order events.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ExecutionModelOrderEventsRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self._order_events = []\n self.universe_settings.resolution = Resolution.MINUTE\n\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(100000)\n\n self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes=20), 0.025, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY))\n\n self._execution_model = CustomImmediateExecutionModel()\n self.set_execution(self._execution_model)\n self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))\n\n def on_order_event(self, order_event):\n self._order_events.append(order_event)\n\n def on_end_of_algorithm(self):\n if len(self._execution_model.order_events) != len(self._order_events):\n raise Exception(f\"Order events count mismatch. Execution model: {len(self._execution_model.order_events)}, Algorithm: {len(self._order_events)}\")\n\n for i, (model_event, algo_event) in enumerate(zip(self._execution_model.order_events, self._order_events)):\n if (model_event.id != algo_event.id or\n model_event.order_id != algo_event.order_id or\n model_event.status != algo_event.status):\n raise Exception(f\"Order event mismatch at index {i}. Execution model: {model_event}, Algorithm: {algo_event}\")\n\nclass CustomImmediateExecutionModel(ExecutionModel):\n def __init__(self):\n self._targets_collection = PortfolioTargetCollection()\n self._order_tickets = {}\n self.order_events = []\n\n def execute(self, algorithm, targets):\n self._targets_collection.add_range(targets)\n if not self._targets_collection.is_empty:\n for target in self._targets_collection.order_by_margin_impact(algorithm):\n security = algorithm.securities[target.symbol]\n\n # calculate remaining quantity to be ordered\n quantity = OrderSizing.get_unordered_quantity(algorithm, target, security, True)\n\n if (quantity != 0 and\n BuyingPowerModelExtensions.above_minimum_order_margin_portfolio_percentage(security.buying_power_model,\n security, quantity, algorithm.portfolio, algorithm.settings.minimum_order_margin_portfolio_percentage)):\n ticket = algorithm.market_order(security.symbol, quantity, asynchronous=True, tag=target.tag)\n self._order_tickets[ticket.order_id] = ticket\n\n self._targets_collection.clear_fulfilled(algorithm)\n\n def on_order_event(self, algorithm, order_event):\n algorithm.log(f\"{algorithm.time} - Order event received: {order_event}\")\n\n # This method will get events for all orders, but if we save the tickets in Execute we can filter\n # to process events for orders placed by this model\n if order_event.order_id in self._order_tickets:\n ticket = self._order_tickets[order_event.order_id]\n if order_event.status.is_fill():\n algorithm.debug(f\"Purchased Stock: {order_event.symbol}\")\n if order_event.status.is_closed():\n del self._order_tickets[order_event.order_id]\n\n self.order_events.append(order_event)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template algorithm simply initializes the date range and cash. This is a skeleton\nframework you can use for designing an algorithm.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndicatorSuiteAlgorithm(QCAlgorithm):\n '''Demonstration algorithm of popular indicators and plotting them.'''\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self._symbol = \"SPY\"\n self._symbol2 = \"GOOG\"\n self.custom_symbol = \"IBM\"\n self.price = 0.0\n\n self.set_start_date(2013, 1, 1) #Set Start Date\n self.set_end_date(2014, 12, 31) #Set End Date\n self.set_cash(25000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n\n self.add_equity(self._symbol, Resolution.DAILY)\n self.add_equity(self._symbol2, Resolution.DAILY)\n self.add_data(CustomData, self.custom_symbol, Resolution.DAILY)\n\n # Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object)\n self.indicators = {\n 'BB' : self.bb(self._symbol, 20, 1, MovingAverageType.SIMPLE, Resolution.DAILY),\n 'RSI' : self.rsi(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY),\n 'EMA' : self.ema(self._symbol, 14, Resolution.DAILY),\n 'SMA' : self.sma(self._symbol, 14, Resolution.DAILY),\n 'MACD' : self.macd(self._symbol, 12, 26, 9, MovingAverageType.SIMPLE, Resolution.DAILY),\n 'MOM' : self.mom(self._symbol, 20, Resolution.DAILY),\n 'MOMP' : self.momp(self._symbol, 20, Resolution.DAILY),\n 'STD' : self.std(self._symbol, 20, Resolution.DAILY),\n # by default if the symbol is a tradebar type then it will be the min of the low property\n 'MIN' : self.min(self._symbol, 14, Resolution.DAILY),\n # by default if the symbol is a tradebar type then it will be the max of the high property\n 'MAX' : self.max(self._symbol, 14, Resolution.DAILY),\n 'ATR' : self.atr(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY),\n 'AROON' : self.aroon(self._symbol, 20, Resolution.DAILY),\n 'B' : self.b(self._symbol, self._symbol2, 14)\n }\n\n # Here we're going to define indicators using 'selector' functions. These 'selector' functions will define what data gets sent into the indicator\n # These functions have a signature like the following: decimal Selector(BaseData base_data), and can be defined like: base_data => base_data.value\n # We'll define these 'selector' functions to select the Low value\n #\n # For more information on 'anonymous functions' see: http:#en.wikipedia.org/wiki/Anonymous_function\n # https:#msdn.microsoft.com/en-us/library/bb397687.aspx\n #\n self.selector_indicators = {\n 'BB' : self.bb(self._symbol, 20, 1, MovingAverageType.SIMPLE, Resolution.DAILY, Field.LOW),\n 'RSI' :self.rsi(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY, Field.LOW),\n 'EMA' :self.ema(self._symbol, 14, Resolution.DAILY, Field.LOW),\n 'SMA' :self.sma(self._symbol, 14, Resolution.DAILY, Field.LOW),\n 'MACD' : self.macd(self._symbol, 12, 26, 9, MovingAverageType.SIMPLE, Resolution.DAILY, Field.LOW),\n 'MOM' : self.mom(self._symbol, 20, Resolution.DAILY, Field.LOW),\n 'MOMP' : self.momp(self._symbol, 20, Resolution.DAILY, Field.LOW),\n 'STD' : self.std(self._symbol, 20, Resolution.DAILY, Field.LOW),\n 'MIN' : self.min(self._symbol, 14, Resolution.DAILY, Field.HIGH),\n 'MAX' : self.max(self._symbol, 14, Resolution.DAILY, Field.LOW),\n # ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar\n # before it gets sent to the ATR/AROON indicator, here we use a function that will multiply the input trade bar by a factor of two\n 'ATR' : self.atr(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY, self.selector_double__trade_bar),\n 'AROON' : self.aroon(self._symbol, 20, Resolution.DAILY, self.selector_double__trade_bar)\n }\n\n # Custom Data Indicator:\n self.rsi_custom = self.rsi(self.custom_symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY)\n self.min_custom = self.min(self.custom_symbol, 14, Resolution.DAILY)\n self.max_custom = self.max(self.custom_symbol, 14, Resolution.DAILY)\n\n # in addition to defining indicators on a single security, you can all define 'composite' indicators.\n # these are indicators that require multiple inputs. the most common of which is a ratio.\n # suppose we seek the ratio of BTC to SPY, we could write the following:\n spy_close = Identity(self._symbol)\n ibm_close = Identity(self.custom_symbol)\n\n # this will create a new indicator whose value is IBM/SPY\n self.ratio = IndicatorExtensions.over(ibm_close, spy_close)\n\n # we can also easily plot our indicators each time they update using th PlotIndicator function\n self.plot_indicator(\"Ratio\", self.ratio)\n\n # The following methods will add multiple charts to the algorithm output.\n # Those chatrs names will be used later to plot different series in a particular chart.\n # For more information on Lean Charting see: https://www.quantconnect.com/docs#Charting\n Chart('BB')\n Chart('STD')\n Chart('ATR')\n Chart('AROON')\n Chart('MACD')\n Chart('Averages')\n # Here we make use of the Schelude method to update the plots once per day at market close.\n self.schedule.on(self.date_rules.every_day(), self.time_rules.before_market_close(self._symbol), self.update_plots)\n\n def on_data(self, data: Slice):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n\n if (#not data.bars.contains_key(self._symbol) or\n not self.indicators['BB'].is_ready or\n not self.indicators['RSI'].is_ready):\n return\n\n if not data.bars.contains_key(self._symbol):\n return\n\n self.price = data[self._symbol].close\n\n if not self.portfolio.hold_stock:\n quantity = int(self.portfolio.cash / self.price)\n self.order(self._symbol, quantity)\n self.debug('Purchased SPY on ' + self.time.strftime('%Y-%m-%d'))\n\n def update_plots(self):\n if not self.indicators['BB'].is_ready or not self.indicators['STD'].is_ready:\n return\n\n # Plots can also be created just with this one line command.\n self.plot('RSI', self.indicators['RSI'])\n # Custom data indicator\n self.plot('RSI-FB', self.rsi_custom)\n\n # Here we make use of the chats decalred in the Initialize method, plotting multiple series\n # in each chart.\n self.plot('STD', 'STD', self.indicators['STD'].current.value)\n\n self.plot('BB', 'Price', self.price)\n self.plot('BB', 'BollingerUpperBand', self.indicators['BB'].upper_band.current.value)\n self.plot('BB', 'BollingerMiddleBand', self.indicators['BB'].middle_band.current.value)\n self.plot('BB', 'BollingerLowerBand', self.indicators['BB'].lower_band.current.value)\n\n\n self.plot('AROON', 'Aroon', self.indicators['AROON'].current.value)\n self.plot('AROON', 'AroonUp', self.indicators['AROON'].aroon_up.current.value)\n self.plot('AROON', 'AroonDown', self.indicators['AROON'].aroon_down.current.value)\n\n # The following Plot method calls are commented out because of the 10 series limit for backtests\n #self.plot('ATR', 'ATR', self.indicators['ATR'].current.value)\n #self.plot('ATR', 'ATRDoubleBar', self.selector_indicators['ATR'].current.value)\n #self.plot('Averages', 'SMA', self.indicators['SMA'].current.value)\n #self.plot('Averages', 'EMA', self.indicators['EMA'].current.value)\n #self.plot('MOM', self.indicators['MOM'].current.value)\n #self.plot('MOMP', self.indicators['MOMP'].current.value)\n #self.plot('MACD', 'MACD', self.indicators['MACD'].current.value)\n #self.plot('MACD', 'MACDSignal', self.indicators['MACD'].signal.current.value)\n\n def selector_double__trade_bar(self, bar):\n trade_bar = TradeBar()\n trade_bar.close = 2 * bar.close\n trade_bar.data_type = bar.data_type\n trade_bar.high = 2 * bar.high\n trade_bar.low = 2 * bar.low\n trade_bar.open = 2 * bar.open\n trade_bar.symbol = bar.symbol\n trade_bar.time = bar.time\n trade_bar.value = 2 * bar.value\n trade_bar.period = bar.period\n return trade_bar\n\n\nclass CustomData(PythonData):\n def get_source(self, config, date, is_live):\n zip_file_name = LeanData.generate_zip_file_name(config.Symbol, date, config.Resolution, config.TickType)\n source = Globals.data_folder + \"/equity/usa/daily/\" + zip_file_name\n return SubscriptionDataSource(source)\n\n def reader(self, config, line, date, is_live):\n if line == None:\n return None\n\n custom_data = CustomData()\n custom_data.symbol = config.symbol\n\n csv = line.split(\",\")\n custom_data.time = datetime.strptime(csv[0], '%Y%m%d %H:%M')\n custom_data.end_time = custom_data.time + timedelta(days=1)\n custom_data.value = float(csv[1]) / 10000.0\n return custom_data\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm demonstrates the various ways to handle History pandas DataFrame", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass PandasDataFrameHistoryAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2014, 6, 9) # Set Start Date\n self.set_end_date(2014, 6, 9) # Set End Date\n\n self.spy = self.add_equity(\"SPY\", Resolution.DAILY).symbol\n self.eur = self.add_forex(\"EURUSD\", Resolution.DAILY).symbol\n\n aapl = self.add_equity(\"AAPL\", Resolution.MINUTE).symbol\n self.option = Symbol.create_option(aapl, Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 750, datetime(2014, 10, 18))\n self.add_option_contract(self.option)\n\n sp1 = self.add_data(QuandlFuture,\"CHRIS/CME_SP1\", Resolution.DAILY)\n sp1.exchange = EquityExchange()\n self.sp1 = sp1.symbol\n\n self.add_universe(self.coarse_selection)\n\n def coarse_selection(self, coarse):\n if self.portfolio.invested:\n return Universe.UNCHANGED\n\n selected = [x.symbol for x in coarse if x.symbol.value in [\"AAA\", \"AIG\", \"BAC\"]]\n if len(selected) == 0:\n return Universe.UNCHANGED\n\n universe_history = self.history(selected, 10, Resolution.DAILY)\n for symbol in selected:\n self.assert_history_index(universe_history, \"close\", 10, \"\", symbol)\n\n return selected\n\n\n def on_data(self, data):\n if self.portfolio.invested:\n return\n\n # we can get history in initialize to set up indicators and such\n self.spy_daily_sma = SimpleMovingAverage(14)\n\n # get the last calendar year's worth of SPY data at the configured resolution (daily)\n trade_bar_history = self.history([\"SPY\"], timedelta(365))\n self.assert_history_index(trade_bar_history, \"close\", 251, \"SPY\", self.spy)\n\n # get the last calendar year's worth of EURUSD data at the configured resolution (daily)\n quote_bar_history = self.history([\"EURUSD\"], timedelta(298))\n self.assert_history_index(quote_bar_history, \"bidclose\", 251, \"EURUSD\", self.eur)\n\n option_history = self.history([self.option], timedelta(3))\n option_history.index = option_history.index.droplevel(level=[0,1,2])\n self.assert_history_index(option_history, \"bidclose\", 390, \"\", self.option)\n\n # get the last calendar year's worth of quandl data at the configured resolution (daily)\n quandl_history = self.history(QuandlFuture, \"CHRIS/CME_SP1\", timedelta(365))\n self.assert_history_index(quandl_history, \"settle\", 251, \"CHRIS/CME_SP1\", self.sp1)\n\n # we can loop over the return value from these functions and we get TradeBars\n # we can use these TradeBars to initialize indicators or perform other math\n self.spy_daily_sma.reset()\n for index, trade_bar in trade_bar_history.loc[\"SPY\"].iterrows():\n self.spy_daily_sma.update(index, trade_bar[\"close\"])\n\n # we can loop over the return values from these functions and we'll get Quandl data\n # this can be used in much the same way as the trade_bar_history above\n self.spy_daily_sma.reset()\n for index, quandl in quandl_history.loc[\"CHRIS/CME_SP1\"].iterrows():\n self.spy_daily_sma.update(index, quandl[\"settle\"])\n\n self.set_holdings(self.eur, 1)\n\n def assert_history_index(self, df, column, expected, ticker, symbol):\n\n if df.empty:\n raise AssertionError(f\"Empty history data frame for {symbol}\")\n if column not in df:\n raise AssertionError(f\"Could not unstack df. Columns: {', '.join(df.columns)} | {column}\")\n\n value = df.iat[0,0]\n df2 = df.xs(df.index.get_level_values('time')[0], level='time')\n df3 = df[column].unstack(level=0)\n\n try:\n\n # str(Symbol.ID)\n self.assert_history_count(f\"df.iloc[0]\", df.iloc[0], len(df.columns))\n self.assert_history_count(f\"df.loc[str({symbol.id})]\", df.loc[str(symbol.id)], expected)\n self.assert_history_count(f\"df.xs(str({symbol.id}))\", df.xs(str(symbol.id)), expected)\n self.assert_history_count(f\"df.at[(str({symbol.id}),), '{column}']\", list(df.at[(str(symbol.id),), column]), expected)\n self.assert_history_count(f\"df2.loc[str({symbol.id})]\", df2.loc[str(symbol.id)], len(df2.columns))\n self.assert_history_count(f\"df3[str({symbol.id})]\", df3[str(symbol.id)], expected)\n self.assert_history_count(f\"df3.get(str({symbol.id}))\", df3.get(str(symbol.id)), expected)\n\n # str(Symbol)\n self.assert_history_count(f\"df.loc[str({symbol})]\", df.loc[str(symbol)], expected)\n self.assert_history_count(f\"df.xs(str({symbol}))\", df.xs(str(symbol)), expected)\n self.assert_history_count(f\"df.at[(str({symbol}),), '{column}']\", list(df.at[(str(symbol),), column]), expected)\n self.assert_history_count(f\"df2.loc[str({symbol})]\", df2.loc[str(symbol)], len(df2.columns))\n self.assert_history_count(f\"df3[str({symbol})]\", df3[str(symbol)], expected)\n self.assert_history_count(f\"df3.get(str({symbol}))\", df3.get(str(symbol)), expected)\n\n # str : Symbol.VALUE\n if len(ticker) == 0:\n return\n self.assert_history_count(f\"df.loc[{ticker}]\", df.loc[ticker], expected)\n self.assert_history_count(f\"df.xs({ticker})\", df.xs(ticker), expected)\n self.assert_history_count(f\"df.at[(ticker,), '{column}']\", list(df.at[(ticker,), column]), expected)\n self.assert_history_count(f\"df2.loc[{ticker}]\", df2.loc[ticker], len(df2.columns))\n self.assert_history_count(f\"df3[{ticker}]\", df3[ticker], expected)\n self.assert_history_count(f\"df3.get({ticker})\", df3.get(ticker), expected)\n\n except Exception as e:\n symbols = set(df.index.get_level_values(level='symbol'))\n raise AssertionError(f\"{symbols}, {symbol.id}, {symbol}, {ticker}. {e}\")\n\n\n def assert_history_count(self, method_call, trade_bar_history, expected):\n if isinstance(trade_bar_history, list):\n count = len(trade_bar_history)\n else:\n count = len(trade_bar_history.index)\n if count != expected:\n raise AssertionError(f\"{method_call} expected {expected}, but received {count}\")\n\n\nclass QuandlFuture(PythonQuandl):\n '''Custom quandl data type for setting customized value column name. Value column is used for the primary trading calculations and charting.'''\n def __init__(self):\n self.value_column_name = \"Settle\"\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Related to GH issue 4275, reproduces a failed string to symbol implicit conversion asserting the exception\nthrown contains the used ticker", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass StringToSymbolImplicitConversionRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10, 8)\n\n self.add_equity(\"SPY\", Resolution.MINUTE)\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n try:\n self.market_order(\"PEPE\", 1)\n except Exception as exception:\n if \"PEPE was not found\" in str(exception) and not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm for testing submit/update/cancel for combo orders", "output": "```python\n\n\nimport itertools\nfrom AlgorithmImports import *\n\nclass ComboOrderTicketDemoAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n self.set_cash(100000)\n\n equity = self.add_equity(\"GOOG\", leverage=4, fill_forward=True)\n option = self.add_option(equity.symbol, fill_forward=True)\n self._option_symbol = option.symbol\n\n option.set_filter(lambda u: u.strikes(-2, +2).expiration(0, 180))\n\n self._open_market_orders = []\n self._open_leg_limit_orders = []\n self._open_limit_orders = []\n\n self._order_legs = None\n\n def on_data(self, data: Slice) -> None:\n if self._order_legs is None:\n if self.is_market_open(self._option_symbol):\n chain = data.option_chains.get(self._option_symbol)\n if chain:\n call_contracts = [contract for contract in chain if contract.right == OptionRight.CALL]\n call_contracts_by_expiry = [(key, list(group)) for key, group in itertools.groupby(call_contracts, key=lambda x: x.expiry)]\n call_contracts_by_expiry.sort(key=lambda x: x[0])\n call_contracts = call_contracts_by_expiry[0][1]\n call_contracts.sort(key=lambda x: x.strike)\n\n if len(call_contracts) < 3:\n return\n\n quantities = [1, -2, 1]\n self._order_legs = []\n for i, contract in enumerate(call_contracts[:3]):\n leg = Leg.create(contract.symbol, quantities[i])\n self._order_legs.append(leg)\n else:\n # COMBO MARKET ORDERS\n self.combo_market_orders()\n # COMBO LIMIT ORDERS\n self.combo_limit_orders()\n # COMBO LEG LIMIT ORDERS\n self.combo_leg_limit_orders()\n\n def combo_market_orders(self) -> None:\n if len(self._open_market_orders) != 0 or self._order_legs is None:\n return\n\n self.log(\"Submitting combo market orders\")\n\n tickets = self.combo_market_order(self._order_legs, 2, asynchronous=False)\n self._open_market_orders.extend(tickets)\n\n tickets = self.combo_market_order(self._order_legs, 2, asynchronous=True)\n self._open_market_orders.extend(tickets)\n\n for ticket in tickets:\n response = ticket.cancel(\"Attempt to cancel combo market order\")\n if response.is_success:\n raise AssertionError(\"Combo market orders should fill instantly, they should not be cancelable in backtest mode: \" + response.order_id)\n\n def combo_limit_orders(self) -> None:\n if len(self._open_limit_orders) == 0:\n self.log(\"Submitting ComboLimitOrder\")\n\n current_price = sum([leg.quantity * self.securities[leg.symbol].close for leg in self._order_legs])\n\n tickets = self.combo_limit_order(self._order_legs, 2, current_price + 1.5)\n self._open_limit_orders.extend(tickets)\n\n # These won't fill, we will test cancel with this\n tickets = self.combo_limit_order(self._order_legs, -2, current_price + 3)\n self._open_limit_orders.extend(tickets)\n else:\n combo1 = self._open_limit_orders[:len(self._order_legs)]\n combo2 = self._open_limit_orders[-len(self._order_legs):]\n\n # check if either is filled and cancel the other\n if self.check_group_orders_for_fills(combo1, combo2):\n return\n\n # if neither order has filled, bring in the limits by a penny\n\n ticket = combo1[0]\n new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + 0.01, 2)\n self.debug(f\"Updating limits - Combo 1 {ticket.order_id}: {new_limit:.2f}\")\n fields = UpdateOrderFields()\n fields.limit_price = new_limit\n fields.tag = f\"Update #{len(ticket.update_requests) + 1}\"\n ticket.update(fields)\n\n ticket = combo2[0]\n new_limit = round(ticket.get(OrderField.LIMIT_PRICE) - 0.01, 2)\n self.debug(f\"Updating limits - Combo 2 {ticket.order_id}: {new_limit:.2f}\")\n fields.limit_price = new_limit\n fields.tag = f\"Update #{len(ticket.update_requests) + 1}\"\n ticket.update(fields)\n\n def combo_leg_limit_orders(self) -> None:\n if len(self._open_leg_limit_orders) == 0:\n self.log(\"Submitting ComboLegLimitOrder\")\n\n # submit a limit order to buy 2 shares at .1% below the bar's close\n for leg in self._order_legs:\n close = self.securities[leg.symbol].close\n leg.order_price = close * .999\n\n tickets = self.combo_leg_limit_order(self._order_legs, quantity=2)\n self._open_leg_limit_orders.extend(tickets)\n\n # submit another limit order to sell 2 shares at .1% above the bar's close\n for leg in self._order_legs:\n close = self.securities[leg.symbol].close\n leg.order_price = close * 1.001\n\n tickets = self.combo_leg_limit_order(self._order_legs, -2)\n self._open_leg_limit_orders.extend(tickets)\n else:\n combo1 = self._open_leg_limit_orders[:len(self._order_legs)]\n combo2 = self._open_leg_limit_orders[-len(self._order_legs):]\n\n # check if either is filled and cancel the other\n if self.check_group_orders_for_fills(combo1, combo2):\n return\n\n # if neither order has filled, bring in the limits by a penny\n\n for ticket in combo1:\n new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + (1 if ticket.quantity > 0 else -1) * 0.01, 2)\n self.debug(f\"Updating limits - Combo #1: {new_limit:.2f}\")\n fields = UpdateOrderFields()\n fields.limit_price = new_limit\n fields.tag = f\"Update #{len(ticket.update_requests) + 1}\"\n ticket.update(fields)\n\n for ticket in combo2:\n new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + (1 if ticket.quantity > 0 else -1) * 0.01, 2)\n self.debug(f\"Updating limits - Combo #2: {new_limit:.2f}\")\n fields.limit_price = new_limit\n fields.tag = f\"Update #{len(ticket.update_requests) + 1}\"\n ticket.update(fields)\n\n def on_order_event(self, order_event: OrderEvent) -> None:\n order = self.transactions.get_order_by_id(order_event.order_id)\n\n if order_event.quantity == 0:\n raise AssertionError(\"OrderEvent quantity is Not expected to be 0, it should hold the current order Quantity\")\n\n if order_event.quantity != order.quantity:\n raise AssertionError(\"OrderEvent quantity should hold the current order Quantity. \"\n f\"Got {order_event.quantity}, expected {order.quantity}\")\n\n if order.type == OrderType.COMBO_LEG_LIMIT and order_event.limit_price == 0:\n raise AssertionError(\"OrderEvent.LIMIT_PRICE is not expected to be 0 for ComboLegLimitOrder\")\n\n def check_group_orders_for_fills(self, combo1: list[OrderTicket], combo2: list[OrderTicket]) -> bool:\n if all(x.status == OrderStatus.FILLED for x in combo1):\n self.log(f\"{combo1[0].order_type}: Canceling combo #2, combo #1 is filled.\")\n if any(OrderExtensions.is_open(x.status) for x in combo2):\n for ticket in combo2:\n ticket.cancel(\"Combo #1 filled.\")\n return True\n\n if all(x.status == OrderStatus.FILLED for x in combo2):\n self.log(f\"{combo2[0].order_type}: Canceling combo #1, combo #2 is filled.\")\n if any(OrderExtensions.is_open(x.status) for x in combo1):\n for ticket in combo1:\n ticket.cancel(\"Combo #2 filled.\")\n return True\n\n return False\n\n def on_end_of_algorithm(self) -> None:\n filled_orders = list(self.transactions.get_orders(lambda x: x.status == OrderStatus.FILLED))\n order_tickets = list(self.transactions.get_order_tickets())\n open_orders = self.transactions.get_open_orders()\n open_order_tickets = list(self.transactions.get_open_order_tickets())\n remaining_open_orders = self.transactions.get_open_orders_remaining_quantity()\n\n # 6 market, 6 limit, 6 leg limit.\n # Out of the 6 limit orders, 3 are expected to be canceled.\n expected_orders_count = 18\n expected_fills_count = 15\n if len(filled_orders) != expected_fills_count or len(order_tickets) != expected_orders_count:\n raise AssertionError(f\"There were expected {expected_fills_count} filled orders and {expected_orders_count} order tickets, but there were {len(filled_orders)} filled orders and {len(order_tickets)} order tickets\")\n\n filled_combo_market_orders = [x for x in filled_orders if x.type == OrderType.COMBO_MARKET]\n filled_combo_limit_orders = [x for x in filled_orders if x.type == OrderType.COMBO_LIMIT]\n filled_combo_leg_limit_orders = [x for x in filled_orders if x.type == OrderType.COMBO_LEG_LIMIT]\n if len(filled_combo_market_orders) != 6 or len(filled_combo_limit_orders) != 3 or len(filled_combo_leg_limit_orders) != 6:\n raise AssertionError(\"There were expected 6 filled market orders, 3 filled combo limit orders and 6 filled combo leg limit orders, \"\n f\"but there were {len(filled_combo_market_orders)} filled market orders, {len(filled_combo_limit_orders)} filled \"\n f\"combo limit orders and {len(filled_combo_leg_limit_orders)} filled combo leg limit orders\")\n\n if len(open_orders) != 0 or len(open_order_tickets) != 0:\n raise AssertionError(\"No open orders or tickets were expected\")\n\n if remaining_open_orders != 0:\n raise AssertionError(\"No remaining quantity to be filled from open orders was expected\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to test the OptionChainedUniverseSelectionModel class", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionChainedUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.universe_settings.resolution = Resolution.MINUTE\n self.set_start_date(2014, 6, 6)\n self.set_end_date(2014, 6, 6)\n self.set_cash(100000)\n\n universe = self.add_universe(\"my-minute-universe-name\", lambda time: [ \"AAPL\", \"TWX\" ])\n self.add_universe_selection(\n OptionChainedUniverseSelectionModel(\n universe,\n lambda u: (u.strikes(-2, +2)\n # Expiration method accepts TimeSpan objects or integer for days.\n # The following statements yield the same filtering criteria\n .expiration(0, 180))\n )\n )\n\n def on_data(self, slice):\n if self.portfolio.invested or not (self.is_market_open(\"AAPL\") and self.is_market_open(\"TWX\")): return\n values = list(map(lambda x: x.value, filter(lambda x: x.key == \"?AAPL\" or x.key == \"?TWX\", slice.option_chains)))\n for chain in values:\n # we sort the contracts to find at the money (ATM) contract with farthest expiration\n contracts = sorted(sorted(sorted(chain, \\\n key = lambda x: abs(chain.underlying.price - x.strike)), \\\n key = lambda x: x.expiry, reverse=True), \\\n key = lambda x: x.right, reverse=True)\n\n # if found, trade it\n if len(contracts) == 0: return\n symbol = contracts[0].symbol\n self.market_order(symbol, 1)\n self.market_on_close_order(symbol, -1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Uses daily data and a simple moving average cross to place trades and an ema for stop placement", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass DailyAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,1,1) #Set Start Date\n self.set_end_date(2014,1,1) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\", Resolution.DAILY)\n self.add_equity(\"IBM\", Resolution.HOUR, leverage=1)\n self._macd = self.macd(\"SPY\", 12, 26, 9, MovingAverageType.WILDERS, Resolution.DAILY, Field.CLOSE)\n self._ema = self.ema(\"IBM\", 15 * 6, Resolution.HOUR, Field.SEVEN_BAR)\n self._last_action = self.start_date\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self._macd.is_ready: return\n bar = data.bars.get(\"IBM\")\n if not bar: return\n if self._last_action.date() == self.time.date(): return\n\n self._last_action = self.time\n quantity = self.portfolio[\"SPY\"].quantity\n\n if quantity <= 0 and self._macd.current.value > self._macd.signal.current.value and bar.price > self._ema.current.value:\n self.set_holdings(\"IBM\", 0.25)\n if quantity >= 0 and self._macd.current.value < self._macd.signal.current.value and bar.price < self._ema.current.value:\n self.set_holdings(\"IBM\", -0.25)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to add options for a given underlying equity security.\nIt also shows how you can prefilter contracts easily based on strikes and expirations, and how you\ncan inspect the option chain to pick a specific option contract to trade.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateOptionsHourlyAlgorithm(QCAlgorithm):\n underlying_ticker = \"AAPL\"\n\n def initialize(self):\n self.set_start_date(2014, 6, 6)\n self.set_end_date(2014, 6, 9)\n self.set_cash(100000)\n\n equity = self.add_equity(self.underlying_ticker, Resolution.HOUR)\n option = self.add_option(self.underlying_ticker, Resolution.HOUR)\n self.option_symbol = option.symbol\n\n # set our strike/expiry filter for this option chain\n option.set_filter(lambda u: (u.strikes(-2, +2)\n # Expiration method accepts TimeSpan objects or integer for days.\n # The following statements yield the same filtering criteria\n .expiration(0, 180)))\n #.expiration(TimeSpan.zero, TimeSpan.from_days(180))))\n\n # use the underlying equity as the benchmark\n self.set_benchmark(equity.symbol)\n\n def on_data(self,slice):\n if self.portfolio.invested or not self.is_market_open(self.option_symbol): return\n\n chain = slice.option_chains.get(self.option_symbol)\n if not chain:\n return\n\n # we sort the contracts to find at the money (ATM) contract with farthest expiration\n contracts = sorted(sorted(sorted(chain, \\\n key = lambda x: abs(chain.underlying.price - x.strike)), \\\n key = lambda x: x.expiry, reverse=True), \\\n key = lambda x: x.right, reverse=True)\n\n # if found, trade it\n if len(contracts) == 0 or not self.is_market_open(contracts[0].symbol): return\n symbol = contracts[0].symbol\n self.market_order(symbol, 1)\n self.market_on_close_order(symbol, -1)\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Provides an example algorithm showcasing the Security.data features", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom QuantConnect.Data.Custom.IconicTypes import *\n\nclass DynamicSecurityDataRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2015, 10, 22)\n self.set_end_date(2015, 10, 30)\n\n ticker = \"GOOGL\"\n self._equity = self.add_equity(ticker, Resolution.DAILY)\n\n custom_linked_equity = self.add_data(LinkedData, ticker, Resolution.DAILY)\n\n first_linked_data = LinkedData()\n first_linked_data.count = 100\n first_linked_data.symbol = custom_linked_equity.symbol\n first_linked_data.end_time = self.start_date\n\n second_linked_data = LinkedData()\n second_linked_data.count = 100\n second_linked_data.symbol = custom_linked_equity.symbol\n second_linked_data.end_time = self.start_date\n\n # Adding linked data manually to cache for example purposes, since\n # LinkedData is a type used for testing and doesn't point to any real data.\n custom_linked_equity_type = list(custom_linked_equity.subscriptions)[0].type\n custom_linked_data = list[LinkedData]()\n custom_linked_data.append(first_linked_data)\n custom_linked_data.append(second_linked_data)\n self._equity.cache.add_data_list(custom_linked_data, custom_linked_equity_type, False)\n\n def on_data(self, data):\n # The Security object's Data property provides convenient access\n # to the various types of data related to that security. You can\n # access not only the security's price data, but also any custom\n # data that is mapped to the security, such as our SEC reports.\n\n # 1. Get the most recent data point of a particular type:\n # 1.a Using the generic method, Get(T): => T\n custom_linked_data = self._equity.data.get(LinkedData)\n self.log(f\"{self.time}: LinkedData: {custom_linked_data}\")\n\n # 2. Get the list of data points of a particular type for the most recent time step:\n # 2.a Using the generic method, GetAll(T): => IReadOnlyList\n custom_linked_data_list = self._equity.data.get_all(LinkedData)\n self.log(f\"{self.time}: LinkedData: {len(custom_linked_data_list)}\")\n\n if not self.portfolio.invested:\n self.buy(self._equity.symbol, 10)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm asserts that futures have data at extended market hours when this is enabled.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FuturesExtendedMarketHoursRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 6)\n self.set_end_date(2013, 10, 11)\n\n self._es = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.HOUR, fill_forward=True, extended_market_hours=True)\n self._es.set_filter(0, 180)\n\n self._gc = self.add_future(Futures.Metals.GOLD, Resolution.HOUR, fill_forward=True, extended_market_hours=False)\n self._gc.set_filter(0, 180)\n\n self._es_ran_on_regular_hours = False\n self._es_ran_on_extended_hours = False\n self._gc_ran_on_regular_hours = False\n self._gc_ran_on_extended_hours = False\n\n def on_data(self, slice):\n slice_symbols = set(slice.keys())\n slice_symbols.update(slice.bars.keys())\n slice_symbols.update(slice.ticks.keys())\n slice_symbols.update(slice.quote_bars.keys())\n slice_symbols.update([x.canonical for x in slice_symbols])\n\n es_is_in_regular_hours = self._es.exchange.hours.is_open(self.time, False)\n es_is_in_extended_hours = not es_is_in_regular_hours and self._es.exchange.hours.is_open(self.time, True)\n slice_has_e_s_data = self._es.symbol in slice_symbols\n self._es_ran_on_regular_hours |= es_is_in_regular_hours and slice_has_e_s_data\n self._es_ran_on_extended_hours |= es_is_in_extended_hours and slice_has_e_s_data\n\n gc_is_in_regular_hours = self._gc.exchange.hours.is_open(self.time, False)\n gc_is_in_extended_hours = not gc_is_in_regular_hours and self._gc.exchange.hours.is_open(self.time, True)\n slice_has_g_c_data = self._gc.symbol in slice_symbols\n self._gc_ran_on_regular_hours |= gc_is_in_regular_hours and slice_has_g_c_data\n self._gc_ran_on_extended_hours |= gc_is_in_extended_hours and slice_has_g_c_data\n\n time_of_day = self.time.time()\n current_time_is_regular_hours = (time_of_day >= time(9, 30, 0) and time_of_day < time(16, 15, 0)) or (time_of_day >= time(16, 30, 0) and time_of_day < time(17, 0, 0))\n current_time_is_extended_hours = not current_time_is_regular_hours and (time_of_day < time(9, 30, 0) or time_of_day >= time(18, 0, 0))\n if es_is_in_regular_hours != current_time_is_regular_hours or es_is_in_extended_hours != current_time_is_extended_hours:\n raise AssertionError(\"At {Time}, {_es.symbol} is either in regular hours but current time is in extended hours, or viceversa\")\n\n def on_end_of_algorithm(self):\n if not self._es_ran_on_regular_hours:\n raise AssertionError(f\"Algorithm should have run on regular hours for {self._es.symbol} future, which enabled extended market hours\")\n\n if not self._es_ran_on_extended_hours:\n raise AssertionError(f\"Algorithm should have run on extended hours for {self._es.symbol} future, which enabled extended market hours\")\n\n if not self._gc_ran_on_regular_hours:\n raise AssertionError(f\"Algorithm should have run on regular hours for {self._gc.symbol} future, which did not enable extended market hours\")\n\n if self._gc_ran_on_extended_hours:\n raise AssertionError(f\"Algorithm should have not run on extended hours for {self._gc.symbol} future, which did not enable extended market hours\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests Out of The Money (OTM) future option expiry for puts.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, buy ES Put Option (expiring OTM)\n - contract expires worthless, not exercised, so never opened a position in the underlying\n\n * Liquidation of worthless ES Put OTM contract\n\nAdditionally, we test delistings for future options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionPutOTMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 6, 30)\n\n self.es19m20 = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 6, 19)),\n Resolution.MINUTE).symbol\n\n # Select a future option expiring ITM, and adds it to the algorithm.\n self.es_option = self.add_future_option_contract(\n list(\n sorted(\n [x for x in self.option_chain(self.es19m20) if x.id.strike_price <= 3150.0 and x.id.option_right == OptionRight.PUT],\n key=lambda x: x.id.strike_price,\n reverse=True\n )\n )[0], Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3150.0, datetime(2020, 6, 19))\n if self.es_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)\n\n def scheduled_market_order(self):\n self.market_order(self.es_option, 1)\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2020, 6, 19):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2020, 6, 20):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if not self.securities.contains_key(order_event.symbol):\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.es19m20:\n raise AssertionError(\"Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM\")\n\n # Expected contract is ES19M20 Put Option expiring OTM @ 3200\n if (security.symbol == self.expected_contract):\n self.assert_future_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n self.log(f\"{order_event}\")\n\n\n def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:\n raise AssertionError(\"Holdings were found after a filled option exercise\")\n\n if order_event.direction == OrderDirection.SELL and \"OTM\" not in order_event.message:\n raise AssertionError(\"Contract did not expire OTM\")\n\n if \"Exercise\" in order_event.message:\n raise AssertionError(\"Exercised option, even though it expires OTM\")\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template framework algorithm uses framework components to define the algorithm.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateIndiaAlgorithm(QCAlgorithm):\n '''Basic template framework algorithm uses framework components to define the algorithm.'''\n\n def initialize(self):\n '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_account_currency(\"INR\") #Set Account Currency \n self.set_start_date(2019, 1, 23) #Set Start Date\n self.set_end_date(2019, 10, 31) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"YESBANK\", Resolution.MINUTE, Market.INDIA)\n self.debug(\"numpy test >>> print numpy.pi: \" + str(np.pi))\n\n # Set Order Properties as per the requirements for order placement\n self.default_order_properties = IndiaOrderProperties(Exchange.NSE)\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.market_order(\"YESBANK\", 1)\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n self.debug(\"Purchased Stock: {0}\".format(order_event.symbol))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of using the ETFConstituentsUniverseSelectionModel", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Selection.ETFConstituentsUniverseSelectionModel import *\n\nclass ETFConstituentsFrameworkAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 12, 1)\n self.set_end_date(2020, 12, 7)\n self.set_cash(100000)\n\n self.universe_settings.resolution = Resolution.DAILY\n symbol = Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n self.add_universe_selection(ETFConstituentsUniverseSelectionModel(symbol, self.universe_settings, self.etf_constituents_filter))\n\n self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(days=1)))\n\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n\n\n def etf_constituents_filter(self, constituents: List[ETFConstituentData]) -> List[Symbol]:\n # Get the 10 securities with the largest weight in the index\n selected = sorted([c for c in constituents if c.weight],\n key=lambda c: c.weight, reverse=True)[:8]\n return [c.symbol for c in selected]\n\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression test for consistency of hour data over a reverse split event in US equities.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass HourReverseSplitRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 11, 7)\n self.set_end_date(2013, 11, 8)\n self.set_cash(100000)\n self.set_benchmark(lambda x: 0)\n\n self._symbol = self.add_equity(\"VXX.1\", Resolution.HOUR).symbol\n \n def on_data(self, slice):\n if slice.bars.count == 0: return\n if (not self.portfolio.invested) and self.time.date() == self.end_date.date():\n self.buy(self._symbol, 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm shows some of the various helper methods available when defining universes", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass UniverseSelectionDefinitionsAlgorithm(QCAlgorithm):\n\n def initialize(self):\n # subscriptions added via universe selection will have this resolution\n self.universe_settings.resolution = Resolution.DAILY\n\n self.set_start_date(2014,3,24) # Set Start Date\n self.set_end_date(2014,3,28) # Set End Date\n self.set_cash(100000) # Set Strategy Cash\n\n # add universe for the top 3 stocks by dollar volume\n self.add_universe(self.universe.top(3))\n\n self.changes = None\n self.on_securities_changed_was_called = False\n\n def on_data(self, data):\n if self.changes is None: return\n\n # liquidate securities that fell out of our universe\n for security in self.changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n\n # invest in securities just added to our universe\n for security in self.changes.added_securities:\n if not security.invested:\n self.market_order(security.symbol, 10)\n\n self.changes = None\n\n # this event fires whenever we have changes to our universe\n def on_securities_changed(self, changes):\n self.changes = changes\n self.on_securities_changed_was_called = True\n\n def on_end_of_algorithm(self):\n if not self.on_securities_changed_was_called:\n raise AssertionError(\"OnSecuritiesChanged() method was never called!\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: In this algorithm, we fetch a list of tickers with corresponding dates from a file on Dropbox.\nWe then create a fine fundamental universe which contains those symbols on their respective dates.###", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass DropboxCoarseFineAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2019, 9, 23) # Set Start Date\n self.set_end_date(2019, 9, 30) # Set End Date\n self.set_cash(100000) # Set Strategy Cash\n self.add_universe(self.select_coarse, self.select_fine)\n\n self.universe_data = None\n self.next_update = datetime(1, 1, 1) # Minimum datetime\n self.url = \"https://www.dropbox.com/s/x2sb9gaiicc6hm3/tickers_with_dates.csv?dl=1\"\n\n def on_end_of_day(self, symbol: Symbol) -> None:\n self.debug(f\"{self.time.date()} {symbol.value} with Market Cap: ${self.securities[symbol].fundamentals.market_cap}\")\n\n def select_coarse(self, coarse):\n return self.get_symbols()\n\n def select_fine(self, fine):\n symbols = self.get_symbols()\n\n # Return symbols from our list which have a market capitalization of at least 10B\n return [f.symbol for f in fine if f.market_cap > 1e10 and f.symbol in symbols]\n\n def get_symbols(self):\n\n # In live trading update every 12 hours\n if self.live_mode:\n if self.time < self.next_update:\n # Return today's row\n return self.universe_data[self.time.date()]\n # When updating set the new reset time.\n self.next_update = self.time + timedelta(hours=12)\n self.universe_data = self.parse(self.url)\n\n # In backtest load once if not set, then just use the dates.\n if not self.universe_data:\n self.universe_data = self.parse(self.url)\n\n # Check if contains the row we need\n if self.time.date() not in self.universe_data:\n return Universe.UNCHANGED\n\n return self.universe_data[self.time.date()]\n\n\n def parse(self, url):\n # Download file from url as string\n file = self.download(url).split(\"\\n\")\n\n # # Remove formatting characters\n data = [x.replace(\"\\r\", \"\").replace(\" \", \"\") for x in file]\n\n # # Split data by date and symbol\n split_data = [x.split(\",\") for x in data]\n\n # Dictionary to hold list of active symbols for each date, keyed by date\n symbols_by_date = {}\n\n # Parse data into dictionary\n for arr in split_data:\n date = datetime.strptime(arr[0], \"%Y%m%d\").date()\n symbols = [Symbol.create(ticker, SecurityType.EQUITY, Market.USA) for ticker in arr[1:]]\n symbols_by_date[date] = symbols\n\n return symbols_by_date\n\n def on_securities_changed(self, changes):\n self.log(f\"Added Securities: {[security.symbol.value for security in changes.added_securities]}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm demonstrating and ensuring that Bybit crypto futures brokerage model works as expected", "output": "```python\n\n\nfrom cmath import isclose\nfrom AlgorithmImports import *\n\nclass BybitCryptoFuturesRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2022, 12, 13)\n self.set_end_date(2022, 12, 13)\n\n # Set strategy cash (USD)\n self.set_cash(100000)\n\n self.set_brokerage_model(BrokerageName.BYBIT, AccountType.MARGIN)\n\n # Translate lines 44-59 to Python:\n\n self.add_crypto(\"BTCUSDT\", Resolution.MINUTE)\n\n self.btc_usdt = self.add_crypto_future(\"BTCUSDT\", Resolution.MINUTE)\n self.btc_usd = self.add_crypto_future(\"BTCUSD\", Resolution.MINUTE)\n\n # create two moving averages\n self.fast = self.ema(self.btc_usdt.symbol, 30, Resolution.MINUTE)\n self.slow = self.ema(self.btc_usdt.symbol, 60, Resolution.MINUTE)\n\n self.interest_per_symbol = {}\n self.interest_per_symbol[self.btc_usd.symbol] = 0\n self.interest_per_symbol[self.btc_usdt.symbol] = 0\n\n # the amount of USDT we need to hold to trade 'BTCUSDT'\n self.btc_usdt.quote_currency.set_amount(200)\n # the amount of BTC we need to hold to trade 'BTCUSD'\n self.btc_usd.base_currency.set_amount(0.005)\n\n def on_data(self, data):\n interest_rates = data.get[MarginInterestRate]()\n for interest_rate in interest_rates:\n self.interest_per_symbol[interest_rate.key] += 1\n\n cached_interest_rate = self.securities[interest_rate.key].cache.get_data(MarginInterestRate)\n if cached_interest_rate != interest_rate.value:\n raise AssertionError(f\"Unexpected cached margin interest rate for {interest_rate.key}!\")\n\n if not self.slow.is_ready:\n return\n\n if self.fast > self.slow:\n if not self.portfolio.invested and self.transactions.orders_count == 0:\n ticket = self.buy(self.btc_usd.symbol, 1000)\n if ticket.status != OrderStatus.INVALID:\n raise AssertionError(f\"Unexpected valid order {ticket}, should fail due to margin not sufficient\")\n\n self.buy(self.btc_usd.symbol, 100)\n\n margin_used = self.portfolio.total_margin_used\n btc_usd_holdings = self.btc_usd.holdings\n\n # Coin futures value is 100 USD\n holdings_value_btc_usd = 100\n if abs(btc_usd_holdings.total_sale_volume - holdings_value_btc_usd) > 1:\n raise AssertionError(f\"Unexpected TotalSaleVolume {btc_usd_holdings.total_sale_volume}\")\n if abs(btc_usd_holdings.absolute_holdings_cost - holdings_value_btc_usd) > 1:\n raise AssertionError(f\"Unexpected holdings cost {btc_usd_holdings.holdings_cost}\")\n # margin used is based on the maintenance rate\n if (abs(btc_usd_holdings.absolute_holdings_cost * 0.05 - margin_used) > 1 or\n not isclose(self.btc_usd.buying_power_model.get_maintenance_margin(MaintenanceMarginParameters.for_current_holdings(self.btc_usd)).value, margin_used)):\n raise AssertionError(f\"Unexpected margin used {margin_used}\")\n\n self.buy(self.btc_usdt.symbol, 0.01)\n\n margin_used = self.portfolio.total_margin_used - margin_used\n btc_usdt_holdings = self.btc_usdt.holdings\n\n # USDT futures value is based on it's price\n holdings_value_usdt = self.btc_usdt.price * self.btc_usdt.symbol_properties.contract_multiplier * 0.01\n\n if abs(btc_usdt_holdings.total_sale_volume - holdings_value_usdt) > 1:\n raise AssertionError(f\"Unexpected TotalSaleVolume {btc_usdt_holdings.total_sale_volume}\")\n if abs(btc_usdt_holdings.absolute_holdings_cost - holdings_value_usdt) > 1:\n raise AssertionError(f\"Unexpected holdings cost {btc_usdt_holdings.holdings_cost}\")\n if (abs(btc_usdt_holdings.absolute_holdings_cost * 0.05 - margin_used) > 1 or\n not isclose(self.btc_usdt.buying_power_model.get_maintenance_margin(MaintenanceMarginParameters.for_current_holdings(self.btc_usdt)).value, margin_used)):\n raise AssertionError(f\"Unexpected margin used {margin_used}\")\n\n # position just opened should be just spread here\n unrealized_profit = self.portfolio.total_unrealized_profit\n if (5 - abs(unrealized_profit)) < 0:\n raise AssertionError(f\"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}\")\n\n if self.portfolio.total_profit != 0:\n raise AssertionError(f\"Unexpected TotalProfit {self.portfolio.total_profit}\")\n # let's revert our position\n elif self.transactions.orders_count == 3:\n self.sell(self.btc_usd.symbol, 300)\n\n btc_usd_holdings = self.btc_usd.holdings\n if abs(btc_usd_holdings.absolute_holdings_cost - 100 * 2) > 1:\n raise AssertionError(f\"Unexpected holdings cost {btc_usd_holdings.holdings_cost}\")\n\n self.sell(self.btc_usdt.symbol, 0.03)\n\n # USDT futures value is based on it's price\n holdings_value_usdt = self.btc_usdt.price * self.btc_usdt.symbol_properties.contract_multiplier * 0.02\n if abs(self.btc_usdt.holdings.absolute_holdings_cost - holdings_value_usdt) > 1:\n raise AssertionError(f\"Unexpected holdings cost {self.btc_usdt.holdings.holdings_cost}\")\n\n # position just opened should be just spread here\n profit = self.portfolio.total_unrealized_profit\n if (5 - abs(profit)) < 0:\n raise AssertionError(f\"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}\")\n # we barely did any difference on the previous trade\n if (5 - abs(self.portfolio.total_profit)) < 0:\n raise AssertionError(f\"Unexpected TotalProfit {self.portfolio.total_profit}\")\n\n def on_order_event(self, order_event):\n self.debug(\"{} {}\".format(self.time, order_event.to_string()))\n\n def on_end_of_algorithm(self):\n self.log(f\"{self.time} - TotalPortfolioValue: {self.portfolio.total_portfolio_value}\")\n self.log(f\"{self.time} - CashBook: {self.portfolio.cash_book}\")\n\n if any(x == 0 for x in self.interest_per_symbol.values()):\n raise AssertionError(\"Expected interest rate data for all symbols\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Test algorithm using a 'ConstituentsUniverse' with test data", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ConstituentsUniverseRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 7) #Set Start Date\n self.set_end_date(2013, 10, 11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self._appl = Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA)\n self._spy = Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n self._qqq = Symbol.create(\"QQQ\", SecurityType.EQUITY, Market.USA)\n self._fb = Symbol.create(\"FB\", SecurityType.EQUITY, Market.USA)\n self._step = 0\n\n self.universe_settings.resolution = Resolution.DAILY\n\n custom_universe_symbol = Symbol(SecurityIdentifier.generate_constituent_identifier(\n \"constituents-universe-qctest\",\n SecurityType.EQUITY,\n Market.USA),\n \"constituents-universe-qctest\")\n\n self.add_universe(ConstituentsUniverse(custom_universe_symbol, self.universe_settings))\n\n def on_data(self, data):\n self._step = self._step + 1\n if self._step == 1:\n if not data.contains_key(self._qqq) or not data.contains_key(self._appl):\n raise ValueError(\"Unexpected symbols found, step: \" + str(self._step))\n if data.count != 2:\n raise ValueError(\"Unexpected data count, step: \" + str(self._step))\n # AAPL will be deselected by the ConstituentsUniverse\n # but it shouldn't be removed since we hold it\n self.set_holdings(self._appl, 0.5)\n elif self._step == 2:\n if not data.contains_key(self._appl):\n raise ValueError(\"Unexpected symbols found, step: \" + str(self._step))\n if data.count != 1:\n raise ValueError(\"Unexpected data count, step: \" + str(self._step))\n # AAPL should now be released\n # note: takes one extra loop because the order is executed on market open\n self.liquidate()\n elif self._step == 3:\n if not data.contains_key(self._fb) or not data.contains_key(self._spy) or not data.contains_key(self._appl):\n raise ValueError(\"Unexpected symbols found, step: \" + str(self._step))\n if data.count != 3:\n raise ValueError(\"Unexpected data count, step: \" + str(self._step))\n elif self._step == 4:\n if not data.contains_key(self._fb) or not data.contains_key(self._spy):\n raise ValueError(\"Unexpected symbols found, step: \" + str(self._step))\n if data.count != 2:\n raise ValueError(\"Unexpected data count, step: \" + str(self._step))\n\n def on_end_of_algorithm(self):\n # First selection is on the midnight of the 8th, start getting data from the 8th to the 11th\n if self._step != 4:\n raise ValueError(\"Unexpected step count: \" + str(self._step))\n\n def OnSecuritiesChanged(self, changes):\n for added in changes.added_securities:\n self.log(f\"{self.time} AddedSecurities \" + str(added))\n\n for removed in changes.removed_securities:\n self.log(f\"{self.time} RemovedSecurities \" + str(removed) + str(self._step))\n # we are currently notifying the removal of AAPl twice,\n # when deselected and when finally removed (since it stayed pending)\n if removed.symbol == self._appl and self._step != 1 and self._step != 2 or removed.symbol == self._qqq and self._step != 1:\n raise ValueError(\"Unexpected removal step count: \" + str(self._step))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression test to demonstrate setting custom Symbol Properties and Market Hours for a custom data import", "output": "```python\n\n\nimport json\nfrom AlgorithmImports import *\n\nclass CustomDataPropertiesRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n self.set_start_date(2020, 1, 5) # Set Start Date\n self.set_end_date(2020, 1, 10) # Set End Date\n self.set_cash(100000) # Set Strategy Cash\n\n # Define our custom data properties and exchange hours\n ticker = 'BTC'\n properties = SymbolProperties(\"Bitcoin\", \"USD\", 1, 0.01, 0.01, ticker)\n exchange_hours = SecurityExchangeHours.always_open(TimeZones.NEW_YORK)\n\n # Add the custom data to our algorithm with our custom properties and exchange hours\n self._bitcoin = self.add_data(Bitcoin, ticker, properties, exchange_hours, leverage=1, fill_forward=False)\n\n # Verify our symbol properties were changed and loaded into this security\n if self._bitcoin.symbol_properties != properties :\n raise AssertionError(\"Failed to set and retrieve custom SymbolProperties for BTC\")\n\n # Verify our exchange hours were changed and loaded into this security\n if self._bitcoin.exchange.hours != exchange_hours :\n raise AssertionError(\"Failed to set and retrieve custom ExchangeHours for BTC\")\n\n # For regression purposes on AddData overloads, this call is simply to ensure Lean can accept this\n # with default params and is not routed to a breaking function.\n self.add_data(Bitcoin, \"BTCUSD\")\n\n def on_data(self, data: Slice) -> None:\n if not self.portfolio.invested:\n if data['BTC'].close != 0 :\n self.order('BTC', self.portfolio.margin_remaining/abs(data['BTC'].close + 1))\n\n def on_end_of_algorithm(self) -> None:\n #Reset our Symbol property value, for testing purposes.\n self.symbol_properties_database.set_entry(Market.USA, self.market_hours_database.get_database_symbol_key(self._bitcoin.symbol), SecurityType.BASE,\n SymbolProperties.get_default(\"USD\"))\n\n\nclass Bitcoin(PythonData):\n '''Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data'''\n\n def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:\n if is_live_mode:\n return SubscriptionDataSource(\"https://www.bitstamp.net/api/ticker/\", SubscriptionTransportMedium.REST)\n\n #return \"http://my-ftp-server.com/futures-data-\" + date.to_string(\"Ymd\") + \".zip\"\n # OR simply return a fixed small data file. Large files will slow down your backtest\n subscription = SubscriptionDataSource(\"https://www.quantconnect.com/api/v2/proxy/nasdaq/api/v3/datatables/QDL/BITFINEX.csv?code=BTCUSD&api_key=WyAazVXnq7ATy_fefTqm\")\n subscription.sort = True\n return subscription\n\n def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData:\n coin = Bitcoin()\n coin.symbol = config.symbol\n\n if is_live_mode:\n # Example Line Format:\n # {\"high\": \"441.00\", \"last\": \"421.86\", \"timestamp\": \"1411606877\", \"bid\": \"421.96\", \"vwap\": \"428.58\", \"volume\": \"14120.40683975\", \"low\": \"418.83\", \"ask\": \"421.99\"}\n try:\n live_btc = json.loads(line)\n\n # If value is zero, return None\n value = live_btc[\"last\"]\n if value == 0: return coin\n\n coin.time = datetime.now()\n coin.value = value\n coin[\"Open\"] = float(live_btc[\"open\"])\n coin[\"High\"] = float(live_btc[\"high\"])\n coin[\"Low\"] = float(live_btc[\"low\"])\n coin[\"Close\"] = float(live_btc[\"last\"])\n coin[\"Ask\"] = float(live_btc[\"ask\"])\n coin[\"Bid\"] = float(live_btc[\"bid\"])\n coin[\"VolumeBTC\"] = float(live_btc[\"volume\"])\n coin[\"WeightedPrice\"] = float(live_btc[\"vwap\"])\n return coin\n except ValueError:\n # Do nothing, possible error in json decoding\n return coin\n\n # Example Line Format:\n #code date high low mid last bid ask volume\n #BTCUSD 2024-10-08 63248.0 61940.0 62246.5 62245.0 62246.0 62247.0 5.929230648356\n if not (line.strip() and line[7].isdigit()): return coin\n\n try:\n data = line.split(',')\n coin.time = datetime.strptime(data[1], \"%Y-%m-%d\")\n coin.end_time = coin.time + timedelta(1)\n coin.value = float(data[5])\n coin[\"High\"] = float(data[2])\n coin[\"Low\"] = float(data[3])\n coin[\"Mid\"] = float(data[4])\n coin[\"Close\"] = float(data[5])\n coin[\"Bid\"] = float(data[6])\n coin[\"Ask\"] = float(data[7])\n coin[\"VolumeBTC\"] = float(data[8])\n return coin\n\n except ValueError:\n # Do nothing, possible error in json decoding\n return coin\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting that the option chain APIs return consistent values.\nSee QCAlgorithm.OptionChain(Symbol) and QCAlgorithm.OptionChainProvider", "output": "```python\n\n\nfrom datetime import datetime\nfrom AlgorithmImports import *\n\nclass OptionChainApisConsistencyRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n test_date = self.get_test_date()\n\n self.set_start_date(test_date)\n self.set_end_date(test_date)\n\n option = self.get_option()\n\n option_chain_from_algorithm_api = [x.symbol for x in self.option_chain(option.symbol).contracts.values()]\n\n exchange_time = Extensions.convert_from_utc(self.utc_time, option.exchange.time_zone)\n option_chain_from_provider_api = list(self.option_chain_provider.get_option_contract_list(option.symbol, exchange_time))\n\n if len(option_chain_from_algorithm_api) == 0:\n raise AssertionError(\"No options in chain from algorithm API\")\n\n if len(option_chain_from_provider_api) == 0:\n raise AssertionError(\"No options in chain from provider API\")\n\n if len(option_chain_from_algorithm_api) != len(option_chain_from_provider_api):\n raise AssertionError(f\"Expected {len(option_chain_from_provider_api)} options in chain from provider API, \"\n f\"but got {len(option_chain_from_algorithm_api)}\")\n\n for i in range(len(option_chain_from_algorithm_api)):\n symbol1 = option_chain_from_algorithm_api[i]\n symbol2 = option_chain_from_provider_api[i]\n\n if symbol1 != symbol2:\n raise AssertionError(f\"Expected {symbol2} in chain from provider API, but got {symbol1}\")\n\n def get_test_date(self) -> datetime:\n return datetime(2015, 12, 25)\n\n def get_option(self) -> Option:\n return self.add_option(\"GOOG\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Shows how setting to use the SecurityMarginModel.null (or BuyingPowerModel.NULL)\nto disable the sufficient margin call verification.\nSee also: ", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass NullBuyingPowerOptionBullCallSpreadAlgorithm(QCAlgorithm):\n def initialize(self):\n\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n self.set_cash(200000)\n\n self.set_security_initializer(lambda security: security.set_margin_model(SecurityMarginModel.NULL))\n self.portfolio.set_positions(SecurityPositionGroupModel.NULL)\n\n equity = self.add_equity(\"GOOG\")\n option = self.add_option(equity.symbol)\n self.option_symbol = option.symbol\n\n option.set_filter(-2, 2, 0, 180)\n \n def on_data(self, slice):\n if self.portfolio.invested or not self.is_market_open(self.option_symbol):\n return\n \n chain = slice.option_chains.get(self.option_symbol)\n if chain:\n call_contracts = [x for x in chain if x.right == OptionRight.CALL]\n\n expiry = min(x.expiry for x in call_contracts)\n\n call_contracts = sorted([x for x in call_contracts if x.expiry == expiry],\n key = lambda x: x.strike)\n\n long_call = call_contracts[0]\n short_call = [x for x in call_contracts if x.strike > long_call.strike][0]\n\n quantity = 1000\n\n tickets = [\n self.market_order(short_call.symbol, -quantity),\n self.market_order(long_call.symbol, quantity)\n ]\n \n for ticket in tickets:\n if ticket.status != OrderStatus.FILLED:\n raise AssertionError(f\"There should be no restriction on buying {ticket.quantity} of {ticket.symbol} with BuyingPowerModel.NULL\")\n\n\n def on_end_of_algorithm(self) -> None:\n if self.portfolio.total_margin_used != 0:\n raise AssertionError(\"The TotalMarginUsed should be zero to avoid margin calls.\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests In The Money (ITM) index option expiry for puts.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1)\n * Option exercise, receiving cash (sell, qty -1)\n\nAdditionally, we test delistings for index options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndexOptionPutITMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 1, 31)\n\n self.spx = self.add_index(\"SPX\", Resolution.MINUTE).symbol\n\n # Select a index option expiring ITM, and adds it to the algorithm.\n self.spx_options = list(self.option_chain(self.spx))\n self.spx_options = [i for i in self.spx_options if i.id.strike_price >= 4200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1]\n self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price))[0]\n self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.PUT, 4200, datetime(2021, 1, 15))\n if self.spx_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, 1))\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2021, 1, 15):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2021, 1, 16):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if order_event.symbol not in self.securities:\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.spx:\n self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_contract])\n elif security.symbol == self.expected_contract:\n self.assert_index_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security):\n expected_liquidation_time_utc = datetime(2021, 1, 15)\n\n if order_event.direction == OrderDirection.BUY and order_event.utc_time != expected_liquidation_time_utc:\n raise AssertionError(f\"Liquidated index option contract, but not at the expected time. Expected: {expected_liquidation_time_utc} - found {order_event.utc_time}\")\n\n # No way to detect option exercise orders or any other kind of special orders\n # other than matching strings, for now.\n if \"Option Exercise\" in order_event.message:\n if order_event.fill_price != 3300:\n raise AssertionError(\"Option did not exercise at expected strike price (3300)\")\n\n if option_contract.holdings.quantity != 0:\n raise AssertionError(f\"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}\")\n\n def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after a filled option exercise\")\n if \"Exercise\" in order_event.message and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after exercising option contract {option.symbol}\")\n\n ### \n ### Ran at the end of the algorithm to ensure the algorithm has no holdings\n ### \n ### The algorithm has holdings\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests In The Money (ITM) future option expiry for short puts.\nWe expect 3 orders from the algorithm, which are:\n\n * Initial entry, sell ES Put Option (expiring ITM)\n * Option assignment, buy 1 contract of the underlying (ES)\n * Future contract expiry, liquidation (sell 1 ES future)\n\nAdditionally, we test delistings for future options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionShortPutITMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 6, 30)\n\n self.es19m20 = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 6, 19)),\n Resolution.MINUTE).symbol\n\n # Select a future option expiring ITM, and adds it to the algorithm.\n self.es_option = self.add_future_option_contract(\n list(\n sorted(\n [x for x in self.option_chain(self.es19m20) if x.id.strike_price <= 3400.0 and x.id.option_right == OptionRight.PUT],\n key=lambda x: x.id.strike_price,\n reverse=True\n )\n )[0], Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3400.0, datetime(2020, 6, 19))\n if self.es_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)\n\n def scheduled_market_order(self):\n self.market_order(self.es_option, -1)\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2020, 6, 19):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2020, 6, 20):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if not self.securities.contains_key(order_event.symbol):\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.es19m20:\n self.assert_future_option_order_exercise(order_event, security, self.securities[self.expected_contract])\n\n elif security.symbol == self.expected_contract:\n self.assert_future_option_contract_order(order_event, security)\n\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n self.log(f\"{order_event}\")\n\n def assert_future_option_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security):\n if \"Assignment\" in order_event.message:\n if order_event.fill_price != 3400.0:\n raise AssertionError(\"Option was not assigned at expected strike price (3400)\")\n\n if order_event.direction != OrderDirection.BUY or future.holdings.quantity != 1:\n raise AssertionError(f\"Expected Qty: 1 futures holdings for assigned future {future.symbol}, found {future.holdings.quantity}\")\n\n return\n\n if order_event.direction == OrderDirection.SELL and future.holdings.quantity != 0:\n # We buy back the underlying at expiration, so we expect a neutral position then\n raise AssertionError(f\"Expected no holdings when liquidating future contract {future.symbol}\")\n\n def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != -1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n\n if order_event.is_assignment and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after option contract was assigned: {option.symbol}\")\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Options Open Interest data regression test.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionOpenInterestRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_cash(1000000)\n self.set_start_date(2014,6,5)\n self.set_end_date(2014,6,6)\n\n option = self.add_option(\"TWX\")\n\n # set our strike/expiry filter for this option chain\n option.set_filter(-10, 10, timedelta(0), timedelta(365*2))\n\n # use the underlying equity as the benchmark\n self.set_benchmark(\"TWX\")\n\n def on_data(self, slice):\n if not self.portfolio.invested:\n for chain in slice.option_chains:\n for contract in chain.value:\n if float(contract.symbol.id.strike_price) == 72.5 and \\\n contract.symbol.id.option_right == OptionRight.CALL and \\\n contract.symbol.id.date == datetime(2016, 1, 15):\n\n history = self.history(OpenInterest, contract.symbol, timedelta(1))[\"openinterest\"]\n if len(history.index) == 0 or 0 in history.values:\n raise ValueError(\"Regression test failed: open interest history request is empty\")\n\n security = self.securities[contract.symbol]\n open_interest_cache = security.cache.get_data(OpenInterest)\n if open_interest_cache == None:\n raise ValueError(\"Regression test failed: current open interest isn't in the security cache\")\n if slice.time.date() == datetime(2014, 6, 5).date() and (contract.open_interest != 50 or security.open_interest != 50):\n raise ValueError(\"Regression test failed: current open interest was not correctly loaded and is not equal to 50\")\n if slice.time.date() == datetime(2014, 6, 6).date() and (contract.open_interest != 70 or security.open_interest != 70):\n raise ValueError(\"Regression test failed: current open interest was not correctly loaded and is not equal to 70\")\n if slice.time.date() == datetime(2014, 6, 6).date():\n self.market_order(contract.symbol, 1)\n self.market_on_close_order(contract.symbol, -1)\n\n if all(contract.open_interest == 0 for contract in chain.value):\n raise ValueError(\"Regression test failed: open interest is zero for all contracts\")\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: We add an option contract using 'QCAlgorithm.add_option_contract' and place a trade, the underlying\ngets deselected from the universe selection but should still be present since we manually added the option contract.\nLater we call 'QCAlgorithm.remove_option_contract' and expect both option and underlying to be removed.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AddOptionContractExpiresRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2014, 6, 5)\n self.set_end_date(2014, 6, 30)\n\n self._expiration = datetime(2014, 6, 21)\n self._option = None\n self._traded = False\n\n self._twx = Symbol.create(\"TWX\", SecurityType.EQUITY, Market.USA)\n\n self.add_universe(\"my-daily-universe-name\", self.selector)\n\n def selector(self, time):\n return [ \"AAPL\" ]\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if self._option == None:\n chain = self.option_chain(self._twx)\n options = sorted(chain, key=lambda x: x.id.symbol)\n\n option = next((option\n for option in options\n if option.id.date == self._expiration and\n option.id.option_right == OptionRight.CALL and\n option.id.option_style == OptionStyle.AMERICAN), None)\n if option != None:\n self._option = self.add_option_contract(option).symbol\n\n if self._option != None and self.securities[self._option].price != 0 and not self._traded:\n self._traded = True\n self.buy(self._option, 1)\n\n if self.time > self._expiration and self.securities[self._twx].invested:\n # we liquidate the option exercised position\n self.liquidate(self._twx)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm demonstrating the use of custom data sourced from multiple \"files\" in the object store", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomDataMultiFileObjectStoreRegressionAlgorithm(QCAlgorithm):\n custom_data = \"2017-08-18 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\\n2017-08-18 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\\n2017-08-18 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\\n2017-08-18 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\\n2017-08-18 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\\n2017-08-18 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\\n2017-08-18 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\\n2017-08-18 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\\n2017-08-18 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\\n2017-08-18 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-18 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\\n2017-08-18 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\\n2017-08-18 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\\n2017-08-18 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\\n2017-08-18 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\\n2017-08-18 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-18 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\\n2017-08-18 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\\n2017-08-18 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-18 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\\n2017-08-18 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\\n2017-08-18 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\\n2017-08-18 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57\\n2017-08-19 01:00:00,5771.75,5792.9,5738.6,5760.2,140394424,5894.04\\n2017-08-19 02:00:00,5709.35,5729.85,5683.1,5699.1,142041404,5462.45\\n2017-08-19 03:00:00,5748.95,5819.4,5739.4,5808.4,124410018,5121.33\\n2017-08-19 04:00:00,5820.4,5854.9,5770.25,5850.05,107160887,4560.84\\n2017-08-19 05:00:00,5841.9,5863.4,5804.3,5813.6,117541145,4591.91\\n2017-08-19 06:00:00,5805.75,5828.4,5777.9,5822.25,115539008,4643.17\\n2017-08-19 07:00:00,5754.15,5755,5645.65,5655.9,198400131,7148\\n2017-08-19 08:00:00,5639.9,5686.15,5616.85,5667.65,182410583,6697.18\\n2017-08-19 09:00:00,5638.05,5640,5566.25,5590.25,193488581,6308.88\\n2017-08-19 10:00:00,5606.95,5666.25,5570.25,5609.1,196571543,6792.49\\n2017-08-19 11:00:00,5627.95,5635.25,5579.35,5588.7,160095940,5939.3\\n2017-08-19 12:00:00,5647.95,5699.35,5630.95,5682.35,239029425,9184.29\\n2017-08-19 13:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\\n2017-08-19 14:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\\n2017-08-19 15:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\\n2017-08-19 16:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\\n2017-08-19 17:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\\n2017-08-19 18:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\\n2017-08-19 19:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\\n2017-08-19 20:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\\n2017-08-19 21:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\\n2017-08-19 22:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-19 23:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\\n2017-08-21 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\\n2017-08-21 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\\n2017-08-21 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\\n2017-08-21 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\\n2017-08-21 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\\n2017-08-21 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\\n2017-08-21 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\\n2017-08-21 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\\n2017-08-21 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\\n2017-08-21 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-21 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\\n2017-08-21 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\\n2017-08-21 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\\n2017-08-21 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\\n2017-08-21 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\\n2017-08-21 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-21 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\\n2017-08-21 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\\n2017-08-21 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-21 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\\n2017-08-21 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\\n2017-08-21 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\\n2017-08-21 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57\"\n\n def initialize(self):\n self.set_start_date(2017, 8, 18)\n self.set_end_date(2017, 8, 21)\n self.set_cash(100000)\n\n self.set_benchmark(lambda x: 0)\n\n self.custom_symbol = self.add_data(ExampleCustomData, \"ExampleCustomData\", Resolution.HOUR).symbol\n\n # Saving data here for demonstration and regression testing purposes.\n # In real scenarios, data has to be saved to the object store before the algorithm starts.\n # Note: The data is stored in separate files for each date.\n data = {}\n for line in self.custom_data.split('\\n'):\n csv = line.split(',')\n time = datetime.strptime(csv[0], '%Y-%m-%d %H:%M:%S').date()\n if time not in data:\n data[time] = line\n else:\n data[time] += '\\n' + line\n\n for date, date_data in data.items():\n self.object_store.save(self.get_custom_data_key(date), date_data)\n\n self.received_data = []\n\n def on_data(self, slice: Slice):\n if slice.contains_key(self.custom_symbol):\n custom_data = slice.get(ExampleCustomData, self.custom_symbol)\n if custom_data.price == 0:\n raise AssertionError(\"Custom data price was not expected to be zero\")\n\n self.received_data.append(custom_data)\n\n def on_end_of_algorithm(self):\n if not self.received_data:\n raise AssertionError(\"Custom data was not fetched\")\n\n custom_security = self.securities[self.custom_symbol]\n if custom_security is None or custom_security.price == 0:\n raise AssertionError(\"Expected the custom security to be added to the algorithm securities and to have a price that is not zero\")\n\n # Make sure history requests work as expected\n history = self.history(ExampleCustomData, self.custom_symbol, self.start_date, self.end_date, Resolution.HOUR)\n\n if history.shape[0] != len(self.received_data):\n raise AssertionError(\"History request returned more or less data than expected\")\n\n for i in range(len(self.received_data)):\n received_data = self.received_data[i]\n if (history.index[i][0] != received_data.symbol or\n history.index[i][1] != received_data.time or\n history[[\"value\"]].values[i][0] != received_data.value or\n history[[\"open\"]].values[i][0] != received_data.open or\n history[[\"high\"]].values[i][0] != received_data.high or\n history[[\"low\"]].values[i][0] != received_data.low or\n history[[\"close\"]].values[i][0] != received_data.close):\n raise AssertionError(\"History request returned different data than expected\")\n\n @staticmethod\n def get_custom_data_key(date: date) -> str:\n return f\"CustomData/ExampleCustomData{date.strftime('%Y%m%d')}\"\n\nclass ExampleCustomData(PythonData):\n CustomDataKey = \"\"\n\n def get_source(self, config, date, is_live):\n return SubscriptionDataSource(CustomDataMultiFileObjectStoreRegressionAlgorithm.get_custom_data_key(date.date()),\n SubscriptionTransportMedium.OBJECT_STORE,\n FileFormat.CSV)\n\n def reader(self, config, line, date, is_live):\n data = line.split(',')\n obj_data = ExampleCustomData()\n obj_data.symbol = config.symbol\n obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S')\n obj_data.value = float(data[4])\n obj_data[\"Open\"] = float(data[1])\n obj_data[\"High\"] = float(data[2])\n obj_data[\"Low\"] = float(data[3])\n obj_data[\"Close\"] = float(data[4])\n return obj_data\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm sends a list of current portfolio targets to Numerai API before each trading day\nSee (https://docs.numer.ai/numerai-signals/signals-overview) for more information\nabout accepted symbols, signals, etc.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass NumeraiSignalExportDemonstrationAlgorithm(QCAlgorithm):\n\n _securities = []\n\n def initialize(self) -> None:\n ''' Initialize the date and add all equity symbols present in list _symbols '''\n\n self.set_start_date(2020, 10, 7) #Set Start Date\n self.set_end_date(2020, 10, 12) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))\n\n # Add the CRSP US Total Market Index constituents, which represents approximately 100% of the investable US Equity market\n self.etf_symbol = self.add_equity(\"VTI\").symbol\n self.add_universe(self.universe.etf(self.etf_symbol))\n\n # Create a Scheduled Event to submit signals every trading day at 13:00 UTC\n self.schedule.on(self.date_rules.every_day(self.etf_symbol), self.time_rules.at(13, 0, TimeZones.UTC), self.submit_signals)\n\n # Set Numerai signal export provider\n # Numerai Public ID: This value is provided by Numerai Signals in their main webpage once you've logged in\n # and created a API key. See (https://signals.numer.ai/account)\n numerai_public_id = \"\"\n\n # Numerai Secret ID: This value is provided by Numerai Signals in their main webpage once you've logged in\n # and created a API key. See (https://signals.numer.ai/account)\n numerai_secret_id = \"\"\n\n # Numerai Model ID: This value is provided by Numerai Signals in their main webpage once you've logged in\n # and created a model. See (https://signals.numer.ai/models)\n numerai_model_id = \"\"\n\n numerai_filename = \"\" # (Optional) Replace this value with your submission filename \n\n # Disable automatic exports as we manually set them\n self.signal_export.automatic_export_time_span = None\n\n # Set Numerai signal export provider\n self.signal_export.add_signal_export_provider(NumeraiSignalExport(numerai_public_id, numerai_secret_id, numerai_model_id, numerai_filename))\n\n\n def submit_signals(self) -> None:\n # Select the subset of ETF constituents we can trade\n symbols = sorted([security.symbol for security in self._securities if security.has_data])\n if len(symbols) == 0:\n return\n\n # Get historical data\n # close_prices = self.history(symbols, 22, Resolution.DAILY).close.unstack(0)\n \n # Create portfolio targets\n # Numerai requires that at least one of the signals have a unique weight\n # To ensure they are all unique, this demo gives a linear allocation to each symbol (ie. 1/55, 2/55, ..., 10/55)\n denominator = len(symbols) * (len(symbols) + 1) / 2 # sum of 1, 2, ..., len(symbols)\n targets = [PortfolioTarget(symbol, (i+1) / denominator) for i, symbol in enumerate(symbols)]\n\n # (Optional) Place trades\n self.set_holdings(targets)\n\n # Send signals to Numerai\n success = self.signal_export.set_target_portfolio(targets)\n if not success:\n self.debug(f\"Couldn't send targets at {self.time}\")\n\n\n def on_securities_changed(self, changes: SecurityChanges) -> None:\n for security in changes.removed_securities:\n if security in self._securities:\n self._securities.remove(security)\n \n self._securities.extend([security for security in changes.added_securities if security.symbol != self.etf_symbol])\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to add options for a given underlying equity security.\nIt also shows how you can prefilter contracts easily based on strikes and expirations, and how you\ncan inspect the option chain to pick a specific option contract to trade.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateOptionsAlgorithm(QCAlgorithm):\n underlying_ticker = \"GOOG\"\n\n def initialize(self):\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n self.set_cash(100000)\n\n equity = self.add_equity(self.underlying_ticker)\n option = self.add_option(self.underlying_ticker)\n self.option_symbol = option.symbol\n\n # set our strike/expiry filter for this option chain\n option.set_filter(lambda u: (u.strikes(-2, +2)\n # Expiration method accepts TimeSpan objects or integer for days.\n # The following statements yield the same filtering criteria\n .expiration(0, 180)))\n #.expiration(TimeSpan.zero, TimeSpan.from_days(180))))\n\n # use the underlying equity as the benchmark\n self.set_benchmark(equity.symbol)\n\n def on_data(self, slice):\n if self.portfolio.invested or not self.is_market_open(self.option_symbol): return\n\n chain = slice.option_chains.get(self.option_symbol)\n if not chain:\n return\n\n # we sort the contracts to find at the money (ATM) contract with farthest expiration\n contracts = sorted(sorted(sorted(chain, \\\n key = lambda x: abs(chain.underlying.price - x.strike)), \\\n key = lambda x: x.expiry, reverse=True), \\\n key = lambda x: x.right, reverse=True)\n\n # if found, trade it\n if len(contracts) == 0: return\n symbol = contracts[0].symbol\n self.market_order(symbol, 1)\n self.market_on_close_order(symbol, -1)\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting that historical data can be requested with tick resolution without requiring\na tick resolution subscription", "output": "```python\n\n\nfrom datetime import timedelta\nfrom AlgorithmImports import *\n\nclass TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 8)\n self.set_end_date(2013, 10, 8)\n\n # Subscribing SPY and IBM with daily and hour resolution instead of tick resolution\n spy = self.add_equity(\"SPY\", Resolution.DAILY).symbol\n ibm = self.add_equity(\"IBM\", Resolution.HOUR).symbol\n\n # Requesting history for SPY and IBM (separately) with tick resolution\n spy_history = self.history[Tick](spy, timedelta(days=1), Resolution.TICK)\n if not any(spy_history):\n raise AssertionError(\"SPY tick history is empty\")\n\n ibm_history = self.history[Tick](ibm, timedelta(days=1), Resolution.TICK)\n if not any(ibm_history):\n raise AssertionError(\"IBM tick history is empty\")\n\n # Requesting history for SPY and IBM (together) with tick resolution\n spy_ibm_history = self.history[Tick]([spy, ibm], timedelta(days=1), Resolution.TICK)\n if not any(spy_ibm_history):\n raise AssertionError(\"Compound SPY and IBM tick history is empty\")\n\n self.quit()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic algorithm demonstrating how to place trailing stop orders.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass TrailingStopOrderRegressionAlgorithm(QCAlgorithm):\n '''Basic algorithm demonstrating how to place trailing stop orders.'''\n\n buy_trailing_amount = 2\n sell_trailing_amount = 0.5\n asynchronous_orders = False\n\n def initialize(self):\n\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n self.set_cash(100000)\n\n self._symbol = self.add_equity(\"SPY\").symbol\n\n self._buy_order_ticket: OrderTicket = None\n self._sell_order_ticket: OrderTicket = None\n self._previous_slice: Slice = None\n\n def on_data(self, slice: Slice):\n if not slice.contains_key(self._symbol):\n return\n\n if self._buy_order_ticket is None:\n self._buy_order_ticket = self.trailing_stop_order(self._symbol, 100, trailing_amount=self.buy_trailing_amount, trailing_as_percentage=False, asynchronous=self.asynchronous_orders)\n elif self._buy_order_ticket.status != OrderStatus.FILLED:\n stop_price = self._buy_order_ticket.get(OrderField.STOP_PRICE)\n\n # Get the previous bar to compare to the stop price,\n # because stop price update attempt with the current slice data happens after OnData.\n low = self._previous_slice.quote_bars[self._symbol].ask.low if self._previous_slice.quote_bars.contains_key(self._symbol) \\\n else self._previous_slice.bars[self._symbol].low\n\n stop_price_to_market_price_distance = stop_price - low\n if stop_price_to_market_price_distance > self.buy_trailing_amount:\n raise AssertionError(f\"StopPrice {stop_price} should be within {self.buy_trailing_amount} of the previous low price {low} at all times.\")\n\n if self._sell_order_ticket is None:\n if self.portfolio.invested:\n self._sell_order_ticket = self.trailing_stop_order(self._symbol, -100, trailing_amount=self.sell_trailing_amount, trailing_as_percentage=False, asynchronous=self.asynchronous_orders)\n elif self._sell_order_ticket.status != OrderStatus.FILLED:\n stop_price = self._sell_order_ticket.get(OrderField.STOP_PRICE)\n\n # Get the previous bar to compare to the stop price,\n # because stop price update attempt with the current slice data happens after OnData.\n high = self._previous_slice.quote_bars[self._symbol].bid.high if self._previous_slice.quote_bars.contains_key(self._symbol) \\\n else self._previous_slice.bars[self._symbol].high\n stop_price_to_market_price_distance = high - stop_price\n if stop_price_to_market_price_distance > self.sell_trailing_amount:\n raise AssertionError(f\"StopPrice {stop_price} should be within {self.sell_trailing_amount} of the previous high price {high} at all times.\")\n\n self._previous_slice = slice\n\n def on_order_event(self, orderEvent: OrderEvent):\n if orderEvent.status == OrderStatus.FILLED:\n if orderEvent.direction == OrderDirection.BUY:\n stop_price = self._buy_order_ticket.get(OrderField.STOP_PRICE)\n if orderEvent.fill_price < stop_price:\n raise AssertionError(f\"Buy trailing stop order should have filled with price greater than or equal to the stop price {stop_price}. \"\n f\"Fill price: {orderEvent.fill_price}\")\n else:\n stop_price = self._sell_order_ticket.get(OrderField.STOP_PRICE)\n if orderEvent.fill_price > stop_price:\n raise AssertionError(f\"Sell trailing stop order should have filled with price less than or equal to the stop price {stop_price}. \"\n f\"Fill price: {orderEvent.fill_price}\")\n\n def on_end_of_algorithm(self):\n for ticket in self.transactions.get_order_tickets():\n if ticket.submit_request.asynchronous != self.asynchronous_orders:\n raise AssertionError(\"Expected all orders to have the same asynchronous flag as the algorithm.\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting the behavior of different callback commands call", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass InvalidCommand():\n variable = 10\n\nclass VoidCommand():\n quantity = 0\n target = []\n parameters = {}\n targettime = None\n\n def run(self, algo: IAlgorithm) -> bool:\n if not self.targettime or self.targettime != algo.time:\n return False\n tag = self.parameters[\"tag\"]\n algo.order(self.target[0], self.get_quantity(), tag=tag)\n return True\n\n def get_quantity(self):\n return self.quantity\n\nclass BoolCommand(Command):\n something_else = {}\n array_test = []\n result = False\n\n def run(self, algo) -> bool:\n trade_ibm = self.my_custom_method()\n if trade_ibm:\n algo.debug(f\"BoolCommand.run: {str(self)}\")\n algo.buy(\"IBM\", 1)\n return trade_ibm\n\n def my_custom_method(self):\n return self.result\n\nclass CallbackCommandRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n\n self.add_equity(\"SPY\")\n self.add_equity(\"IBM\")\n self.add_equity(\"BAC\")\n\n self.add_command(VoidCommand)\n self.add_command(BoolCommand)\n\n threw_exception = False\n try:\n self.add_command(InvalidCommand)\n except:\n threw_exception = True\n if not threw_exception:\n raise ValueError('InvalidCommand did not throw!')\n\n bool_command = BoolCommand()\n bool_command.result = True\n bool_command.something_else = { \"Property\": 10 }\n bool_command.array_test = [ \"SPY\", \"BTCUSD\" ]\n link = self.link(bool_command)\n if \"&command%5barray_test%5d%5b0%5d=SPY&command%5barray_test%5d%5b1%5d=BTCUSD&command%5bresult%5d=True&command%5bsomething_else%5d%5bProperty%5d=10&command%5b%24type%5d=BoolCommand\" not in link:\n raise ValueError(f'Invalid link was generated! {link}')\n\n potential_command = VoidCommand()\n potential_command.target = [ \"BAC\" ]\n potential_command.quantity = 10\n potential_command.parameters = { \"tag\": \"Signal X\" }\n\n command_link = self.link(potential_command)\n if \"&command%5btarget%5d%5b0%5d=BAC&command%5bquantity%5d=10&command%5bparameters%5d%5btag%5d=Signal+X&command%5b%24type%5d=VoidCommand\" not in command_link:\n raise ValueError(f'Invalid link was generated! {command_link}')\n self.notify.email(\"email@address\", \"Trade Command Event\", f\"Signal X trade\\nFollow link to trigger: {command_link}\")\n\n untyped_command_link = self.link({ \"symbol\": \"SPY\", \"parameters\": { \"quantity\": 10 } })\n if \"&command%5bsymbol%5d=SPY&command%5bparameters%5d%5bquantity%5d=10\" not in untyped_command_link:\n raise ValueError(f'Invalid link was generated! {untyped_command_link}')\n self.notify.email(\"email@address\", \"Untyped Command Event\", f\"Signal Y trade\\nFollow link to trigger: {untyped_command_link}\")\n\n # We need to create a project on QuantConnect to test the broadcast_command method\n # and use the project_id in the broadcast_command call\n self.project_id = 21805137\n\n # All live deployments receive the broadcasts below\n broadcast_result = self.broadcast_command(potential_command)\n broadcast_result2 = self.broadcast_command({ \"symbol\": \"SPY\", \"parameters\": { \"quantity\": 10 } })\n\n def on_command(self, data: object) -> bool:\n self.debug(f\"on_command: {str(data)}\")\n self.buy(data.symbol, data.parameters[\"quantity\"])\n return True # False, None\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm demonstrating custom charting support in QuantConnect.\nThe entire charting system of quantconnect is adaptable. You can adjust it to draw whatever you'd like.\nCharts can be stacked, or overlayed on each other. Series can be candles, lines or scatter plots.\nEven the default behaviours of QuantConnect can be overridden.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomChartingAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2016,1,1)\n self.set_end_date(2017,1,1)\n self.set_cash(100000)\n\n spy = self.add_equity(\"SPY\", Resolution.DAILY).symbol\n\n # In your initialize method:\n # Chart - Master Container for the Chart:\n stock_plot = Chart(\"Trade Plot\")\n # On the Trade Plotter Chart we want 3 series: trades and price:\n stock_plot.add_series(Series(\"Buy\", SeriesType.SCATTER, 0))\n stock_plot.add_series(Series(\"Sell\", SeriesType.SCATTER, 0))\n stock_plot.add_series(Series(\"Price\", SeriesType.LINE, 0))\n self.add_chart(stock_plot)\n\n # On the Average Cross Chart we want 2 series, slow MA and fast MA\n avg_cross = Chart(\"Average Cross\")\n avg_cross.add_series(Series(\"FastMA\", SeriesType.LINE, 0))\n avg_cross.add_series(Series(\"SlowMA\", SeriesType.LINE, 0))\n self.add_chart(avg_cross)\n\n # There's support for candlestick charts built-in:\n weekly_spy_plot = Chart(\"Weekly SPY\")\n spy_candlesticks = CandlestickSeries(\"SPY\")\n weekly_spy_plot.add_series(spy_candlesticks)\n self.add_chart(weekly_spy_plot)\n\n self.consolidate(spy, Calendar.WEEKLY, lambda bar: self.plot(\"Weekly SPY\", \"SPY\", bar))\n\n self.fast_ma = 0\n self.slow_ma = 0\n self.last_price = 0\n self.resample = datetime.min\n self.resample_period = (self.end_date - self.start_date) / 2000\n\n def on_data(self, slice):\n if slice[\"SPY\"] is None: return\n\n self.last_price = slice[\"SPY\"].close\n if self.fast_ma == 0: self.fast_ma = self.last_price\n if self.slow_ma == 0: self.slow_ma = self.last_price\n self.fast_ma = (0.01 * self.last_price) + (0.99 * self.fast_ma)\n self.slow_ma = (0.001 * self.last_price) + (0.999 * self.slow_ma)\n\n\n if self.time > self.resample:\n self.resample = self.time + self.resample_period\n self.plot(\"Average Cross\", \"FastMA\", self.fast_ma)\n self.plot(\"Average Cross\", \"SlowMA\", self.slow_ma)\n\n # On the 5th days when not invested buy:\n if not self.portfolio.invested and self.time.day % 13 == 0:\n \tself.order(\"SPY\", (int)(self.portfolio.margin_remaining / self.last_price))\n \tself.plot(\"Trade Plot\", \"Buy\", self.last_price)\n elif self.time.day % 21 == 0 and self.portfolio.invested:\n self.plot(\"Trade Plot\", \"Sell\", self.last_price)\n self.liquidate()\n\n def on_end_of_day(self, symbol):\n #Log the end of day prices:\n self.plot(\"Trade Plot\", \"Price\", self.last_price)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: def initialize(self):", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomDataTypeHistoryAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2017, 8, 20)\n self.set_end_date(2017, 8, 20)\n\n self._symbol = self.add_data(CustomDataType, \"CustomDataType\", Resolution.HOUR).symbol\n\n history = list(self.history[CustomDataType](self._symbol, 48, Resolution.HOUR))\n\n if len(history) == 0:\n raise AssertionError(\"History request returned no data\")\n\n self._assert_history_data(history)\n\n history2 = list(self.history[CustomDataType]([self._symbol], 48, Resolution.HOUR))\n\n if len(history2) != len(history):\n raise AssertionError(\"History requests returned different data\")\n\n self._assert_history_data([y.values()[0] for y in history2])\n\n def _assert_history_data(self, history: List[PythonData]) -> None:\n expected_keys = ['open', 'close', 'high', 'low', 'some_property']\n if any(any(not x[key] for key in expected_keys)\n or x[\"some_property\"] != \"some property value\"\n for x in history):\n raise AssertionError(\"History request returned data without the expected properties\")\n\nclass CustomDataType(PythonData):\n\n def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live: bool) -> SubscriptionDataSource:\n source = \"https://www.dl.dropboxusercontent.com/s/d83xvd7mm9fzpk0/path_to_my_csv_data.csv?dl=0\"\n return SubscriptionDataSource(source, SubscriptionTransportMedium.REMOTE_FILE)\n\n def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live: bool) -> BaseData:\n if not (line.strip()):\n return None\n\n data = line.split(',')\n obj_data = CustomDataType()\n obj_data.symbol = config.symbol\n\n try:\n obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S') + timedelta(hours=20)\n obj_data[\"open\"] = float(data[1])\n obj_data[\"high\"] = float(data[2])\n obj_data[\"low\"] = float(data[3])\n obj_data[\"close\"] = float(data[4])\n obj_data.value = obj_data[\"close\"]\n\n # property for asserting the correct data is fetched\n obj_data[\"some_property\"] = \"some property value\"\n except ValueError:\n return None\n\n return obj_data\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template algorithm simply initializes the date range and cash", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateFillForwardAlgorithm(QCAlgorithm):\n '''Basic template algorithm simply initializes the date range and cash'''\n\n def initialize(self):\n '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n \n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,11,30) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_security(SecurityType.EQUITY, \"ASUR\", Resolution.SECOND)\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n \n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(\"ASUR\", 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: We add an option contract using 'QCAlgorithm.add_option_contract' and place a trade, the underlying\ngets deselected from the universe selection but should still be present since we manually added the option contract.\nLater we call 'QCAlgorithm.remove_option_contract' and expect both option and underlying to be removed.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AddOptionContractFromUniverseRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2014, 6, 5)\n self.set_end_date(2014, 6, 9)\n\n self._expiration = datetime(2014, 6, 21)\n self._security_changes = None\n self._option = None\n self._traded = False\n\n self._twx = Symbol.create(\"TWX\", SecurityType.EQUITY, Market.USA)\n self._aapl = Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA)\n self.universe_settings.resolution = Resolution.MINUTE\n self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW\n\n self.add_universe(self.selector, self.selector)\n\n def selector(self, fundamental):\n if self.time <= datetime(2014, 6, 5):\n return [ self._twx ]\n return [ self._aapl ]\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if self._option != None and self.securities[self._option].price != 0 and not self._traded:\n self._traded = True\n self.buy(self._option, 1)\n\n if self.time == datetime(2014, 6, 6, 14, 0, 0):\n # liquidate & remove the option\n self.remove_option_contract(self._option)\n\n def on_securities_changed(self, changes):\n # keep track of all removed and added securities\n if self._security_changes == None:\n self._security_changes = changes\n else:\n self._security_changes += changes\n\n if any(security.symbol.security_type == SecurityType.OPTION for security in changes.added_securities):\n return\n\n for addedSecurity in changes.added_securities:\n option_chain = self.option_chain(addedSecurity.symbol)\n options = sorted(option_chain, key=lambda x: x.id.symbol)\n\n option = next((option\n for option in options\n if option.id.date == self._expiration and\n option.id.option_right == OptionRight.CALL and\n option.id.option_style == OptionStyle.AMERICAN), None)\n\n self.add_option_contract(option)\n\n # just keep the first we got\n if self._option == None:\n self._option = option\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm of how to use RangeConsolidator", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass RangeConsolidatorAlgorithm(QCAlgorithm):\n def get_resolution(self) -> Resolution:\n return Resolution.DAILY\n\n def get_range(self) -> int:\n return 100\n\n def initialize(self) -> None:\n self.set_start_and_end_dates()\n self.add_equity(\"SPY\", self.get_resolution())\n range_consolidator = self.create_range_consolidator()\n range_consolidator.data_consolidated += self.on_data_consolidated\n self._first_data_consolidated = None\n\n self.subscription_manager.add_consolidator(\"SPY\", range_consolidator)\n\n def set_start_and_end_dates(self) -> None:\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n\n def on_end_of_algorithm(self) -> None:\n if not self._first_data_consolidated:\n raise AssertionError(\"The consolidator should have consolidated at least one RangeBar, but it did not consolidated any one\")\n\n def create_range_consolidator(self) -> RangeConsolidator:\n return RangeConsolidator(self.get_range())\n\n def on_data_consolidated(self, sender: object, range_bar: RangeBar) -> None:\n if not self._first_data_consolidated:\n self._first_data_consolidated = range_bar\n\n if round(range_bar.high - range_bar.low, 2) != self.get_range() * 0.01: # The minimum price change for SPY is 0.01, therefore the range size of each bar equals Range * 0.01\n raise AssertionError(f\"The difference between the High and Low for all RangeBar's should be {self.get_range() * 0.01}, but for this RangeBar was {round(range_bar.low - range_bar.high, 2)}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Alpha model for ETF constituents, where we generate insights based on the weighting\nof the ETF constituent", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nconstituent_data = []\n\nclass ETFConstituentAlphaModel(AlphaModel):\n def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:\n pass\n\n ### \n ### Creates new insights based on constituent data and their weighting\n ### in their respective ETF\n ### \n def update(self, algorithm: QCAlgorithm, data: Slice) -> list[Insight]:\n global constituent_data\n insights = []\n\n for constituent in constituent_data:\n if constituent.symbol not in data.bars and \\\n constituent.symbol not in data.quote_bars:\n\n continue\n\n insight_direction = InsightDirection.UP if constituent.weight is not None and constituent.weight >= 0.01 else InsightDirection.DOWN\n\n insights.append(Insight(\n algorithm.utc_time,\n constituent.symbol,\n timedelta(days=1),\n InsightType.PRICE,\n insight_direction,\n float(1 * int(insight_direction)),\n 1.0,\n weight=float(0 if constituent.weight is None else constituent.weight)\n ))\n\n return insights\n\nclass ETFConstituentPortfolioModel(PortfolioConstructionModel):\n def __init__(self) -> None:\n self.has_added = False\n\n ### \n ### Securities changed, detects if we've got new additions to the universe\n ### so that we don't try to trade every loop\n ### \n def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:\n self.has_added = len(changes.added_securities) != 0\n\n ### \n ### Creates portfolio targets based on the insights provided to us by the alpha model.\n ### Emits portfolio targets setting the quantity to the weight of the constituent\n ### in its respective ETF.\n ### \n def create_targets(self, algorithm: QCAlgorithm, insights: list[Insight]) -> list[PortfolioTarget]:\n if not self.has_added:\n return []\n\n final_insights = []\n for insight in insights:\n final_insights.append(PortfolioTarget(insight.symbol, float(0 if insight.weight is None else insight.weight)))\n self.has_added = False\n\n return final_insights\n\nclass ETFConstituentExecutionModel(ExecutionModel):\n ### \n ### Liquidates if constituents have been removed from the universe\n ### \n def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:\n for change in changes.removed_securities:\n algorithm.liquidate(change.symbol)\n\n ### \n ### Creates orders for constituents that attempts to add\n ### the weighting of the constituent in our portfolio. The\n ### resulting algorithm portfolio weight might not be equal\n ### to the leverage of the ETF (1x, 2x, 3x, etc.)\n ### \n def execute(self, algorithm: QCAlgorithm, targets: list[IPortfolioTarget]) -> None:\n for target in targets:\n algorithm.set_holdings(target.symbol, target.quantity)\n\nclass ETFConstituentUniverseFrameworkRegressionAlgorithm(QCAlgorithm):\n ### \n ### Initializes the algorithm, setting up the framework classes and ETF constituent universe settings\n ### \n def initialize(self) -> None:\n self.set_start_date(2020, 12, 1)\n self.set_end_date(2021, 1, 31)\n self.set_cash(100000)\n\n self.set_alpha(ETFConstituentAlphaModel())\n self.set_portfolio_construction(ETFConstituentPortfolioModel())\n self.set_execution(ETFConstituentExecutionModel())\n\n self.universe_settings.resolution = Resolution.HOUR\n universe = self.add_universe(self.universe.etf(\"SPY\", self.universe_settings, self.filter_etf_constituents))\n\n historical_data = self.history(universe, 1, flatten=True)\n if len(historical_data) < 200:\n raise ValueError(f\"Unexpected universe DataCollection count {len(historical_data)}! Expected > 200\")\n\n ### \n ### Filters ETF constituents\n ### \n ### ETF constituents\n ### ETF constituent Symbols that we want to include in the algorithm\n def filter_etf_constituents(self, constituents: list[ETFConstituentUniverse]) -> list[Symbol]:\n global constituent_data\n\n constituent_data_local = [i for i in constituents if i.weight and i.weight >= 0.001]\n constituent_data = list(constituent_data_local)\n\n return [i.symbol for i in constituent_data_local]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm verifies automatic option contract assignment behavior.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionAssignmentRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2015, 12, 23)\n self.set_end_date(2015, 12, 28)\n self.set_cash(100000)\n self.stock = self.add_equity(\"GOOG\", Resolution.MINUTE)\n\n contracts = list(self.option_chain(self.stock.symbol))\n\n self.put_option_symbol = sorted(\n [c for c in contracts if c.id.option_right == OptionRight.PUT and c.id.strike_price == 800],\n key=lambda c: c.id.date\n )[0]\n\n self.call_option_symbol = sorted(\n [c for c in contracts if c.id.option_right == OptionRight.CALL and c.id.strike_price == 600],\n key=lambda c: c.id.date\n )[0]\n\n self.put_option = self.add_option_contract(self.put_option_symbol)\n self.call_option = self.add_option_contract(self.call_option_symbol)\n\n def on_data(self, data):\n if not self.portfolio.invested and self.stock.price != 0 and self.put_option.price != 0 and self.call_option.price != 0:\n #this gets executed on start and after each auto-assignment, finally ending with expiration assignment\n if self.time < self.put_option_symbol.id.date:\n self.market_order(self.put_option_symbol, -1)\n\n if self.time < self.call_option_symbol.id.date:\n self.market_order(self.call_option_symbol, -1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm for fractional forex pair", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FractionalQuantityRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n\n self.set_start_date(2015, 11, 12)\n self.set_end_date(2016, 4, 1)\n self.set_cash(100000)\n self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH)\n\n self.set_time_zone(TimeZones.UTC)\n\n security = self.add_security(SecurityType.CRYPTO, \"BTCUSD\", Resolution.DAILY, Market.GDAX, False, 1, True)\n\n ### The default buying power model for the Crypto security type is now CashBuyingPowerModel.\n ### Since this test algorithm uses leverage we need to set a buying power model with margin.\n security.set_buying_power_model(SecurityMarginModel(3.3))\n\n con = TradeBarConsolidator(1)\n self.subscription_manager.add_consolidator(\"BTCUSD\", con)\n con.data_consolidated += self.data_consolidated\n self.set_benchmark(security.symbol)\n\n def data_consolidated(self, sender, bar):\n quantity = math.floor((self.portfolio.cash + self.portfolio.total_fees) / abs(bar.value + 1))\n btc_qnty = float(self.portfolio[\"BTCUSD\"].quantity)\n\n if not self.portfolio.invested:\n self.order(\"BTCUSD\", quantity)\n elif btc_qnty == quantity:\n self.order(\"BTCUSD\", 0.1)\n elif btc_qnty == quantity + 0.1:\n self.order(\"BTCUSD\", 0.01)\n elif btc_qnty == quantity + 0.11:\n self.order(\"BTCUSD\", -0.02)\n elif btc_qnty == quantity + 0.09:\n # should fail (below minimum order quantity)\n self.order(\"BTCUSD\", 0.00001)\n self.set_holdings(\"BTCUSD\", -2.0)\n self.set_holdings(\"BTCUSD\", 2.0)\n self.quit()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: CapmAlphaRankingFrameworkAlgorithm: example of custom scheduled universe selection model\nUniverse Selection inspired by https://www.quantconnect.com/tutorials/strategy-library/capm-alpha-ranking-strategy-on-dow-30-companies", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CapmAlphaRankingFrameworkAlgorithm(QCAlgorithm):\n '''CapmAlphaRankingFrameworkAlgorithm: example of custom scheduled universe selection model'''\n\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.MINUTE\n\n self.set_start_date(2016, 1, 1) #Set Start Date\n self.set_end_date(2017, 1, 1) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n # set algorithm framework models\n self.set_universe_selection(CapmAlphaRankingUniverseSelectionModel())\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1), 0.025, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))\n\nclass CapmAlphaRankingUniverseSelectionModel(UniverseSelectionModel):\n '''This universe selection model picks stocks with the highest alpha: interception of the linear regression against a benchmark.'''\n\n period = 21\n benchmark = \"SPY\"\n\n # Symbols of Dow 30 companies.\n _symbols = [Symbol.create(x, SecurityType.EQUITY, Market.USA)\n for x in [\"AAPL\", \"AXP\", \"BA\", \"CAT\", \"CSCO\", \"CVX\", \"DD\", \"DIS\", \"GE\", \"GS\",\n \"HD\", \"IBM\", \"INTC\", \"JPM\", \"KO\", \"MCD\", \"MMM\", \"MRK\", \"MSFT\",\n \"NKE\",\"PFE\", \"PG\", \"TRV\", \"UNH\", \"UTX\", \"V\", \"VZ\", \"WMT\", \"XOM\"]]\n\n def create_universes(self, algorithm):\n\n # Adds the benchmark to the user defined universe\n benchmark = algorithm.add_equity(self.benchmark, Resolution.DAILY)\n\n # Defines a schedule universe that fires after market open when the month starts\n return [ ScheduledUniverse(\n benchmark.exchange.time_zone,\n algorithm.date_rules.month_start(self.benchmark),\n algorithm.time_rules.after_market_open(self.benchmark),\n lambda datetime: self.select_pair(algorithm, datetime),\n algorithm.universe_settings)]\n\n def select_pair(self, algorithm, date):\n '''Selects the pair (two stocks) with the highest alpha'''\n dictionary = dict()\n benchmark = self._get_returns(algorithm, self.benchmark)\n ones = np.ones(len(benchmark))\n\n for symbol in self._symbols:\n prices = self._get_returns(algorithm, symbol)\n if prices is None: continue\n A = np.vstack([prices, ones]).T\n\n # Calculate the Least-Square fitting to the returns of a given symbol and the benchmark\n ols = np.linalg.lstsq(A, benchmark)[0]\n dictionary[symbol] = ols[1]\n\n # Returns the top 2 highest alphas\n ordered_dictionary = sorted(dictionary.items(), key= lambda x: x[1], reverse=True)\n return [x[0] for x in ordered_dictionary[:2]]\n\n def _get_returns(self, algorithm, symbol):\n\n history = algorithm.history([symbol], self.period, Resolution.DAILY)\n if history.empty: return None\n\n window = RollingWindow(self.period)\n rate_of_change = RateOfChange(1)\n\n def roc_updated(s, item):\n window.add(item.value)\n\n rate_of_change.updated += roc_updated\n\n history = history.close.reset_index(level=0, drop=True).items()\n\n for time, value in history:\n rate_of_change.update(time, value)\n\n return [ x for x in window]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm is for testing a custom Python filter for options\nthat returns a OptionFilterUniverse.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FilterUniverseRegressionAlgorithm(QCAlgorithm):\n underlying_ticker = \"GOOG\"\n\n def initialize(self):\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 28)\n self.set_cash(100000)\n\n equity = self.add_equity(self.underlying_ticker)\n option = self.add_option(self.underlying_ticker)\n self.option_symbol = option.symbol\n\n # Set our custom universe filter\n option.set_filter(self.filter_function)\n\n # use the underlying equity as the benchmark\n self.set_benchmark(equity.symbol)\n\n def filter_function(self, universe):\n universe = universe.weeklys_only().strikes(-5, +5).calls_only().expiration(0, 1)\n return universe\n\n def on_data(self,slice):\n if self.portfolio.invested: return\n\n for kvp in slice.option_chains:\n \n if kvp.key != self.option_symbol: continue\n\n chain = kvp.value\n contracts = [option for option in sorted(chain, key = lambda x:x.strike, reverse = True)]\n \n if contracts:\n self.market_order(contracts[0].symbol, 1)\n\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to validate SecurityCache.Session functionality.\nVerifies that daily session bars (Open, High, Low, Close, Volume) are correctly", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass SecuritySessionRegressionAlgorithm(QCAlgorithm):\n \n def initialize(self):\n self.add_security_initializer(self.initialize_session_tracking)\n self.initialize_security()\n\n # Check initial session values\n session = self.security.session\n if session is None:\n raise RegressionTestException(\"Security.Session is none\")\n if (session.open != 0\n or session.high != 0\n or session.low != 0\n or session.close != 0\n or session.volume != 0\n or session.open_interest != 0):\n raise RegressionTestException(\"Session should start with all zero values.\")\n \n self.security_was_removed = False\n self.open = self.close = self.high = self.volume = 0\n self.low = float('inf')\n self.current_date = self.start_date\n self.previous_session_bar = None\n\n self.schedule.on(\n self.date_rules.every_day(),\n self.time_rules.after_market_close(self.security.symbol, 1),\n self.validate_session_bars\n )\n\n def initialize_security(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.security = self.add_equity(\"SPY\", Resolution.HOUR)\n\n def initialize_session_tracking(self, security):\n # activate session tracking\n security.session.size = 3\n\n def _are_equal(self, value1, value2):\n tolerance = 1e-10\n return abs(value1 - value2) <= tolerance\n \n def validate_session_bars(self):\n session = self.security.session\n # At this point the data was consolidated (market close)\n\n # Save previous session bar\n self.previous_session_bar = {\n 'date': self.current_date,\n 'open': self.open,\n 'high': self.high,\n 'low': self.low,\n 'close': self.close,\n 'volume': self.volume\n }\n\n if self.security_was_removed:\n self.previous_session_bar = None\n self.security_was_removed = False\n return\n\n # Check current session values\n if (not self._are_equal(session.open, self.open)\n or not self._are_equal(session.high, self.high)\n or not self._are_equal(session.low, self.low)\n or not self._are_equal(session.close, self.close)\n or not self._are_equal(session.volume, self.volume)):\n raise RegressionTestException(\"Mismatch in current session bar (OHLCV)\")\n\n def is_within_market_hours(self, current_date_time):\n market_open = self.security.exchange.hours.get_next_market_open(current_date_time.date(), False).time()\n market_close = self.security.exchange.hours.get_next_market_close(current_date_time.date(), False).time()\n current_time = current_date_time.time()\n return market_open < current_time <= market_close\n\n def on_data(self, data):\n if not self.is_within_market_hours(data.time):\n # Skip data outside market hours\n return\n\n # Accumulate data within regular market hours\n # to later compare against the Session values\n self.accumulate_session_data(data)\n\n def accumulate_session_data(self, data):\n symbol = self.security.symbol\n if self.current_date.date() == data.time.date():\n # Same trading day\n if self.open == 0:\n self.open = data[symbol].open\n self.high = max(self.high, data[symbol].high)\n self.low = min(self.low, data[symbol].low)\n self.close = data[symbol].close\n self.volume += data[symbol].volume\n else:\n # New trading day\n\n if self.previous_session_bar is not None:\n session = self.security.session\n if (self.previous_session_bar['open'] != session[1].open\n or self.previous_session_bar['high'] != session[1].high\n or self.previous_session_bar['low'] != session[1].low\n or self.previous_session_bar['close'] != session[1].close\n or self.previous_session_bar['volume'] != session[1].volume):\n raise RegressionTestException(\"Mismatch in previous session bar (OHLCV)\")\n\n # This is the first data point of the new session\n self.open = data[symbol].open\n self.close = data[symbol].close\n self.high = data[symbol].high\n self.low = data[symbol].low\n self.volume = data[symbol].volume\n self.current_date = data.time\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting that tick history request includes both trade and quote data", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass HistoryTickRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 12)\n self.set_end_date(2013, 10, 13)\n\n self._symbol = self.add_equity(\"SPY\", Resolution.TICK).symbol\n\n trades_count = 0\n quotes_count = 0\n for point in self.history[Tick](self._symbol, timedelta(days=1), Resolution.TICK):\n if point.tick_type == TickType.TRADE:\n trades_count += 1\n elif point.tick_type == TickType.QUOTE:\n quotes_count += 1\n\n if trades_count > 0 and quotes_count > 0:\n # We already found at least one tick of each type, we can exit the loop\n break\n\n if trades_count == 0 or quotes_count == 0:\n raise AssertionError(\"Expected to find at least one tick of each type (quote and trade)\")\n\n self.quit()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to assert the behavior of .", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm\nfrom Alphas.EmaCrossAlphaModel import EmaCrossAlphaModel\n\nclass EmaCrossAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):\n\n def initialize(self):\n super().initialize()\n self.set_alpha(EmaCrossAlphaModel())\n\n def on_end_of_algorithm(self):\n pass\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of how to define a universe using the fundamental data", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel\n\nclass FundamentalUniverseSelectionRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2014, 3, 26)\n self.set_end_date(2014, 4, 7)\n\n self.universe_settings.resolution = Resolution.DAILY\n\n self.add_equity(\"SPY\")\n self.add_equity(\"AAPL\")\n\n self.set_universe_selection(FundamentalUniverseSelectionModelTest())\n\n self.changes = None\n\n def on_data(self, data):\n # if we have no changes, do nothing\n if self.changes is None: return\n\n # liquidate removed securities\n for security in self.changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n self.debug(\"Liquidated Stock: \" + str(security.symbol.value))\n\n # we want 50% allocation in each security in our universe\n for security in self.changes.added_securities:\n self.set_holdings(security.symbol, 0.02)\n\n self.changes = None\n\n # this event fires whenever we have changes to our universe\n def on_securities_changed(self, changes):\n self.changes = changes\n\nclass FundamentalUniverseSelectionModelTest(FundamentalUniverseSelectionModel):\n\n def select(self, algorithm, fundamental):\n # sort descending by daily dollar volume\n sorted_by_dollar_volume = sorted([x for x in fundamental if x.price > 1],\n key=lambda x: x.dollar_volume, reverse=True)\n\n # sort descending by P/E ratio\n sorted_by_pe_ratio = sorted(sorted_by_dollar_volume, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)\n\n # take the top entries from our sorted collection\n return [ x.symbol for x in sorted_by_pe_ratio[:2] ]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of how to define a universe using the fundamental data", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FundamentalUniverseSelectionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2014, 3, 25)\n self.set_end_date(2014, 4, 7)\n\n self.universe_settings.resolution = Resolution.DAILY\n\n self.add_equity(\"SPY\")\n self.add_equity(\"AAPL\")\n\n self.set_universe_selection(FundamentalUniverseSelectionModel(self.select))\n\n self.changes = None\n self.number_of_symbols_fundamental = 10\n\n # return a list of three fixed symbol objects\n def selection_function(self, fundamental):\n # sort descending by daily dollar volume\n sorted_by_dollar_volume = sorted([x for x in fundamental if x.price > 1],\n key=lambda x: x.dollar_volume, reverse=True)\n\n # sort descending by P/E ratio\n sorted_by_pe_ratio = sorted(sorted_by_dollar_volume, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)\n\n # take the top entries from our sorted collection\n return [ x.symbol for x in sorted_by_pe_ratio[:self.number_of_symbols_fundamental] ]\n\n def on_data(self, data):\n # if we have no changes, do nothing\n if self.changes is None: return\n\n # liquidate removed securities\n for security in self.changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n self.debug(\"Liquidated Stock: \" + str(security.symbol.value))\n\n # we want 50% allocation in each security in our universe\n for security in self.changes.added_securities:\n self.set_holdings(security.symbol, 0.02)\n\n self.changes = None\n\n # this event fires whenever we have changes to our universe\n def on_securities_changed(self, changes):\n self.changes = changes\n\n def select(self, fundamental):\n # sort descending by daily dollar volume\n sorted_by_dollar_volume = sorted([x for x in fundamental if x.has_fundamental_data and x.price > 1],\n key=lambda x: x.dollar_volume, reverse=True)\n\n # sort descending by P/E ratio\n sorted_by_pe_ratio = sorted(sorted_by_dollar_volume, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)\n\n # take the top entries from our sorted collection\n return [ x.symbol for x in sorted_by_pe_ratio[:2] ]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Test algorithm using 'QCAlgorithm.add_risk_management(IRiskManagementModel)'", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AddRiskManagementAlgorithm(QCAlgorithm):\n '''Basic template framework algorithm uses framework components to define the algorithm.'''\n\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.universe_settings.resolution = Resolution.MINUTE\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n symbols = [ Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA) ]\n\n # set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel(symbols))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n\n # Both setting methods should work\n risk_model = CompositeRiskManagementModel(MaximumDrawdownPercentPortfolio(0.02))\n risk_model.add_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.01))\n\n self.set_risk_management(MaximumDrawdownPercentPortfolio(0.02))\n self.add_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.01))\n\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic Continuous Futures Template Algorithm with extended market hours", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateContinuousFutureWithExtendedMarketAlgorithm(QCAlgorithm):\n '''Basic template algorithm simply initializes the date range and cash'''\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013, 7, 1)\n self.set_end_date(2014, 1, 1)\n\n self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI,\n data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,\n data_mapping_mode = DataMappingMode.LAST_TRADING_DAY,\n contract_depth_offset = 0,\n extended_market_hours = True)\n\n self._fast = self.sma(self._continuous_contract.symbol, 4, Resolution.DAILY)\n self._slow = self.sma(self._continuous_contract.symbol, 10, Resolution.DAILY)\n self._current_contract = None\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n for changed_event in data.symbol_changed_events.values():\n if changed_event.symbol == self._continuous_contract.symbol:\n self.log(f\"SymbolChanged event: {changed_event}\")\n\n if not self.is_market_open(self._continuous_contract.symbol):\n return\n\n if not self.portfolio.invested:\n if self._fast.current.value > self._slow.current.value:\n self._current_contract = self.securities[self._continuous_contract.mapped]\n self.buy(self._current_contract.symbol, 1)\n elif self._fast.current.value < self._slow.current.value:\n self.liquidate()\n\n if self._current_contract is not None and self._current_contract.symbol != self._continuous_contract.mapped:\n self.log(f\"{Time} - rolling position from {self._current_contract.symbol} to {self._continuous_contract.mapped}\")\n\n current_position_size = self._current_contract.holdings.quantity\n self.liquidate(self._current_contract.symbol)\n self.buy(self._continuous_contract.mapped, current_position_size)\n self._current_contract = self.securities[self._continuous_contract.mapped]\n\n def on_order_event(self, order_event):\n self.debug(\"Purchased Stock: {0}\".format(order_event.symbol))\n\n def on_securities_changed(self, changes):\n self.debug(f\"{self.time}-{changes}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Asserts that algorithms can be universe-only, that is, universe selection is performed even if the ETF security is not explicitly added.\nReproduces https://github.com/QuantConnect/Lean/issues/7473", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass UniverseOnlyRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 12, 1)\n self.set_end_date(2020, 12, 12)\n self.set_cash(100000)\n\n self.universe_settings.resolution = Resolution.DAILY\n\n # Add universe without a security added\n self.add_universe(self.universe.etf(\"GDVD\", self.universe_settings, self.filter_universe))\n\n self.selection_done = False\n\n def filter_universe(self, constituents: List[ETFConstituentData]) -> List[Symbol]:\n self.selection_done = True\n return [x.symbol for x in constituents]\n\n def on_end_of_algorithm(self):\n if not self.selection_done:\n raise AssertionError(\"Universe selection was not performed\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to use the OptionUniverseSelectionModel to select options contracts based on specified conditions.\nThe model is updated daily and selects different options based on the current date.\nThe algorithm ensures that only valid option contracts are selected for the universe.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AddOptionUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2014, 6, 5)\n self.set_end_date(2014, 6, 6)\n self.option_count = 0\n \n self.universe_settings.resolution = Resolution.MINUTE\n self.set_universe_selection(OptionUniverseSelectionModel(\n timedelta(days=1),\n self.select_option_chain_symbols\n ))\n \n def select_option_chain_symbols(self, utc_time):\n new_york_time = Extensions.convert_from_utc(utc_time, TimeZones.NEW_YORK)\n if new_york_time.date() < datetime(2014, 6, 6).date():\n return [ Symbol.create(\"TWX\", SecurityType.OPTION, Market.USA) ]\n \n if new_york_time.date() >= datetime(2014, 6, 6).date():\n return [ Symbol.create(\"AAPL\", SecurityType.OPTION, Market.USA) ]\n\n def on_securities_changed(self, changes):\n if len(changes.added_securities) > 0:\n for security in changes.added_securities:\n symbol = security.symbol.underlying if security.symbol.underlying else security.Symbol\n if symbol.value != \"AAPL\" and symbol.value != \"TWX\":\n raise RegressionTestException(f\"Unexpected security {security.Symbol}\")\n \n if security.symbol.security_type == SecurityType.OPTION:\n self.option_count += 1\n\n def on_end_of_algorithm(self):\n if len(self.active_securities) == 0:\n raise RegressionTestException(\"No active securities found. Expected at least one active security\")\n if self.option_count == 0:\n raise RegressionTestException(\"The option count should be greater than 0\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Abstract regression framework algorithm for multiple framework regression tests", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BaseFrameworkRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2014, 6, 1)\n self.set_end_date(2014, 6, 30)\n\n self.universe_settings.resolution = Resolution.HOUR\n self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW\n\n symbols = [Symbol.create(ticker, SecurityType.EQUITY, Market.USA)\n for ticker in [\"AAPL\", \"AIG\", \"BAC\", \"SPY\"]]\n\n # Manually add AAPL and AIG when the algorithm starts\n self.set_universe_selection(ManualUniverseSelectionModel(symbols[:2]))\n\n # At midnight, add all securities every day except on the last data\n # With this procedure, the Alpha Model will experience multiple universe changes\n self.add_universe_selection(ScheduledUniverseSelectionModel(\n self.date_rules.every_day(), self.time_rules.midnight,\n lambda dt: symbols if dt < self.end_date - timedelta(1) else []))\n\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(31), 0.025, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(NullRiskManagementModel())\n\n def on_end_of_algorithm(self):\n # The base implementation checks for active insights\n insights_count = len(self.insights.get_insights(lambda insight: insight.is_active(self.utc_time)))\n if insights_count != 0:\n raise AssertionError(f\"The number of active insights should be 0. Actual: {insights_count}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Shows how to set a custom benchmark for you algorithms", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomBenchmarkAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\", Resolution.SECOND)\n \n # Disabling the benchmark / setting to a fixed value \n # self.set_benchmark(lambda x: 0)\n \n # Set the benchmark to AAPL US Equity\n self.set_benchmark(Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA))\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n self.debug(\"Purchased Stock\")\n\n tuple_result = SymbolCache.try_get_symbol(\"AAPL\", None)\n if tuple_result[0]:\n raise AssertionError(\"Benchmark Symbol is not expected to be added to the Symbol cache\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting the behavior of specifying a null position group allowing us to fill orders which would be invalid if not", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass NullMarginMultipleOrdersRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n self.set_cash(10000)\n\n # override security position group model\n self.portfolio.set_positions(SecurityPositionGroupModel.NULL)\n # override margin requirements\n self.set_security_initializer(lambda security: security.set_buying_power_model(ConstantBuyingPowerModel(1)))\n\n equity = self.add_equity(\"GOOG\", leverage=4, fill_forward=True)\n option = self.add_option(equity.symbol, fill_forward=True)\n self._option_symbol = option.symbol\n\n option.set_filter(lambda u: u.strikes(-2, +2).expiration(0, 180))\n\n def on_data(self, data: Slice):\n if not self.portfolio.invested:\n if self.is_market_open(self._option_symbol):\n chain = data.option_chains.get(self._option_symbol)\n if chain:\n call_contracts = [contract for contract in chain if contract.right == OptionRight.CALL]\n call_contracts.sort(key=lambda x: (x.expiry, 1/ x.strike), reverse=True)\n\n option_contract = call_contracts[0]\n self.market_order(option_contract.symbol.underlying, 1000)\n self.market_order(option_contract.symbol, -10)\n\n if self.portfolio.total_margin_used != 1010:\n raise ValueError(f\"Unexpected margin used {self.portfolio.total_margin_used}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of using custom buying power model in backtesting.\nQuantConnect allows you to model all orders as deeply and accurately as you need.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomBuyingPowerModelAlgorithm(QCAlgorithm):\n '''Demonstration of using custom buying power model in backtesting.\n QuantConnect allows you to model all orders as deeply and accurately as you need.'''\n\n def initialize(self):\n self.set_start_date(2013,10,1) # Set Start Date\n self.set_end_date(2013,10,31) # Set End Date\n security = self.add_equity(\"SPY\", Resolution.HOUR)\n self.spy = security.symbol\n\n # set the buying power model\n security.set_buying_power_model(CustomBuyingPowerModel())\n\n def on_data(self, slice):\n if self.portfolio.invested:\n return\n\n quantity = self.calculate_order_quantity(self.spy, 1)\n if quantity % 100 != 0:\n raise AssertionError(f'CustomBuyingPowerModel only allow quantity that is multiple of 100 and {quantity} was found')\n\n # We normally get insufficient buying power model, but the\n # CustomBuyingPowerModel always says that there is sufficient buying power for the orders\n self.market_order(self.spy, quantity * 10)\n\n\nclass CustomBuyingPowerModel(BuyingPowerModel):\n def get_maximum_order_quantity_for_target_buying_power(self, parameters):\n quantity = super().get_maximum_order_quantity_for_target_buying_power(parameters).quantity\n quantity = np.floor(quantity / 100) * 100\n return GetMaximumOrderQuantityResult(quantity)\n\n def has_sufficient_buying_power_for_order(self, parameters):\n return HasSufficientBuyingPowerForOrderResult(True)\n\n # Let's always return 0 as the maintenance margin so we avoid margin call orders\n def get_maintenance_margin(self, parameters):\n return MaintenanceMargin(0)\n\n # Override this as well because the base implementation calls GetMaintenanceMargin (overridden)\n # because in C# it wouldn't resolve the overridden Python method\n def get_reserved_buying_power_for_position(self, parameters):\n return parameters.result_in_account_currency(0)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration algorithm for the Warm Up feature with basic indicators.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass WarmupAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10,8) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\", Resolution.SECOND)\n\n fast_period = 60\n slow_period = 3600\n\n self.fast = self.ema(\"SPY\", fast_period)\n self.slow = self.ema(\"SPY\", slow_period)\n\n self.set_warmup(slow_period)\n self.first = True\n\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n if self.first and not self.is_warming_up:\n self.first = False\n self.log(\"Fast: {0}\".format(self.fast.samples))\n self.log(\"Slow: {0}\".format(self.slow.samples))\n\n if self.fast.current.value > self.slow.current.value:\n self.set_holdings(\"SPY\", 1)\n else:\n self.set_holdings(\"SPY\", -1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression test tests for the loading of futures options contracts with a contract month of 2020-03 can live\nand be loaded from the same ZIP file that the 2020-04 contract month Future Option contract lives in.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.expected_symbols = {\n self._create_option(datetime(2020, 3, 26), OptionRight.CALL, 1650.0): False,\n self._create_option(datetime(2020, 3, 26), OptionRight.PUT, 1540.0): False,\n self._create_option(datetime(2020, 2, 25), OptionRight.CALL, 1600.0): False,\n self._create_option(datetime(2020, 2, 25), OptionRight.PUT, 1545.0): False\n }\n \n # Required for FOPs to use extended hours, until GH #6491 is addressed\n self.universe_settings.extended_market_hours = True\n\n self.set_start_date(2020, 1, 4)\n self.set_end_date(2020, 1, 6)\n\n gold_futures = self.add_future(\"GC\", Resolution.MINUTE, Market.COMEX, extended_market_hours=True)\n gold_futures.SetFilter(0, 365)\n\n self.add_future_option(gold_futures.Symbol)\n\n def on_data(self, data: Slice):\n for symbol in data.quote_bars.keys():\n # Check that we are in regular hours, we can place a market order (on extended hours, limit orders should be used)\n if symbol in self.expected_symbols and self.is_in_regular_hours(symbol):\n invested = self.expected_symbols[symbol]\n if not invested:\n self.market_order(symbol, 1)\n\n self.expected_symbols[symbol] = True\n\n def on_end_of_algorithm(self):\n not_encountered = [str(k) for k,v in self.expected_symbols.items() if not v]\n if any(not_encountered):\n raise AssertionError(f\"Expected all Symbols encountered and invested in, but the following were not found: {', '.join(not_encountered)}\")\n\n if not self.portfolio.invested:\n raise AssertionError(\"Expected holdings at the end of algorithm, but none were found.\")\n\n def is_in_regular_hours(self, symbol):\n return self.securities[symbol].exchange.exchange_open\n\n def _create_option(self, expiry: datetime, option_right: OptionRight, strike_price: float) -> Symbol:\n return Symbol.create_option(\n Symbol.create_future(\"GC\", Market.COMEX, datetime(2020, 4, 28)),\n Market.COMEX,\n OptionStyle.AMERICAN,\n option_right,\n strike_price,\n expiry\n )\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to use the FutureUniverseSelectionModel to select futures contracts for a given underlying asset.\nThe model is set to update daily, and the algorithm ensures that the selected contracts meet specific criteria.\nThis also includes a check to ensure that only future contracts are added to the algorithm's universe.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AddFutureUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013, 10, 8)\n self.set_end_date(2013, 10, 10)\n \n self.set_universe_selection(FutureUniverseSelectionModel(\n timedelta(days=1),\n lambda time: [ Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME) ]\n ))\n \n def on_securities_changed(self, changes):\n if len(changes.added_securities) > 0:\n for security in changes.added_securities:\n if security.symbol.security_type != SecurityType.FUTURE:\n raise RegressionTestException(f\"Expected future security, but found '{security.symbol.security_type}'\")\n if security.symbol.id.symbol != \"ES\":\n raise RegressionTestException(f\"Expected future symbol 'ES', but found '{security.symbol.id.symbol}'\")\n\n def on_end_of_algorithm(self):\n if len(self.active_securities) == 0:\n raise RegressionTestException(\"No active securities found. Expected at least one active security\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm asserts that futures have data at extended market hours when this is enabled.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureContractsExtendedMarketHoursRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013, 10, 6)\n self.set_end_date(2013, 10, 11)\n\n es_future_symbol = Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2013, 12, 20))\n self._es = self.add_future_contract(es_future_symbol, Resolution.HOUR, fill_forward=True, extended_market_hours=True)\n\n gc_future_symbol = Symbol.create_future(Futures.Metals.GOLD, Market.COMEX, datetime(2013, 10, 29))\n self._gc = self.add_future_contract(gc_future_symbol, Resolution.HOUR, fill_forward=True, extended_market_hours=False)\n\n self._es_ran_on_regular_hours = False\n self._es_ran_on_extended_hours = False\n self._gc_ran_on_regular_hours = False\n self._gc_ran_on_extended_hours = False\n\n def on_data(self, slice):\n slice_symbols = set(slice.keys())\n slice_symbols.update(slice.bars.keys())\n slice_symbols.update(slice.ticks.keys())\n slice_symbols.update(slice.quote_bars.keys())\n slice_symbols.update([x.canonical for x in slice_symbols])\n\n es_is_in_regular_hours = self._es.exchange.hours.is_open(self.time, False)\n es_is_in_extended_hours = not es_is_in_regular_hours and self._es.exchange.hours.is_open(self.time, True)\n slice_has_es_data = self._es.symbol in slice_symbols\n self._es_ran_on_regular_hours |= es_is_in_regular_hours and slice_has_es_data\n self._es_ran_on_extended_hours |= es_is_in_extended_hours and slice_has_es_data\n\n gc_is_in_regular_hours = self._gc.exchange.hours.is_open(self.time, False)\n gc_is_in_extended_hours = not gc_is_in_regular_hours and self._gc.exchange.hours.is_open(self.time, True)\n slice_has_gc_data = self._gc.symbol in slice_symbols\n self._gc_ran_on_regular_hours |= gc_is_in_regular_hours and slice_has_gc_data\n self._gc_ran_on_extended_hours |= gc_is_in_extended_hours and slice_has_gc_data\n\n def on_end_of_algorithm(self):\n if not self._es_ran_on_regular_hours:\n raise AssertionError(f\"Algorithm should have run on regular hours for {self._es.symbol} future, which enabled extended market hours\")\n\n if not self._es_ran_on_extended_hours:\n raise AssertionError(f\"Algorithm should have run on extended hours for {self._es.symbol} future, which enabled extended market hours\")\n\n if not self._gc_ran_on_regular_hours:\n raise AssertionError(f\"Algorithm should have run on regular hours for {self._gc.symbol} future, which did not enable extended market hours\")\n\n if self._gc_ran_on_extended_hours:\n raise AssertionError(f\"Algorithm should have not run on extended hours for {self._gc.symbol} future, which did not enable extended market hours\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting 'OnWarmupFinished' is being called", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OnWarmupFinishedRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 8) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self.add_equity(\"SPY\", Resolution.MINUTE)\n self.set_warmup(timedelta(days = 1))\n self._on_warmup_finished = 0\n \n def on_warmup_finished(self):\n self._on_warmup_finished += 1\n \n def on_end_of_algorithm(self):\n if self._on_warmup_finished != 1:\n raise AssertionError(f\"Unexpected OnWarmupFinished call count {self._on_warmup_finished}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm to demostrate the event handlers of Brokerage activities", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BrokerageActivityEventHandlingAlgorithm(QCAlgorithm):\n\n ### \n ### Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.\n ### \n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(100000)\n\n self.add_equity(\"SPY\", Resolution.MINUTE)\n\n ### \n ### on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n ### \n ### Slice object keyed by symbol containing the stock data\n def on_data(self, data):\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n\n ### \n ### Brokerage message event handler. This method is called for all types of brokerage messages.\n ### \n def on_brokerage_message(self, message_event):\n self.debug(f\"Brokerage meesage received - {message_event.to_string()}\")\n\n ### \n ### Brokerage disconnected event handler. This method is called when the brokerage connection is lost.\n ### \n def on_brokerage_disconnect(self):\n self.debug(f\"Brokerage disconnected!\")\n\n ### \n ### Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.\n ### \n def on_brokerage_reconnect(self):\n self.debug(f\"Brokerage reconnected!\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm demonstrates the runtime addition and removal of securities from your algorithm.\nWith LEAN it is possible to add and remove securities after the initialization.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AddRemoveSecurityRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\")\n\n self._last_action = None\n\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n if self._last_action is not None and self._last_action.date() == self.time.date():\n return\n\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", .5)\n self._last_action = self.time\n\n if self.time.weekday() == 1:\n self.add_equity(\"AIG\")\n self.add_equity(\"BAC\")\n self._last_action = self.time\n\n if self.time.weekday() == 2:\n self.set_holdings(\"AIG\", .25)\n self.set_holdings(\"BAC\", .25)\n self._last_action = self.time\n\n if self.time.weekday() == 3:\n self.remove_security(\"AIG\")\n self.remove_security(\"BAC\")\n self._last_action = self.time\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.SUBMITTED:\n self.debug(\"{0}: Submitted: {1}\".format(self.time, self.transactions.get_order_by_id(order_event.order_id)))\n if order_event.status == OrderStatus.FILLED:\n self.debug(\"{0}: Filled: {1}\".format(self.time, self.transactions.get_order_by_id(order_event.order_id)))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Simple indicator demonstration algorithm of MACD", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MACDTrendAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2004, 1, 1) #Set Start Date\n self.set_end_date(2015, 1, 1) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\", Resolution.DAILY)\n\n # define our daily macd(12,26) with a 9 day signal\n self.__macd = self.macd(\"SPY\", 12, 26, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY)\n self.__previous = datetime.min\n self.plot_indicator(\"MACD\", True, self.__macd, self.__macd.signal)\n self.plot_indicator(\"SPY\", self.__macd.fast, self.__macd.slow)\n\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n # wait for our macd to fully initialize\n if not self.__macd.is_ready: return\n\n # only once per day\n if self.__previous.date() == self.time.date(): return\n\n # define a small tolerance on our checks to avoid bouncing\n tolerance = 0.0025\n\n holdings = self.portfolio[\"SPY\"].quantity\n\n signal_delta_percent = (self.__macd.current.value - self.__macd.signal.current.value)/self.__macd.fast.current.value\n\n # if our macd is greater than our signal, then let's go long\n if holdings <= 0 and signal_delta_percent > tolerance: # 0.01%\n # longterm says buy as well\n self.set_holdings(\"SPY\", 1.0)\n\n # of our macd is less than our signal, then let's go short\n elif holdings >= 0 and signal_delta_percent < -tolerance:\n self.liquidate(\"SPY\")\n\n\n self.__previous = self.time\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example demonstrating how to access to options history for a given underlying equity security.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateOptionsHistoryAlgorithm(QCAlgorithm):\n ''' This example demonstrates how to get access to options history for a given underlying equity security.'''\n\n def initialize(self):\n # this test opens position in the first day of trading, lives through stock split (7 for 1), and closes adjusted position on the second day\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n self.set_cash(1000000)\n\n option = self.add_option(\"GOOG\")\n # add the initial contract filter \n # SetFilter method accepts timedelta objects or integer for days.\n # The following statements yield the same filtering criteria\n option.set_filter(-2, +2, 0, 180)\n # option.set_filter(-2,2, timedelta(0), timedelta(180))\n\n # set the pricing model for Greeks and volatility\n # find more pricing models https://www.quantconnect.com/lean/documentation/topic27704.html\n option.price_model = OptionPriceModels.crank_nicolson_fd()\n # set the warm-up period for the pricing model\n self.set_warm_up(TimeSpan.from_days(4))\n # set the benchmark to be the initial cash\n self.set_benchmark(lambda x: 1000000)\n\n def on_data(self,slice):\n if self.is_warming_up: return\n if not self.portfolio.invested:\n for chain in slice.option_chains:\n volatility = self.securities[chain.key.underlying].volatility_model.volatility\n for contract in chain.value:\n self.log(\"{0},Bid={1} Ask={2} Last={3} OI={4} sigma={5:.3f} NPV={6:.3f} \\\n delta={7:.3f} gamma={8:.3f} vega={9:.3f} beta={10:.2f} theta={11:.2f} IV={12:.2f}\".format(\n contract.symbol.value,\n contract.bid_price,\n contract.ask_price,\n contract.last_price,\n contract.open_interest,\n volatility,\n contract.theoretical_price,\n contract.greeks.delta,\n contract.greeks.gamma,\n contract.greeks.vega,\n contract.greeks.rho,\n contract.greeks.theta / 365,\n contract.implied_volatility))\n\n def on_securities_changed(self, changes):\n for change in changes.added_securities:\n # only print options price\n if change.symbol.value == \"GOOG\": return\n history = self.history(change.symbol, 10, Resolution.MINUTE).sort_index(level='time', ascending=False)[:3]\n for index, row in history.iterrows():\n self.log(\"History: \" + str(index[3])\n + \": \" + index[4].strftime(\"%m/%d/%Y %I:%M:%S %p\")\n + \" > \" + str(row.close))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm demonstrating the use of custom data sourced from the object store", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomDataObjectStoreRegressionAlgorithm(QCAlgorithm):\n custom_data = \"2017-08-18 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\\n2017-08-18 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\\n2017-08-18 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\\n2017-08-18 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\\n2017-08-18 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\\n2017-08-18 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\\n2017-08-18 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\\n2017-08-18 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\\n2017-08-18 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\\n2017-08-18 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-18 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\\n2017-08-18 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\\n2017-08-18 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\\n2017-08-18 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\\n2017-08-18 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\\n2017-08-18 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-18 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\\n2017-08-18 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\\n2017-08-18 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-18 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\\n2017-08-18 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\\n2017-08-18 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\\n2017-08-18 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57\\n2017-08-19 01:00:00,5771.75,5792.9,5738.6,5760.2,140394424,5894.04\\n2017-08-19 02:00:00,5709.35,5729.85,5683.1,5699.1,142041404,5462.45\\n2017-08-19 03:00:00,5748.95,5819.4,5739.4,5808.4,124410018,5121.33\\n2017-08-19 04:00:00,5820.4,5854.9,5770.25,5850.05,107160887,4560.84\\n2017-08-19 05:00:00,5841.9,5863.4,5804.3,5813.6,117541145,4591.91\\n2017-08-19 06:00:00,5805.75,5828.4,5777.9,5822.25,115539008,4643.17\\n2017-08-19 07:00:00,5754.15,5755,5645.65,5655.9,198400131,7148\\n2017-08-19 08:00:00,5639.9,5686.15,5616.85,5667.65,182410583,6697.18\\n2017-08-19 09:00:00,5638.05,5640,5566.25,5590.25,193488581,6308.88\\n2017-08-19 10:00:00,5606.95,5666.25,5570.25,5609.1,196571543,6792.49\\n2017-08-19 11:00:00,5627.95,5635.25,5579.35,5588.7,160095940,5939.3\\n2017-08-19 12:00:00,5647.95,5699.35,5630.95,5682.35,239029425,9184.29\\n2017-08-19 13:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\\n2017-08-19 14:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\\n2017-08-19 15:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\\n2017-08-19 16:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\\n2017-08-19 17:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\\n2017-08-19 18:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\\n2017-08-19 19:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\\n2017-08-19 20:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\\n2017-08-19 21:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\\n2017-08-19 22:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-19 23:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\\n2017-08-21 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\\n2017-08-21 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\\n2017-08-21 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\\n2017-08-21 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\\n2017-08-21 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\\n2017-08-21 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\\n2017-08-21 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\\n2017-08-21 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\\n2017-08-21 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\\n2017-08-21 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-21 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\\n2017-08-21 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\\n2017-08-21 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\\n2017-08-21 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\\n2017-08-21 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\\n2017-08-21 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-21 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\\n2017-08-21 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\\n2017-08-21 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\\n2017-08-21 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\\n2017-08-21 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\\n2017-08-21 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\\n2017-08-21 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57\"\n\n def initialize(self):\n self.set_start_date(2017, 8, 18)\n self.set_end_date(2017, 8, 21)\n self.set_cash(100000)\n\n self.set_benchmark(lambda x: 0)\n\n ExampleCustomData.custom_data_key = self.get_custom_data_key()\n\n self.custom_symbol = self.add_data(ExampleCustomData, \"ExampleCustomData\", Resolution.HOUR).symbol\n\n # Saving data here for demonstration and regression testing purposes.\n # In real scenarios, data has to be saved to the object store before the algorithm starts.\n self.save_data_to_object_store()\n\n self.received_data = []\n\n def on_data(self, slice: Slice):\n if slice.contains_key(self.custom_symbol):\n custom_data = slice.get(ExampleCustomData, self.custom_symbol)\n if custom_data.price == 0:\n raise AssertionError(\"Custom data price was not expected to be zero\")\n\n self.received_data.append(custom_data)\n\n def on_end_of_algorithm(self):\n if not self.received_data:\n raise AssertionError(\"Custom data was not fetched\")\n\n custom_security = self.securities[self.custom_symbol]\n if custom_security is None or custom_security.price == 0:\n raise AssertionError(\"Expected the custom security to be added to the algorithm securities and to have a price that is not zero\")\n\n # Make sure history requests work as expected\n history = self.history(ExampleCustomData, self.custom_symbol, self.start_date, self.end_date, Resolution.HOUR)\n\n if history.shape[0] != len(self.received_data):\n raise AssertionError(\"History request returned more or less data than expected\")\n\n for i in range(len(self.received_data)):\n received_data = self.received_data[i]\n if (history.index[i][0] != received_data.symbol or\n history.index[i][1] != received_data.time or\n history[[\"value\"]].values[i][0] != received_data.value or\n history[[\"open\"]].values[i][0] != received_data.open or\n history[[\"high\"]].values[i][0] != received_data.high or\n history[[\"low\"]].values[i][0] != received_data.low or\n history[[\"close\"]].values[i][0] != received_data.close):\n raise AssertionError(\"History request returned different data than expected\")\n\n def get_custom_data_key(self):\n return \"CustomData/ExampleCustomData\"\n\n def save_data_to_object_store(self):\n self.object_store.save(self.get_custom_data_key(), self.custom_data)\n\nclass ExampleCustomData(PythonData):\n custom_data_key = \"\"\n\n def get_source(self, config, date, is_live):\n return SubscriptionDataSource(self.custom_data_key, SubscriptionTransportMedium.OBJECT_STORE, FileFormat.CSV)\n\n def reader(self, config, line, date, is_live):\n data = line.split(',')\n obj_data = ExampleCustomData()\n obj_data.symbol = config.symbol\n obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S')\n obj_data.value = float(data[4])\n obj_data[\"Open\"] = float(data[1])\n obj_data[\"High\"] = float(data[2])\n obj_data[\"Low\"] = float(data[3])\n obj_data[\"Close\"] = float(data[4])\n return obj_data\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm showcases two margin related event handlers.\nOnMarginCallWarning: Fired when a portfolio's remaining margin dips below 5% of the total portfolio value\nOnMarginCall: Fired immediately before margin call orders are execued, this gives the algorithm a change to regain margin on its own through liquidation", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MarginCallEventsAlgorithm(QCAlgorithm):\n \"\"\"\n This algorithm showcases two margin related event handlers.\n on_margin_call_warning: Fired when a portfolio's remaining margin dips below 5% of the total portfolio value\n on_margin_call: Fired immediately before margin call orders are execued, this gives the algorithm a change to regain margin on its own through liquidation\n \"\"\"\n\n def initialize(self):\n self.set_cash(100000)\n self.set_start_date(2013,10,1)\n self.set_end_date(2013,12,11)\n self.add_equity(\"SPY\", Resolution.SECOND)\n # cranking up the leverage increases the odds of a margin call\n # when the security falls in value\n self.securities[\"SPY\"].set_leverage(100)\n\n def on_data(self, data):\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\",100)\n\n def on_margin_call(self, requests):\n # Margin call event handler. This method is called right before the margin call orders are placed in the market.\n # The orders to be executed to bring this algorithm within margin limits\n # this code gets called BEFORE the orders are placed, so we can try to liquidate some of our positions\n # before we get the margin call orders executed. We could also modify these orders by changing their quantities\n for order in requests:\n\n # liquidate an extra 10% each time we get a margin call to give us more padding\n new_quantity = int(order.quantity * 1.1)\n requests.remove(order)\n requests.append(SubmitOrderRequest(order.order_type, order.security_type, order.symbol, new_quantity, order.stop_price, order.limit_price, self.time, \"on_margin_call\"))\n\n return requests\n\n def on_margin_call_warning(self):\n # Margin call warning event handler.\n # This method is called when portfolio.margin_remaining is under 5% of your portfolio.total_portfolio_value\n # a chance to prevent a margin call from occurring\n\n spy_holdings = self.securities[\"SPY\"].holdings.quantity\n shares = int(-spy_holdings * 0.005)\n self.error(\"{0} - on_margin_call_warning(): Liquidating {1} shares of SPY to avoid margin call.\".format(self.time, shares))\n self.market_order(\"SPY\", shares)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm used to test a fine and coarse selection methods returning Universe.UNCHANGED", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass UniverseUnchangedRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.universe_settings.resolution = Resolution.DAILY\n\n # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.\n # Commented so regression algorithm is more sensitive\n #self.settings.minimum_order_margin_portfolio_percentage = 0.005\n self.set_start_date(2014,3,25)\n self.set_end_date(2014,4,7)\n\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(days = 1), 0.025, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n\n self.add_universe(self.coarse_selection_function, self.fine_selection_function)\n\n self.number_of_symbols_fine = 2\n\n def coarse_selection_function(self, coarse):\n # the first and second selection\n if self.time.date() <= date(2014, 3, 26):\n tickers = [ \"AAPL\", \"AIG\", \"IBM\" ]\n return [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers ]\n\n # will skip fine selection\n return Universe.UNCHANGED\n\n def fine_selection_function(self, fine):\n if self.time.date() == date(2014, 3, 25):\n sorted_by_pe_ratio = sorted(fine, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)\n return [ x.symbol for x in sorted_by_pe_ratio[:self.number_of_symbols_fine] ]\n\n # the second selection will return unchanged, in the following fine selection will be skipped\n return Universe.UNCHANGED\n\n # assert security changes, throw if called more than once\n def on_securities_changed(self, changes):\n added_symbols = [ x.symbol for x in changes.added_securities ]\n if (len(changes.added_securities) != 2\n or self.time.date() != date(2014, 3, 25)\n or Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA) not in added_symbols\n or Symbol.create(\"IBM\", SecurityType.EQUITY, Market.USA) not in added_symbols):\n raise ValueError(\"Unexpected security changes\")\n self.log(f\"OnSecuritiesChanged({self.time}):: {changes}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting the behavior of Universe.SELECTED collection", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass UniverseSelectedRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2014, 3, 25)\n self.set_end_date(2014, 3, 27)\n\n self.universe_settings.resolution = Resolution.DAILY\n\n self._universe = self.add_universe(self.selection_function)\n self.selection_count = 0\n\n def selection_function(self, fundamentals):\n sorted_by_dollar_volume = sorted(fundamentals, key=lambda x: x.dollar_volume, reverse=True)\n\n sorted_by_dollar_volume = sorted_by_dollar_volume[self.selection_count:]\n self.selection_count = self.selection_count + 1\n\n # return the symbol objects of the top entries from our sorted collection\n return [ x.symbol for x in sorted_by_dollar_volume[:self.selection_count] ]\n\n def on_data(self, data):\n if Symbol.create(\"TSLA\", SecurityType.EQUITY, Market.USA) in self._universe.selected:\n raise ValueError(f\"TSLA shouldn't of been selected\")\n\n self.buy(next(iter(self._universe.selected)), 1)\n\n def on_end_of_algorithm(self):\n if self.selection_count != 3:\n raise ValueError(f\"Unexpected selection count {self.selection_count}\")\n if self._universe.selected.count != 3 or self._universe.selected.count == self._universe.members.count:\n raise ValueError(f\"Unexpected universe selected count {self._universe.selected.count}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm reproducing data type bugs in the RegisterIndicator API. Related to GH 4205.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom CustomDataRegressionAlgorithm import Bitcoin\n\nclass RegisterIndicatorRegressionAlgorithm(QCAlgorithm):\n # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.\n def initialize(self):\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 1, 10)\n\n SP500 = Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME)\n self._symbol = _symbol = self.future_chain_provider.get_future_contract_list(SP500, (self.start_date + timedelta(days=1)))[0]\n self.add_future_contract(_symbol)\n\n # this collection will hold all indicators and at the end of the algorithm we will assert that all of them are ready\n self._indicators = []\n\n # this collection will be used to determine if the Selectors were called, we will assert so at the end of algorithm\n self._selector_called = [ False, False, False, False, False, False ]\n\n # First we will test that we can register our custom indicator using a QuoteBar consolidator\n indicator = CustomIndicator()\n consolidator = self.resolve_consolidator(_symbol, Resolution.MINUTE, QuoteBar)\n self.register_indicator(_symbol, indicator, consolidator)\n self._indicators.append(indicator)\n\n indicator2 = CustomIndicator()\n # We use the TimeDelta overload to fetch the consolidator\n consolidator = self.resolve_consolidator(_symbol, timedelta(minutes=1), QuoteBar)\n # We specify a custom selector to be used\n self.register_indicator(_symbol, indicator2, consolidator, lambda bar: self.set_selector_called(0) and bar)\n self._indicators.append(indicator2)\n\n # We use a IndicatorBase with QuoteBar data and a custom selector\n indicator3 = SimpleMovingAverage(10)\n consolidator = self.resolve_consolidator(_symbol, timedelta(minutes=1), QuoteBar)\n self.register_indicator(_symbol, indicator3, consolidator, lambda bar: self.set_selector_called(1) and (bar.ask.high - bar.bid.low))\n self._indicators.append(indicator3)\n\n # We test default consolidator resolution works correctly\n moving_average = SimpleMovingAverage(10)\n # Using Resolution, specifying custom selector and explicitly using TradeBar.volume\n self.register_indicator(_symbol, moving_average, Resolution.MINUTE, lambda bar: self.set_selector_called(2) and bar.volume)\n self._indicators.append(moving_average)\n\n moving_average2 = SimpleMovingAverage(10)\n # Using Resolution\n self.register_indicator(_symbol, moving_average2, Resolution.MINUTE)\n self._indicators.append(moving_average2)\n\n moving_average3 = SimpleMovingAverage(10)\n # Using timedelta\n self.register_indicator(_symbol, moving_average3, timedelta(minutes=1))\n self._indicators.append(moving_average3)\n\n moving_average4 = SimpleMovingAverage(10)\n # Using time_delta, specifying custom selector and explicitly using TradeBar.volume\n self.register_indicator(_symbol, moving_average4, timedelta(minutes=1), lambda bar: self.set_selector_called(3) and bar.volume)\n self._indicators.append(moving_average4)\n\n # Test custom data is able to register correctly and indicators updated\n symbol_custom = self.add_data(Bitcoin, \"BTC\", Resolution.MINUTE).symbol\n\n sma_custom_data = SimpleMovingAverage(1)\n self.register_indicator(symbol_custom, sma_custom_data, timedelta(minutes=1), lambda bar: self.set_selector_called(4) and bar.volume)\n self._indicators.append(sma_custom_data)\n\n sma_custom_data2 = SimpleMovingAverage(1)\n self.register_indicator(symbol_custom, sma_custom_data2, Resolution.MINUTE)\n self._indicators.append(sma_custom_data2)\n\n sma_custom_data3 = SimpleMovingAverage(1)\n consolidator = self.resolve_consolidator(symbol_custom, timedelta(minutes=1))\n self.register_indicator(symbol_custom, sma_custom_data3, consolidator, lambda bar: self.set_selector_called(5) and bar.volume)\n self._indicators.append(sma_custom_data3)\n\n def set_selector_called(self, position):\n self._selector_called[position] = True\n return True\n\n # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n def on_data(self, data):\n if not self.portfolio.invested:\n self.set_holdings(self._symbol, 0.5)\n\n def on_end_of_algorithm(self):\n if any(not was_called for was_called in self._selector_called):\n raise ValueError(\"All selectors should of been called\")\n if any(not indicator.is_ready for indicator in self._indicators):\n raise ValueError(\"All indicators should be ready\")\n self.log(f'Total of {len(self._indicators)} are ready')\n\nclass CustomIndicator(PythonIndicator):\n def __init__(self):\n super().__init__()\n self.name = \"Jose\"\n self.value = 0\n\n def update(self, input):\n self.value = input.ask.high\n return True\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Tests the delisting of the composite Symbol (ETF symbol) and the removal of\nthe universe and the symbol from the algorithm.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ETFConstituentUniverseCompositeDelistingRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2020, 12, 1)\n self.set_end_date(2021, 1, 31)\n self.set_cash(100000)\n\n self.universe_symbol_count = 0\n self.universe_selection_done = False\n self.universe_added = False\n self.universe_removed = False\n\n self.universe_settings.resolution = Resolution.HOUR\n self.delisting_date = date(2021, 1, 21)\n\n self.aapl = self.add_equity(\"AAPL\", Resolution.HOUR).symbol\n self.gdvd = self.add_equity(\"GDVD\", Resolution.HOUR).symbol\n\n self.add_universe(self.universe.etf(self.gdvd, self.universe_settings, self.filter_etfs))\n\n def filter_etfs(self, constituents):\n self.universe_selection_done = True\n\n if self.utc_time.date() > self.delisting_date:\n raise AssertionError(f\"Performing constituent universe selection on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')} after composite ETF has been delisted\")\n\n constituent_symbols = [i.symbol for i in constituents]\n self.universe_symbol_count = len(set(constituent_symbols))\n\n return constituent_symbols\n\n def on_data(self, data):\n if self.utc_time.date() > self.delisting_date and any([i != self.aapl for i in data.keys()]):\n raise AssertionError(\"Received unexpected slice in OnData(...) after universe was deselected\")\n\n if not self.portfolio.invested:\n self.set_holdings(self.aapl, 0.5)\n\n def on_securities_changed(self, changes):\n if len(changes.added_securities) != 0 and self.utc_time.date() > self.delisting_date:\n raise AssertionError(\"New securities added after ETF constituents were delisted\")\n\n # Since we added the etf subscription it will get delisted and send us a removal event\n expected_changes_count = self.universe_symbol_count + 1\n\n if self.universe_selection_done:\n # \"_universe_symbol_count + 1\" because selection is done right away,\n # so AddedSecurities includes all ETF constituents (including APPL) plus GDVD\n self.universe_added = self.universe_added or len(changes.added_securities) == expected_changes_count\n\n # TODO: shouldn't be sending AAPL as a removed security since it was added by another universe\n self.universe_removed = self.universe_removed or (\n len(changes.removed_securities) == expected_changes_count and\n self.utc_time.date() >= self.delisting_date and\n self.utc_time.date() < self.end_date.date())\n\n def on_end_of_algorithm(self):\n if not self.universe_added:\n raise AssertionError(\"ETF constituent universe was never added to the algorithm\")\n if not self.universe_removed:\n raise AssertionError(\"ETF constituent universe was not removed from the algorithm after delisting\")\n if len(self.active_securities) > 2:\n raise AssertionError(f\"Expected less than 2 securities after algorithm ended, found {len(self.securities)}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.\nThis test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.\n\nAll orders are sent from the brokerage, none of them will be placed by the algorithm.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomBrokerageSideOrderHandlingRegressionPartialAlgorithm(QCAlgorithm):\n '''Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.\n This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.\n\n All orders are sent from the brokerage, none of them will be placed by the algorithm.'''\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(100000)\n\n self.set_brokerage_message_handler(CustomBrokerageMessageHandler(self))\n\n self._spy = Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n\n def on_end_of_algorithm(self):\n # The security should have been added\n if not self.securities.contains_key(self._spy):\n raise AssertionError(\"Expected security to have been added\")\n\n if self.transactions.orders_count == 0:\n raise AssertionError(\"Expected orders to be added from brokerage side\")\n\n if len(list(self.portfolio.positions.groups)) != 1:\n raise AssertionError(\"Expected only one position\")\n\nclass CustomBrokerageMessageHandler(DefaultBrokerageMessageHandler):\n def __init__(self, algorithm):\n super().__init__(algorithm)\n self._algorithm = algorithm\n\n def handle_order(self, event_args):\n order = event_args.order\n if order.tag is None or not order.tag.isdigit():\n raise AssertionError(\"Expected all new brokerage-side orders to have a valid tag\")\n\n # We will only process orders with even tags\n return int(order.tag) % 2 == 0\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: In this algorithm we show how you can easily use the universe selection feature to fetch symbols\nto be traded using the BaseData custom data system in combination with the AddUniverse{T} method.\nAddUniverse{T} requires a function that will return the symbols to be traded.", "output": "```python\n\n\nfrom AlgorithmImports import *\nimport base64\n\nclass DropboxUniverseSelectionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n self.set_start_date(2017, 7, 4)\n self.set_end_date(2018, 7, 4)\n\n self._backtest_symbols_per_day = {}\n self._current_universe = []\n\n self.universe_settings.resolution = Resolution.DAILY\n\n # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.\n # Commented so regression algorithm is more sensitive\n #self.settings.minimum_order_margin_portfolio_percentage = 0.005\n\n self.add_universe(\"my-dropbox-universe\", self.selector)\n\n def selector(self, date: datetime) -> list[str]:\n # handle live mode file format\n if self.live_mode:\n # fetch the file from dropbox\n str = self.download(\"https://www.dropbox.com/s/2l73mu97gcehmh7/daily-stock-picker-live.csv?dl=1\")\n # if we have a file for today, return symbols, else leave universe unchanged\n self._current_universe = str.split(',') if len(str) > 0 else self._current_universe\n return self._current_universe\n\n # backtest - first cache the entire file\n if len(self._backtest_symbols_per_day) == 0:\n\n # No need for headers for authorization with dropbox, these two lines are for example purposes \n byte_key = base64.b64encode(\"UserName:Password\".encode('ASCII'))\n # The headers must be passed to the Download method as dictionary\n headers = { 'Authorization' : f'Basic ({byte_key.decode(\"ASCII\")})' }\n\n str = self.download(\"https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1\", headers)\n for line in str.splitlines():\n data = line.split(',')\n self._backtest_symbols_per_day[data[0]] = data[1:]\n\n index = date.strftime(\"%Y%m%d\")\n self._current_universe = self._backtest_symbols_per_day.get(index, self._current_universe)\n\n return self._current_universe\n\n def on_data(self, slice: Slice) -> None:\n if slice.bars.count == 0:\n return\n if not self._changes:\n return\n\n # start fresh\n self.liquidate()\n\n percentage = 1 / slice.bars.count\n for trade_bar in slice.bars.values():\n self.set_holdings(trade_bar.symbol, percentage)\n\n # reset changes\n self._changes = None\n\n def on_securities_changed(self, changes: SecurityChanges) -> None:\n self._changes = changes\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm showing how to implement a custom universe selection model and asserting it's behavior", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel\n\nclass CustomUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2014,3,24)\n self.set_end_date(2014,4,7)\n\n self.universe_settings.resolution = Resolution.DAILY\n self.set_universe_selection(MyCustomUniverseSelectionModel())\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n for kvp in self.active_securities:\n self.set_holdings(kvp.key, 0.1)\n\nclass MyCustomUniverseSelectionModel(FundamentalUniverseSelectionModel):\n\n def __init__(self, universe_settings = None):\n super().__init__(universe_settings)\n self._selected = False\n\n def select(self, algorithm, fundamental):\n if not self._selected:\n self._selected = True\n return [ Symbol.create('AAPL', SecurityType.EQUITY, Market.USA) ]\n return Universe.UNCHANGED\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting the behavior of the indicator history api", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndicatorHistoryRegressionAlgorithm(QCAlgorithm):\n '''Regression algorithm asserting the behavior of the indicator history api'''\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2013, 1, 1)\n self.set_end_date(2014, 12, 31)\n\n self._symbol = self.add_equity(\"SPY\", Resolution.DAILY).symbol\n\n def on_data(self, slice: Slice):\n self.bollinger_bands = BollingerBands(\"BB\", 20, 2.0, MovingAverageType.SIMPLE)\n\n if self.bollinger_bands.window.is_ready:\n raise ValueError(\"Unexpected ready bollinger bands state\")\n\n indicatorHistory = self.indicator_history(self.bollinger_bands, self._symbol, 50)\n \n self.debug(f\"indicatorHistory: {indicatorHistory}\")\n\n self.debug(f\"data_frame: {indicatorHistory.data_frame}\")\n\n if not self.bollinger_bands.window.is_ready:\n raise ValueError(\"Unexpected not ready bollinger bands state\")\n\n # we ask for 50 data points\n if indicatorHistory.count != 50:\n raise ValueError(f\"Unexpected indicators values {indicatorHistory.count}\")\n\n for indicatorDataPoints in indicatorHistory:\n middle_band = indicatorDataPoints[\"middle_band\"]\n self.debug(f\"BB @{indicatorDataPoints.current}: middle_band: {middle_band} upper_band: {indicatorDataPoints.upper_band}\")\n if indicatorDataPoints == 0:\n raise ValueError(f\"Unexpected indicators point {indicatorDataPoints}\")\n\n currentValues = indicatorHistory.current\n if len(currentValues) != 50 or len([x for x in currentValues if x.value == 0]) > 0:\n raise ValueError(f\"Unexpected indicators current values {len(currentValues)}\")\n upperBandPoints = indicatorHistory[\"upper_band\"]\n if len(upperBandPoints) != 50 or len([x for x in upperBandPoints if x.value == 0]) > 0:\n raise ValueError(f\"Unexpected indicators upperBandPoints values {len(upperBandPoints)}\")\n\n # We are done now!\n self.quit()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of how to use custom security properties.\nIn this algorithm we trade a security based on the values of a slow and fast EMAs which are stored in the security itself.", "output": "```python\n\n\nfrom cmath import isclose\nfrom AlgorithmImports import *\n\nclass SecurityCustomPropertiesAlgorithm(QCAlgorithm):\n '''Demonstration of how to use custom security properties.\n In this algorithm we trade a security based on the values of a slow and fast EMAs which are stored in the security itself.'''\n\n def initialize(self):\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n self.set_cash(100000)\n\n self.spy = self.add_equity(\"SPY\", Resolution.MINUTE)\n\n # Using the dynamic interface to store our indicator as a custom property.\n self.spy.slow_ema = self.ema(self.spy.symbol, 30, Resolution.MINUTE)\n\n # Using the generic interface to store our indicator as a custom property.\n self.spy.add(\"fast_ema\", self.ema(self.spy.symbol, 60, Resolution.MINUTE))\n\n # Using the indexer to store our indicator as a custom property\n self.spy[\"bb\"] = self.bb(self.spy.symbol, 20, 1, MovingAverageType.SIMPLE, Resolution.MINUTE)\n\n # Fee factor to be used by the custom fee model\n self.spy.fee_factor = 0.00002\n self.spy.set_fee_model(CustomFeeModel())\n\n # This property will be used to store the prices used to calculate the fees in order to assert the correct fee factor is used.\n self.spy.orders_fees_prices = {}\n\n def on_data(self, data):\n if not self.spy.fast_ema.is_ready:\n return\n\n if not self.portfolio.invested:\n # Using the property and the generic interface to access our indicator\n if self.spy.slow_ema > self.spy.fast_ema:\n self.set_holdings(self.spy.symbol, 1)\n else:\n if self.spy.get[ExponentialMovingAverage](\"slow_ema\") < self.spy.get[ExponentialMovingAverage](\"fast_ema\"):\n self.liquidate(self.spy.symbol)\n\n # Using the indexer to access our indicator\n bb: BollingerBands = self.spy[\"bb\"]\n self.plot(\"bb\", bb.upper_band, bb.middle_band, bb.lower_band)\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n fee = order_event.order_fee\n expected_fee = self.spy.orders_fees_prices[order_event.order_id] * order_event.absolute_fill_quantity * self.spy.fee_factor\n if not isclose(fee.value.amount, expected_fee, rel_tol=1e-15):\n raise AssertionError(f\"Custom fee model failed to set the correct fee. Expected: {expected_fee}. Actual: {fee.value.amount}\")\n\n def on_end_of_algorithm(self):\n if self.transactions.orders_count == 0:\n raise AssertionError(\"No orders executed\")\n\nclass CustomFeeModel(FeeModel):\n '''This custom fee is implemented for demonstration purposes only.'''\n\n def get_order_fee(self, parameters):\n security = parameters.security\n # custom fee math using the fee factor stored in security instance\n fee_factor = security.fee_factor\n if fee_factor is None:\n fee_factor = 0.00001\n\n # Store the price used to calculate the fee for this order\n security[\"orders_fees_prices\"][parameters.order.id] = security.price\n\n fee = max(1.0, security.price * parameters.order.absolute_quantity * fee_factor)\n\n return OrderFee(CashAmount(fee, \"USD\"))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting that using separate coarse & fine selection with async universe settings is not allowed", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CoarseFineAsyncUniverseRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n\n self.universe_settings.asynchronous = True\n\n threw_exception = False\n try:\n self.add_universe(self.coarse_selection_function, self.fine_selection_function)\n except:\n # expected\n threw_exception = True\n pass\n\n if not threw_exception:\n raise ValueError(\"Expected exception to be thrown for AddUniverse\")\n\n self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.coarse_selection_function, self.fine_selection_function))\n\n def coarse_selection_function(self, coarse):\n return []\n\n def fine_selection_function(self, fine):\n return []\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Base regression algorithm exercising different style options with option price models that might\nor might not support them. Also, if the option style is supported, greeks are asserted to be accesible and have valid values.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionPriceModelForOptionStylesBaseRegressionAlgorithm(QCAlgorithm):\n def __init__(self) -> None:\n super().__init__()\n self._option_style_is_supported = False\n self._check_greeks = True\n self._tried_greeks_calculation = False\n self._option = None\n\n def on_data(self, slice: Slice) -> None:\n if self.is_warming_up:\n return\n\n for kvp in slice.option_chains:\n if not self._option or kvp.key != self._option.symbol:\n continue\n\n self.check_greeks([contract for contract in kvp.value])\n\n def on_end_of_day(self, symbol: Symbol) -> None:\n self._check_greeks = True\n\n def on_end_of_algorithm(self) -> None:\n if not self._tried_greeks_calculation:\n raise AssertionError(\"Expected greeks to be accessed\")\n\n def init(self, option: Option, option_style_is_supported: bool) -> None:\n self._option = option\n self._option_style_is_supported = option_style_is_supported\n self._check_greeks = True\n self._tried_greeks_calculation = False\n\n def check_greeks(self, contracts: list[OptionContract]) -> None:\n if not self._check_greeks or len(contracts) == 0 or not self._option:\n return\n\n self._check_greeks = False\n self._tried_greeks_calculation = True\n\n for contract in contracts:\n greeks = None\n try:\n greeks = contract.greeks\n\n # Greeks should have not been successfully accessed if the option style is not supported\n option_style_str = 'American' if self._option.style == OptionStyle.AMERICAN else 'European'\n if not self._option_style_is_supported:\n raise AssertionError(f'Expected greeks not to be calculated for {contract.symbol.value}, an {option_style_str} style option, using {type(self._option.price_model).__name__}, which does not support them, but they were')\n except ArgumentException:\n # ArgumentException is only expected if the option style is not supported\n if self._option_style_is_supported:\n raise AssertionError(f'Expected greeks to be calculated for {contract.symbol.value}, an {option_style_str} style option, using {type(self._option.price_model).__name__}, which supports them, but they were not')\n\n # Greeks should be valid if they were successfuly accessed for supported option style\n # Delta can be {-1, 0, 1} if the price is too wild, rho can be 0 if risk free rate is 0\n # Vega can be 0 if the price is very off from theoretical price, Gamma = 0 if Delta belongs to {-1, 1}\n if (self._option_style_is_supported\n and (not greeks\n or ((contract.right == OptionRight.CALL and (greeks.delta < 0.0 or greeks.delta > 1.0 or greeks.rho < 0.0))\n or (contract.right == OptionRight.PUT and (greeks.delta < -1.0 or greeks.delta > 0.0 or greeks.rho > 0.0))\n or greeks.theta == 0.0 or greeks.vega < 0.0 or greeks.gamma < 0.0))):\n raise AssertionError(f'Expected greeks to have valid values. Greeks were: Delta: {greeks.delta}, Rho: {greeks.rho}, Theta: {greeks.theta}, Vega: {greeks.vega}, Gamma: {greeks.gamma}')\n\n\n\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests that we only receive the option chain for a single future contract\nin the option universe filter.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.invested = False\n self.on_data_reached = False\n self.option_filter_ran = False\n self.symbols_received = []\n self.expected_symbols_received = []\n self.data_received = {}\n\n self.set_start_date(2020, 1, 4)\n self.set_end_date(2020, 1, 8)\n\n self.es = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, Market.CME)\n self.es.set_filter(lambda future_filter: future_filter.expiration(0, 365).expiration_cycle([3, 6]))\n\n self.add_future_option(self.es.symbol, self.option_contract_universe_filter_function)\n\n def option_contract_universe_filter_function(self, option_contracts: OptionFilterUniverse) -> OptionFilterUniverse:\n self.option_filter_ran = True\n\n expiry_dates = list(set([x.symbol.underlying.id.date for x in option_contracts]))\n expiry = None if not any(expiry_dates) else expiry_dates[0]\n\n symbols = [x.symbol.underlying for x in option_contracts]\n symbol = None if not any(symbols) else symbols[0]\n\n if expiry is None or symbol is None:\n raise AssertionError(\"Expected a single Option contract in the chain, found 0 contracts\")\n\n self.expected_symbols_received.extend([x.symbol for x in option_contracts])\n\n return option_contracts\n\n def on_data(self, data: Slice):\n if not data.has_data:\n return\n\n self.on_data_reached = True\n has_option_quote_bars = False\n\n for qb in data.quote_bars.values():\n if qb.symbol.security_type != SecurityType.FUTURE_OPTION:\n continue\n\n has_option_quote_bars = True\n\n self.symbols_received.append(qb.symbol)\n if qb.symbol not in self.data_received:\n self.data_received[qb.symbol] = []\n\n self.data_received[qb.symbol].append(qb)\n\n if self.invested or not has_option_quote_bars:\n return\n\n for chain in sorted(data.option_chains.values(), key=lambda chain: chain.symbol.underlying.id.date):\n future_invested = False\n option_invested = False\n\n for option in chain.contracts.keys():\n if future_invested and option_invested:\n return\n\n future = option.underlying\n\n if not option_invested and data.contains_key(option):\n self.market_order(option, 1)\n self.invested = True\n option_invested = True\n\n if not future_invested and data.contains_key(future):\n self.market_order(future, 1)\n self.invested = True\n future_invested = True\n\n def on_end_of_algorithm(self):\n super().on_end_of_algorithm()\n self.symbols_received = list(set(self.symbols_received))\n self.expected_symbols_received = list(set(self.expected_symbols_received))\n\n if not self.option_filter_ran:\n raise AssertionError(\"Option chain filter was never ran\")\n if not self.on_data_reached:\n raise AssertionError(\"OnData() was never called.\")\n if len(self.symbols_received) != len(self.expected_symbols_received):\n raise AssertionError(f\"Expected {len(self.expected_symbols_received)} option contracts Symbols, found {len(self.symbols_received)}\")\n\n missing_symbols = [expected_symbol for expected_symbol in self.expected_symbols_received if expected_symbol not in self.symbols_received]\n if any(missing_symbols):\n raise AssertionError(f'Symbols: \"{\", \".join(missing_symbols)}\" were not found in OnData')\n\n for expected_symbol in self.expected_symbols_received:\n data = self.data_received[expected_symbol]\n for data_point in data:\n data_point.end_time = datetime(1970, 1, 1)\n\n non_dupe_data_count = len(set(data))\n if non_dupe_data_count < 1000:\n raise AssertionError(f\"Received too few data points. Expected >=1000, found {non_dupe_data_count} for {expected_symbol}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to assert the behavior of .", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm\nfrom Alphas.MacdAlphaModel import MacdAlphaModel\n\nclass MacdAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):\n\n def initialize(self):\n super().initialize()\n self.set_alpha(MacdAlphaModel())\n\n def on_end_of_algorithm(self):\n expected = 4\n if self.insights.total_count != expected:\n raise AssertionError(f\"The total number of insights should be {expected}. Actual: {self.insights.total_count}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Tests that orders are denied if they exceed the max shortable quantity.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass RegressionTestShortableProvider(LocalDiskShortableProvider):\n def __init__(self):\n super().__init__(\"testbrokerage\")\n\nclass ShortableProviderOrdersRejectedRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.orders_allowed = []\n self.orders_denied = []\n self.initialized = False\n self.invalidated_allowed_order = False\n self.invalidated_new_order_with_portfolio_holdings = False\n\n self.set_start_date(2013, 10, 4)\n self.set_end_date(2013, 10, 11)\n self.set_cash(10000000)\n\n self.spy = self.add_equity(\"SPY\", Resolution.MINUTE)\n self.aig = self.add_equity(\"AIG\", Resolution.MINUTE)\n\n self.spy.set_shortable_provider(RegressionTestShortableProvider())\n self.aig.set_shortable_provider(RegressionTestShortableProvider())\n\n def on_data(self, data):\n if not self.initialized:\n self.handle_order(self.limit_order(self.spy.symbol, -1001, 10000)) # Should be canceled, exceeds the max shortable quantity\n order_ticket = self.limit_order(self.spy.symbol, -1000, 10000)\n self.handle_order(order_ticket) # Allowed, orders at or below 1000 should be accepted\n self.handle_order(self.limit_order(self.spy.symbol, -10, 0.01)) # Should be canceled, the total quantity we would be short would exceed the max shortable quantity.\n\n response = order_ticket.update_quantity(-999) # should be allowed, we are reducing the quantity we want to short\n if not response.is_success:\n raise ValueError(\"Order update should of succeeded!\")\n\n self.initialized = True\n return\n\n if not self.invalidated_allowed_order:\n if len(self.orders_allowed) != 1:\n raise AssertionError(f\"Expected 1 successful order, found: {len(self.orders_allowed)}\")\n if len(self.orders_denied) != 2:\n raise AssertionError(f\"Expected 2 failed orders, found: {len(self.orders_denied)}\")\n\n allowed_order = self.orders_allowed[0]\n order_update = UpdateOrderFields()\n order_update.limit_price = 0.01\n order_update.quantity = -1001\n order_update.tag = \"Testing updating and exceeding maximum quantity\"\n\n response = allowed_order.update(order_update)\n if response.error_code != OrderResponseErrorCode.EXCEEDS_SHORTABLE_QUANTITY:\n raise AssertionError(f\"Expected order to fail due to exceeded shortable quantity, found: {response.error_code}\")\n\n cancel_response = allowed_order.cancel()\n if cancel_response.is_error:\n raise AssertionError(\"Expected to be able to cancel open order after bad qty update\")\n\n self.invalidated_allowed_order = True\n self.orders_denied.clear()\n self.orders_allowed.clear()\n return\n\n if not self.invalidated_new_order_with_portfolio_holdings:\n self.handle_order(self.market_order(self.spy.symbol, -1000)) # Should succeed, no holdings and no open orders to stop this\n spy_shares = self.portfolio[self.spy.symbol].quantity\n if spy_shares != -1000:\n raise AssertionError(f\"Expected -1000 shares in portfolio, found: {spy_shares}\")\n\n self.handle_order(self.limit_order(self.spy.symbol, -1, 0.01)) # Should fail, portfolio holdings are at the max shortable quantity.\n if len(self.orders_denied) != 1:\n raise AssertionError(f\"Expected limit order to fail due to existing holdings, but found {len(self.orders_denied)} failures\")\n\n self.orders_allowed.clear()\n self.orders_denied.clear()\n\n self.handle_order(self.market_order(self.aig.symbol, -1001))\n if len(self.orders_allowed) != 1:\n raise AssertionError(f\"Expected market order of -1001 BAC to not fail\")\n\n self.invalidated_new_order_with_portfolio_holdings = True\n\n def handle_order(self, order_ticket):\n if order_ticket.submit_request.status == OrderRequestStatus.ERROR:\n self.orders_denied.append(order_ticket)\n return\n\n self.orders_allowed.append(order_ticket)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests using FutureOptions daily resolution", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionHourlyRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 1, 7)\n self.set_end_date(2020, 1, 8)\n resolution = Resolution.HOUR\n\n # Add our underlying future contract\n self.es = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 3, 20)\n ),\n resolution).symbol\n\n # Attempt to fetch a specific ITM future option contract\n es_options = [\n self.add_future_option_contract(x, resolution).symbol for x in (self.option_chain_provider.get_option_contract_list(self.es, self.time)) if x.id.strike_price == 3200 and x.id.option_right == OptionRight.CALL\n ]\n self.es_option = es_options[0]\n\n # Validate it is the expected contract\n expected_contract = Symbol.create_option(self.es, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200, datetime(2020, 3, 20))\n if self.es_option != expected_contract:\n raise AssertionError(f\"Contract {self.es_option} was not the expected contract {expected_contract}\")\n\n # Schedule a purchase of this contract at noon\n self.schedule.on(self.date_rules.today, self.time_rules.noon, self.schedule_callback_buy)\n\n # Schedule liquidation at 2pm when the market is open\n self.schedule.on(self.date_rules.today, self.time_rules.at(17,0,0), self.schedule_callback_liquidate)\n\n def schedule_callback_buy(self):\n self.ticket = self.market_order(self.es_option, 1)\n\n def on_data(self, slice):\n # Assert we are only getting data at 7PM (12AM UTC)\n if slice.time.minute != 0:\n raise AssertionError(f\"Expected data only on hourly intervals; instead was {slice.time}\")\n\n def schedule_callback_liquidate(self):\n self.liquidate()\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}\")\n\n if self.ticket.status != OrderStatus.FILLED:\n raise AssertionError(\"Future option order failed to fill correctly\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Universe Selection regression algorithm simulates an edge case. In one week, Google listed two new symbols, delisted one of them and changed tickers.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass UniverseSelectionRegressionAlgorithm(QCAlgorithm):\n \n def initialize(self):\n \n self.set_start_date(2014,3,22) #Set Start Date\n self.set_end_date(2014,4,7) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n # security that exists with no mappings\n self.add_equity(\"SPY\", Resolution.DAILY)\n # security that doesn't exist until half way in backtest (comes in as GOOCV)\n self.add_equity(\"GOOG\", Resolution.DAILY)\n\n self.universe_settings.resolution = Resolution.DAILY\n self.add_universe(self.coarse_selection_function)\n\n self.delisted_symbols = []\n self.changes = None\n\n\n def coarse_selection_function(self, coarse):\n return [ c.symbol for c in coarse if c.symbol.value == \"GOOG\" or c.symbol.value == \"GOOCV\" or c.symbol.value == \"GOOAV\" or c.symbol.value == \"GOOGL\" ]\n\n\n def on_data(self, data):\n if self.transactions.orders_count == 0:\n self.market_order(\"SPY\", 100)\n\n for kvp in data.delistings:\n self.delisted_symbols.append(kvp.key)\n \n if self.changes is None:\n return\n\n if not all(data.bars.contains_key(x.symbol) for x in self.changes.added_securities):\n return \n \n for security in self.changes.added_securities:\n self.log(\"{0}: Added Security: {1}\".format(self.time, security.symbol))\n self.market_on_open_order(security.symbol, 100)\n\n for security in self.changes.removed_securities:\n self.log(\"{0}: Removed Security: {1}\".format(self.time, security.symbol))\n if security.symbol not in self.delisted_symbols:\n self.log(\"Not in delisted: {0}:\".format(security.symbol))\n self.market_on_open_order(security.symbol, -100)\n\n self.changes = None \n\n\n def on_securities_changed(self, changes):\n self.changes = changes\n\n\n def on_order_event(self, orderEvent):\n if orderEvent.status == OrderStatus.SUBMITTED:\n self.log(\"{0}: Submitted: {1}\".format(self.time, self.transactions.get_order_by_id(orderEvent.order_id)))\n if orderEvent.status == OrderStatus.FILLED:\n self.log(\"{0}: Filled: {1}\".format(self.time, self.transactions.get_order_by_id(orderEvent.order_id)))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of using the ETFConstituentsUniverseSelectionModel with simple ticker", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Selection.ETFConstituentsUniverseSelectionModel import *\nfrom ETFConstituentsFrameworkAlgorithm import ETFConstituentsFrameworkAlgorithm\n\nclass ETFConstituentsFrameworkWithDifferentSelectionModelAlgorithm(ETFConstituentsFrameworkAlgorithm):\n\n def initialize(self):\n super().initialize()\n \n self.set_universe_selection(ETFConstituentsUniverseSelectionModel(\"SPY\", self.universe_settings, self.etf_constituents_filter))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm showing and asserting the usage of the \"ShortMarginInterestRateModel\"\npaired with a \"IShortableProvider\" instance, for example \"InteractiveBrokersShortableProvider\"", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ShortInterestFeeRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n\n self._short = self.add_equity(\"SPY\", Resolution.HOUR)\n self._long = self.add_equity(\"AAPL\", Resolution.HOUR)\n\n for security in [ self._short, self._long]:\n security.set_shortable_provider(LocalDiskShortableProvider(\"testbrokerage\"))\n security.margin_interest_rate_model = ShortMarginInterestRateModel()\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", -0.5)\n self.set_holdings(\"AAPL\", 0.5)\n\n def on_end_of_algorithm(self):\n if self._short.margin_interest_rate_model.amount >= 0:\n raise RegressionTestException(\"Expected short fee interest rate to be charged\")\n\n if self._long.margin_interest_rate_model.amount <= 0:\n raise RegressionTestException(\"Expected short fee interest rate to be earned\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This is an option split regression algorithm", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionRenameRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n\n self.set_cash(1000000)\n self.set_start_date(2013,6,28)\n self.set_end_date(2013,7,2)\n option = self.add_option(\"TFCFA\")\n\n # set our strike/expiry filter for this option chain\n option.set_filter(-1, 1, timedelta(0), timedelta(3650))\n # use the underlying equity as the benchmark\n self.set_benchmark(\"TFCFA\")\n\n def on_data(self, slice):\n ''' Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event\n The current slice of data keyed by symbol string '''\n if not self.portfolio.invested: \n for kvp in slice.option_chains:\n chain = kvp.value\n if self.time.day == 28 and self.time.hour > 9 and self.time.minute > 0:\n \n contracts = [i for i in sorted(chain, key=lambda x:x.expiry) \n if i.right == OptionRight.CALL and \n i.strike == 33 and\n i.expiry.date() == datetime(2013,8,17).date()]\n if contracts:\n # Buying option\n contract = contracts[0]\n self.buy(contract.symbol, 1)\n # Buy the undelying stock\n underlying_symbol = contract.symbol.underlying\n self.buy (underlying_symbol, 100)\n # check\n if float(contract.ask_price) != 1.1:\n raise ValueError(\"Regression test failed: current ask price was not loaded from NWSA backtest file and is not $1.1\")\n elif self.time.day == 2 and self.time.hour > 14 and self.time.minute > 0:\n for kvp in slice.option_chains:\n chain = kvp.value\n self.liquidate()\n contracts = [i for i in sorted(chain, key=lambda x:x.expiry) \n if i.right == OptionRight.CALL and \n i.strike == 33 and\n i.expiry.date() == datetime(2013,8,17).date()]\n if contracts:\n contract = contracts[0]\n self.log(\"Bid Price\" + str(contract.bid_price))\n if float(contract.bid_price) != 0.05:\n raise ValueError(\"Regression test failed: current bid price was not loaded from FOXA file and is not $0.05\")\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Tests the delisting of the composite Symbol (ETF symbol) and the removal of\nthe universe and the symbol from the algorithm, without adding a subscription via AddEquity", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2020, 12, 1)\n self.set_end_date(2021, 1, 31)\n self.set_cash(100000)\n\n self.universe_symbol_count = 0\n self.universe_selection_done = False\n self.universe_added = False\n self.universe_removed = False\n\n self.universe_settings.resolution = Resolution.HOUR\n self.delisting_date = date(2021, 1, 21)\n\n self.aapl = self.add_equity(\"AAPL\", Resolution.HOUR).symbol\n self.gdvd = Symbol.create(\"GDVD\", SecurityType.EQUITY, Market.USA)\n\n self.add_universe(self.universe.etf(self.gdvd, self.universe_settings, self.filter_etfs))\n\n def filter_etfs(self, constituents):\n self.universe_selection_done = True\n\n if self.utc_time.date() > self.delisting_date:\n raise AssertionError(f\"Performing constituent universe selection on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')} after composite ETF has been delisted\")\n\n constituent_symbols = [i.symbol for i in constituents]\n self.universe_symbol_count = len(set(constituent_symbols))\n\n return constituent_symbols\n\n def on_data(self, data):\n if self.utc_time.date() > self.delisting_date and any([i != self.aapl for i in data.keys()]):\n raise AssertionError(\"Received unexpected slice in OnData(...) after universe was deselected\")\n\n if not self.portfolio.invested:\n self.set_holdings(self.aapl, 0.5)\n\n def on_securities_changed(self, changes):\n if len(changes.added_securities) != 0 and self.utc_time.date() > self.delisting_date:\n raise AssertionError(\"New securities added after ETF constituents were delisted\")\n\n if self.universe_selection_done:\n self.universe_added = self.universe_added or len(changes.added_securities) == self.universe_symbol_count\n\n # TODO: shouldn't be sending AAPL as a removed security since it was added by another universe\n self.universe_removed = self.universe_removed or (\n len(changes.removed_securities) == self.universe_symbol_count and\n self.utc_time.date() >= self.delisting_date and\n self.utc_time.date() < self.end_date.date())\n\n def on_end_of_algorithm(self):\n if not self.universe_added:\n raise AssertionError(\"ETF constituent universe was never added to the algorithm\")\n if not self.universe_removed:\n raise AssertionError(\"ETF constituent universe was not removed from the algorithm after delisting\")\n if len(self.active_securities) > 2:\n raise AssertionError(f\"Expected less than 2 securities after algorithm ended, found {len(self.securities)}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to add options for a given underlying equity security.\nIt also shows how you can prefilter contracts easily based on strikes and expirations.\nIt also shows how you can inspect the option chain to pick a specific option contract to trade.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateOptionsFilterUniverseAlgorithm(QCAlgorithm):\n underlying_ticker = \"GOOG\"\n\n def initialize(self):\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 28)\n self.set_cash(100000)\n\n equity = self.add_equity(self.underlying_ticker)\n option = self.add_option(self.underlying_ticker)\n self.option_symbol = option.symbol\n\n # Set our custom universe filter\n option.set_filter(self.filter_function)\n\n # use the underlying equity as the benchmark\n self.set_benchmark(equity.symbol)\n\n def filter_function(self, universe):\n #Expires today, is a call, and is within 10 dollars of the current price\n universe = universe.weeklys_only().expiration(0, 1)\n return [symbol for symbol in universe \n if symbol.id.option_right != OptionRight.PUT \n and -10 < universe.underlying.price - symbol.id.strike_price < 10]\n\n def on_data(self, slice):\n if self.portfolio.invested: return\n\n for kvp in slice.option_chains:\n \n if kvp.key != self.option_symbol: continue\n\n # Get the first call strike under market price expiring today\n chain = kvp.value\n contracts = [option for option in sorted(chain, key = lambda x:x.strike, reverse = True)\n if option.expiry.date() == self.time.date()\n and option.strike < chain.underlying.price]\n \n if contracts:\n self.market_order(contracts[0].symbol, 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CoarseFineFundamentalComboAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2014,1,1) #Set Start Date\n self.set_end_date(2015,1,1) #Set End Date\n self.set_cash(50000) #Set Strategy Cash\n\n # what resolution should the data *added* to the universe be?\n self.universe_settings.resolution = Resolution.DAILY\n\n # this add universe method accepts two parameters:\n # - coarse selection function: accepts an IEnumerable and returns an IEnumerable\n # - fine selection function: accepts an IEnumerable and returns an IEnumerable\n self.add_universe(self.coarse_selection_function, self.fine_selection_function)\n\n self.__number_of_symbols = 5\n self.__number_of_symbols_fine = 2\n self._changes = None\n\n\n # sort the data by daily dollar volume and take the top 'NumberOfSymbols'\n def coarse_selection_function(self, coarse):\n # sort descending by daily dollar volume\n sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)\n\n # return the symbol objects of the top entries from our sorted collection\n return [ x.symbol for x in sorted_by_dollar_volume[:self.__number_of_symbols] ]\n\n # sort the data by P/E ratio and take the top 'NumberOfSymbolsFine'\n def fine_selection_function(self, fine):\n # sort descending by P/E ratio\n sorted_by_pe_ratio = sorted(fine, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)\n\n # take the top entries from our sorted collection\n return [ x.symbol for x in sorted_by_pe_ratio[:self.__number_of_symbols_fine] ]\n\n def on_data(self, data):\n # if we have no changes, do nothing\n if self._changes is None: return\n\n # liquidate removed securities\n for security in self._changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n\n # we want 20% allocation in each security in our universe\n for security in self._changes.added_securities:\n self.set_holdings(security.symbol, 0.2)\n\n self._changes = None\n\n\n # this event fires whenever we have changes to our universe\n def on_securities_changed(self, changes):\n self._changes = changes\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Mean Variance Optimization algorithm\nUses the HistoricalReturnsAlphaModel and the MeanVarianceOptimizationPortfolioConstructionModel\nto create an algorithm that rebalances the portfolio according to modern portfolio theory", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Portfolio.MeanVarianceOptimizationPortfolioConstructionModel import *\n\nclass MeanVarianceOptimizationFrameworkAlgorithm(QCAlgorithm):\n '''Mean Variance Optimization algorithm.'''\n\n def initialize(self):\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.MINUTE\n\n self.settings.rebalance_portfolio_on_insight_changes = False\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self._symbols = [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in [ 'AIG', 'BAC', 'IBM', 'SPY' ] ]\n\n # set algorithm framework models\n self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selector))\n self.set_alpha(HistoricalReturnsAlphaModel(resolution = Resolution.DAILY))\n self.set_portfolio_construction(MeanVarianceOptimizationPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(NullRiskManagementModel())\n\n def coarse_selector(self, coarse):\n # Drops SPY after the 8th\n last = 3 if self.time.day > 8 else len(self._symbols)\n\n return self._symbols[0:last]\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n self.log(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template algorithm for the Axos brokerage", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateAxosAlgorithm(QCAlgorithm):\n '''Basic template algorithm simply initializes the date range and cash'''\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self.set_brokerage_model(BrokerageName.AXOS)\n self.add_equity(\"SPY\", Resolution.MINUTE)\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n # will set 25% of our buying power with a market order\n self.set_holdings(\"SPY\", 0.25)\n self.debug(\"Purchased SPY!\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm for testing parameterized regression algorithms get valid parameters.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass GetParameterRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.check_parameter(None, self.get_parameter(\"non-existing\"), \"GetParameter(\\\"non-existing\\\")\")\n self.check_parameter(\"100\", self.get_parameter(\"non-existing\", \"100\"), \"GetParameter(\\\"non-existing\\\", \\\"100\\\")\")\n self.check_parameter(100, self.get_parameter(\"non-existing\", 100), \"GetParameter(\\\"non-existing\\\", 100)\")\n self.check_parameter(100.0, self.get_parameter(\"non-existing\", 100.0), \"GetParameter(\\\"non-existing\\\", 100.0)\")\n\n self.check_parameter(\"10\", self.get_parameter(\"ema-fast\"), \"GetParameter(\\\"ema-fast\\\")\")\n self.check_parameter(10, self.get_parameter(\"ema-fast\", 100), \"GetParameter(\\\"ema-fast\\\", 100)\")\n self.check_parameter(10.0, self.get_parameter(\"ema-fast\", 100.0), \"GetParameter(\\\"ema-fast\\\", 100.0)\")\n\n self.quit()\n\n def check_parameter(self, expected, actual, call):\n if expected == None and actual != None:\n raise AssertionError(f\"{call} should have returned null but returned {actual} ({type(actual)})\")\n\n if expected != None and actual == None:\n raise AssertionError(f\"{call} should have returned {expected} ({type(expected)}) but returned null\")\n\n if expected != None and actual != None and type(expected) != type(actual) or expected != actual:\n raise AssertionError(f\"{call} should have returned {expected} ({type(expected)}) but returned {actual} ({type(actual)})\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm show casing and asserting the behavior of creating a consolidator specifying the start time", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom collections import deque\n\nclass ConsolidatorStartTimeRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013, 10, 4)\n self.set_end_date(2013, 10, 4)\n\n self.add_equity(\"SPY\", Resolution.MINUTE)\n\n consolidator = TradeBarConsolidator(timedelta(hours=1), start_time=timedelta(hours=9, minutes=30))\n consolidator.data_consolidated += self.bar_handler\n self.subscription_manager.add_consolidator(\"SPY\", consolidator)\n\n self._expectedConsolidationTime = deque()\n self._expectedConsolidationTime.append(time(14, 30))\n self._expectedConsolidationTime.append(time(13, 30))\n self._expectedConsolidationTime.append(time(12, 30))\n self._expectedConsolidationTime.append(time(11, 30))\n self._expectedConsolidationTime.append(time(10, 30))\n self._expectedConsolidationTime.append(time(9, 30))\n\n def bar_handler(self, _, bar):\n if self.time != bar.end_time:\n raise RegressionTestException(f\"Unexpected consolidation time {bar.Time} != {Time}!\")\n\n self.debug(f\"{self.time} - Consolidation\")\n expected = self._expectedConsolidationTime.pop()\n if bar.time.time() != expected:\n raise RegressionTestException(f\"Unexpected consolidation time {bar.time.time()} != {expected}!\")\n\n if bar.period != timedelta(hours=1):\n raise RegressionTestException(f\"Unexpected consolidation period {bar.period}!\")\n\n def on_end_of_algorithm(self):\n if len(self._expectedConsolidationTime) > 0:\n raise RegressionTestException(\"Unexpected consolidation times!\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Framework algorithm that uses the EmaCrossUniverseSelectionModel to\nselect the universe based on a moving average cross.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Alphas.ConstantAlphaModel import ConstantAlphaModel\nfrom Selection.EmaCrossUniverseSelectionModel import EmaCrossUniverseSelectionModel\nfrom Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\n\nclass EmaCrossUniverseSelectionFrameworkAlgorithm(QCAlgorithm):\n '''Framework algorithm that uses the EmaCrossUniverseSelectionModel to select the universe based on a moving average cross.'''\n\n def initialize(self):\n\n self.set_start_date(2013,1,1)\n self.set_end_date(2015,1,1)\n self.set_cash(100000)\n\n fast_period = 100\n slow_period = 300\n count = 10\n\n self.universe_settings.leverage = 2.0\n self.universe_settings.resolution = Resolution.DAILY\n\n self.set_universe_selection(EmaCrossUniverseSelectionModel(fast_period, slow_period, count))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1), None, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to add options for a given underlying equity security.\nIt also shows how you can prefilter contracts easily based on strikes and expirations.\nIt also shows how you can inspect the option chain to pick a specific option contract to trade.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateOptionTradesAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n self.set_cash(100000)\n\n option = self.add_option(\"GOOG\")\n\n # add the initial contract filter \n # SetFilter method accepts timedelta objects or integer for days.\n # The following statements yield the same filtering criteria\n option.set_filter(-2, +2, 0, 10)\n # option.set_filter(-2, +2, timedelta(0), timedelta(10))\n\n # use the underlying equity as the benchmark\n self.set_benchmark(\"GOOG\")\n\n def on_data(self,slice):\n if not self.portfolio.invested:\n for kvp in slice.option_chains:\n chain = kvp.value\n # find the second call strike under market price expiring today\n contracts = sorted(sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike)),\n key = lambda x: x.expiry, reverse=False)\n\n if len(contracts) == 0: continue\n if contracts[0] != None:\n self.market_order(contracts[0].symbol, 1)\n else:\n self.liquidate()\n\n for kpv in slice.bars:\n self.log(\"---> OnData: {0}, {1}, {2}\".format(self.time, kpv.key.value, str(kpv.value.close)))\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm showing that Slice, Securities and Portfolio behave as a Python Dictionary", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass PythonDictionaryFeatureRegressionAlgorithm(QCAlgorithm):\n '''Example algorithm showing that Slice, Securities and Portfolio behave as a Python Dictionary'''\n\n def initialize(self):\n\n self.set_start_date(2013,10, 7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self.spy_symbol = self.add_equity(\"SPY\").symbol\n self.ibm_symbol = self.add_equity(\"IBM\").symbol\n self.aig_symbol = self.add_equity(\"AIG\").symbol\n self.aapl_symbol = Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA)\n\n date_rules = self.date_rules.on(2013, 10, 7)\n self.schedule.on(date_rules, self.time_rules.at(13, 0), self.test_securities_dictionary)\n self.schedule.on(date_rules, self.time_rules.at(14, 0), self.test_portfolio_dictionary)\n self.schedule.on(date_rules, self.time_rules.at(15, 0), self.test_slice_dictionary)\n\n def test_slice_dictionary(self):\n slice = self.current_slice\n\n symbols = ', '.join([f'{x}' for x in slice.keys()])\n slice_data = ', '.join([f'{x}' for x in slice.values()])\n slice_bars = ', '.join([f'{x}' for x in slice.bars.values()])\n\n if \"SPY\" not in slice:\n raise AssertionError('SPY (string) is not in Slice')\n\n if self.spy_symbol not in slice:\n raise AssertionError('SPY (Symbol) is not in Slice')\n\n spy = slice.get(self.spy_symbol)\n if spy is None:\n raise AssertionError('SPY is not in Slice')\n\n for symbol, bar in slice.bars.items():\n self.plot(symbol, 'Price', bar.close)\n\n\n def test_securities_dictionary(self):\n symbols = ', '.join([f'{x}' for x in self.securities.keys()])\n leverages = ', '.join([str(x.get_last_data()) for x in self.securities.values()])\n\n if \"IBM\" not in self.securities:\n raise AssertionError('IBM (string) is not in Securities')\n\n if self.ibm_symbol not in self.securities:\n raise AssertionError('IBM (Symbol) is not in Securities')\n\n ibm = self.securities.get(self.ibm_symbol)\n if ibm is None:\n raise AssertionError('ibm is None')\n\n aapl = self.securities.get(self.aapl_symbol)\n if aapl is not None:\n raise AssertionError('aapl is not None')\n\n for symbol, security in self.securities.items():\n self.plot(symbol, 'Price', security.price)\n\n def test_portfolio_dictionary(self):\n symbols = ', '.join([f'{x}' for x in self.portfolio.keys()])\n leverages = ', '.join([f'{x.symbol}: {x.leverage}' for x in self.portfolio.values()])\n\n if \"AIG\" not in self.securities:\n raise AssertionError('AIG (string) is not in Portfolio')\n\n if self.aig_symbol not in self.securities:\n raise AssertionError('AIG (Symbol) is not in Portfolio')\n\n aig = self.portfolio.get(self.aig_symbol)\n if aig is None:\n raise AssertionError('aig is None')\n\n aapl = self.portfolio.get(self.aapl_symbol)\n if aapl is not None:\n raise AssertionError('aapl is not None')\n\n for symbol, holdings in self.portfolio.items():\n msg = f'{symbol}: {holdings.leverage}'\n\n def on_end_of_algorithm(self):\n\n portfolio_copy = self.portfolio.copy()\n try:\n self.portfolio.clear() # Throws exception\n except Exception as e:\n self.debug(e)\n\n bar = self.securities.pop(\"SPY\")\n length = len(self.securities)\n if length != 2:\n raise AssertionError(f'After popping SPY, Securities should have 2 elements, {length} found')\n\n securities_copy = self.securities.copy()\n self.securities.clear() # Does not throw\n\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1/3)\n self.set_holdings(\"IBM\", 1/3)\n self.set_holdings(\"AIG\", 1/3)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example structure for structuring an algorithm with indicator and consolidator data for many tickers.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MultipleSymbolConsolidationAlgorithm(QCAlgorithm):\n\n # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.\n def initialize(self) -> None:\n # This is the period of bars we'll be creating\n bar_period = TimeSpan.from_minutes(10)\n # This is the period of our sma indicators\n sma_period = 10\n # This is the number of consolidated bars we'll hold in symbol data for reference\n rolling_window_size = 10\n # Holds all of our data keyed by each symbol\n self._data = {}\n # Contains all of our equity symbols\n equity_symbols = [\"AAPL\",\"SPY\",\"IBM\"]\n # Contains all of our forex symbols\n forex_symbols = [\"EURUSD\", \"USDJPY\", \"EURGBP\", \"EURCHF\", \"USDCAD\", \"USDCHF\", \"AUDUSD\",\"NZDUSD\"]\n\n self.set_start_date(2014, 12, 1)\n self.set_end_date(2015, 2, 1)\n\n # initialize our equity data\n for symbol in equity_symbols:\n equity = self.add_equity(symbol)\n self._data[symbol] = SymbolData(equity.symbol, bar_period, rolling_window_size)\n\n # initialize our forex data\n for symbol in forex_symbols:\n forex = self.add_forex(symbol)\n self._data[symbol] = SymbolData(forex.symbol, bar_period, rolling_window_size)\n\n # loop through all our symbols and request data subscriptions and initialize indicator\n for symbol, symbol_data in self._data.items():\n # define the indicator\n symbol_data.sma = SimpleMovingAverage(self.create_indicator_name(symbol, \"sma\" + str(sma_period), Resolution.MINUTE), sma_period)\n # define a consolidator to consolidate data for this symbol on the requested period\n\n if symbol_data._symbol.security_type == SecurityType.EQUITY:\n tb_consolidator = TradeBarConsolidator(bar_period)\n tb_consolidator.data_consolidated += self.on_trade_bar_consolidated\n # we need to add this consolidator so it gets auto updates\n self.subscription_manager.add_consolidator(symbol_data._symbol, tb_consolidator)\n else:\n qb_consolidator = QuoteBarConsolidator(bar_period)\n qb_consolidator.data_consolidated += self.on_quote_bar_consolidated\n # we need to add this consolidator so it gets auto updates\n self.subscription_manager.add_consolidator(symbol_data._symbol, qb_consolidator)\n\n def on_trade_bar_consolidated(self, sender: object, bar: TradeBar) -> None:\n self._on_data_consolidated(sender, bar)\n\n def on_quote_bar_consolidated(self, sender: object, bar: QuoteBar) -> None:\n self._on_data_consolidated(sender, bar)\n\n def _on_data_consolidated(self, sender: object, bar: TradeBar | QuoteBar) -> None:\n self._data[bar.symbol.value].sma.update(bar.time, bar.close)\n self._data[bar.symbol.value].bars.add(bar)\n\n # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n # Argument \"data\": Slice object, dictionary object with your stock data\n def on_data(self, data: Slice) -> None:\n # loop through each symbol in our structure\n for symbol in self._data.keys():\n symbol_data = self._data[symbol]\n # this check proves that this symbol was JUST updated prior to this OnData function being called\n if symbol_data.is_ready() and symbol_data.was_just_updated(self.time):\n if not self.portfolio[symbol].invested:\n self.market_order(symbol, 1)\n\n # End of a trading day event handler. This method is called at the end of the algorithm day (or multiple times if trading multiple assets).\n # Method is called 10 minutes before closing to allow user to close out position.\n def on_end_of_day(self, symbol: Symbol) -> None:\n i = 0\n for symbol_key in sorted(self._data.keys()):\n symbol_data = self._data[symbol_key]\n # we have too many symbols to plot them all, so plot every other\n i += 1\n if symbol_data.is_ready() and i%2 == 0:\n self.plot(symbol_key, symbol_key, symbol_data.sma.current.value)\n\n\nclass SymbolData(object):\n\n def __init__(self, symbol: Symbol, bar_period: timedelta, window_size: int) -> None:\n self._symbol = symbol\n # The period used when population the Bars rolling window\n self.bar_period = bar_period\n # A rolling window of data, data needs to be pumped into Bars by using Bars.update( trade_bar ) and can be accessed like:\n # my_symbol_data.bars[0] - most first recent piece of data\n # my_symbol_data.bars[5] - the sixth most recent piece of data (zero based indexing)\n self.bars = RollingWindow(window_size)\n # The simple moving average indicator for our symbol\n self.sma = None\n\n # Returns true if all the data in this instance is ready (indicators, rolling windows, ect...)\n def is_ready(self) -> bool:\n return self.bars.is_ready and self.sma.is_ready\n\n # Returns true if the most recent trade bar time matches the current time minus the bar's period, this\n # indicates that update was just called on this instance\n def was_just_updated(self, current: datetime) -> bool:\n return self.bars.count > 0 and self.bars[0].time == current - self.bar_period\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to test we can specify a custom settlement model, and override some of its methods", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom CustomBrokerageModelRegressionAlgorithm import CustomBrokerageModel\n\nclass CustomSettlementModelRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,11)\n self.set_cash(10000)\n self.spy = self.add_equity(\"SPY\", Resolution.DAILY)\n self.set_settlement_model(self.spy)\n\n def set_settlement_model(self, security):\n self.set_brokerage_model(CustomBrokerageModelWithCustomSettlementModel())\n\n def on_data(self, slice):\n if self.portfolio.cash_book[Currencies.USD].amount == 10000:\n parameters = ApplyFundsSettlementModelParameters(self.portfolio, self.spy, self.time, CashAmount(101, Currencies.USD), None)\n self.spy.settlement_model.apply_funds(parameters)\n\n def on_end_of_algorithm(self):\n if self.portfolio.cash_book[Currencies.USD].amount != 10101:\n raise AssertionError(f\"It was expected to have 10101 USD in Portfolio, but was {self.portfolio.cash_book[Currencies.USD].amount}\")\n parameters = ScanSettlementModelParameters(self.portfolio, self.spy, datetime(2013, 10, 6))\n self.spy.settlement_model.scan(parameters)\n if self.portfolio.cash_book[Currencies.USD].amount != 10000:\n raise AssertionError(f\"It was expected to have 10000 USD in Portfolio, but was {self.portfolio.cash_book[Currencies.USD].amount}\")\n\nclass CustomSettlementModel:\n def apply_funds(self, parameters):\n self.currency = parameters.cash_amount.currency\n self.amount = parameters.cash_amount.amount\n parameters.portfolio.cash_book[self.currency].add_amount(self.amount)\n\n def scan(self, parameters):\n if parameters.utc_time == datetime(2013, 10, 6):\n parameters.portfolio.cash_book[self.currency].add_amount(-self.amount)\n\n def get_unsettled_cash(self):\n return None\n\nclass CustomBrokerageModelWithCustomSettlementModel(CustomBrokerageModel):\n def get_settlement_model(self, security):\n return CustomSettlementModel()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm demonstrating and ensuring that Bybit crypto brokerage model works as expected", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BybitCryptoRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2022, 12, 13)\n self.set_end_date(2022, 12, 13)\n\n # Set account currency (USDT)\n self.set_account_currency(\"USDT\")\n\n # Set strategy cash (USD)\n self.set_cash(100000)\n\n # Add some coin as initial holdings\n # When connected to a real brokerage, the amount specified in SetCash\n # will be replaced with the amount in your actual account.\n self.set_cash(\"BTC\", 1)\n\n self.set_brokerage_model(BrokerageName.BYBIT, AccountType.CASH)\n\n self.btc_usdt = self.add_crypto(\"BTCUSDT\").symbol\n\n # create two moving averages\n self.fast = self.ema(self.btc_usdt, 30, Resolution.MINUTE)\n self.slow = self.ema(self.btc_usdt, 60, Resolution.MINUTE)\n\n self.liquidated = False\n\n def on_data(self, data):\n if self.portfolio.cash_book[\"USDT\"].conversion_rate == 0 or self.portfolio.cash_book[\"BTC\"].conversion_rate == 0:\n self.log(f\"USDT conversion rate: {self.portfolio.cash_book['USDT'].conversion_rate}\")\n self.log(f\"BTC conversion rate: {self.portfolio.cash_book['BTC'].conversion_rate}\")\n\n raise AssertionError(\"Conversion rate is 0\")\n\n if not self.slow.is_ready:\n return\n\n btc_amount = self.portfolio.cash_book[\"BTC\"].amount\n if self.fast > self.slow:\n if btc_amount == 1 and not self.liquidated:\n self.buy(self.btc_usdt, 1)\n else:\n if btc_amount > 1:\n self.liquidate(self.btc_usdt)\n self.liquidated = True\n elif btc_amount > 0 and self.liquidated and len(self.transactions.get_open_orders()) == 0:\n # Place a limit order to sell our initial BTC holdings at 1% above the current price\n limit_price = round(self.securities[self.btc_usdt].price * 1.01, 2)\n self.limit_order(self.btc_usdt, -btc_amount, limit_price)\n\n def on_order_event(self, order_event):\n self.debug(\"{} {}\".format(self.time, order_event.to_string()))\n\n def on_end_of_algorithm(self):\n self.log(f\"{self.time} - TotalPortfolioValue: {self.portfolio.total_portfolio_value}\")\n self.log(f\"{self.time} - CashBook: {self.portfolio.cash_book}\")\n\n btc_amount = self.portfolio.cash_book[\"BTC\"].amount\n if btc_amount > 0:\n raise AssertionError(f\"BTC holdings should be zero at the end of the algorithm, but was {btc_amount}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm implementing VolumeShareSlippageModel.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Orders.Slippage.VolumeShareSlippageModel import VolumeShareSlippageModel\n\nclass VolumeShareSlippageModelAlgorithm(QCAlgorithm):\n _longs = []\n _shorts = []\n\n def initialize(self) -> None:\n self.set_start_date(2020, 11, 29)\n self.set_end_date(2020, 12, 2)\n # To set the slippage model to limit to fill only 30% volume of the historical volume, with 5% slippage impact.\n self.set_security_initializer(lambda security: security.set_slippage_model(VolumeShareSlippageModel(0.3, 0.05)))\n\n self.universe_settings.resolution = Resolution.DAILY\n # Add universe to trade on the most and least weighted stocks among SPY constituents.\n self.add_universe(self.universe.etf(\"SPY\", universe_filter_func=self.selection))\n\n def selection(self, constituents: list[ETFConstituentUniverse]) -> list[Symbol]:\n sorted_by_weight = sorted(constituents, key=lambda c: c.weight)\n # Add the 10 most weighted stocks to the universe to long later.\n self._longs = [c.symbol for c in sorted_by_weight[-10:]]\n # Add the 10 least weighted stocks to the universe to short later.\n self._shorts = [c.symbol for c in sorted_by_weight[:10]]\n\n return self._longs + self._shorts\n\n def on_data(self, slice: Slice) -> None:\n # Equally invest into the selected stocks to evenly dissipate capital risk.\n # Dollar neutral of long and short stocks to eliminate systematic risk, only capitalize the popularity gap.\n targets = [PortfolioTarget(symbol, 0.05) for symbol in self._longs]\n targets += [PortfolioTarget(symbol, -0.05) for symbol in self._shorts]\n\n # Liquidate the ones not being the most and least popularity stocks to release fund for higher expected return trades.\n self.set_holdings(targets, liquidate_existing_holdings=True)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests In The Money (ITM) index option expiry for short calls.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, sell SPX Call Option (expiring ITM)\n * Option assignment\n\nAdditionally, we test delistings for index options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndexOptionShortCallITMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 1, 31)\n self.set_cash(1000000)\n\n self.portfolio.set_margin_call_model(MarginCallModel.NULL);\n\n # avoid getting assigned\n self.set_security_initializer(CompositeSecurityInitializer(self.security_initializer, FuncSecurityInitializer(self.custom_security_initializer)))\n\n self.spx = self.add_index(\"SPX\", Resolution.MINUTE).symbol\n\n # Select a index option expiring ITM, and adds it to the algorithm.\n self.spx_options = list(self.option_chain(self.spx))\n self.spx_options = [i for i in self.spx_options if i.id.strike_price <= 4200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1]\n self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price, reverse=True))[0]\n self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.PUT, 4200, datetime(2021, 1, 15))\n if self.spx_option != self.expected_contract:\n raise AssertionError(f\"Contract self.expected_contract was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1))\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2021, 1, 15):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2021, 1, 16):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if order_event.symbol not in self.securities:\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.spx:\n self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_contract])\n elif security.symbol == self.expected_contract:\n self.assert_index_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security):\n if \"Assignment\" in order_event.message:\n if order_event.fill_price != 4200:\n raise AssertionError(\"Option was not assigned at expected strike price (4200)\")\n\n if order_event.direction != OrderDirection.SELL or index.holdings.quantity != 0:\n raise AssertionError(f\"Expected Qty: 0 index holdings for assigned index option {index.symbol}, found {index.holdings.quantity}\")\n\n elif index.holdings.quantity != 0:\n raise AssertionError(f\"Expected no holdings in index: {index.symbol}\")\n\n def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != -1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n\n if order_event.is_assignment and option.holdings.quantity != 0:\n raise AssertionError(f\"Holdings were found after option contract was assigned: {option.symbol}\")\n\n ### \n ### Ran at the end of the algorithm to ensure the algorithm has no holdings\n ### \n ### The algorithm has holdings\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}\")\n\n def custom_security_initializer(self, security):\n if Extensions.is_option(security.symbol.security_type):\n security.set_option_assignment_model(NullOptionAssignmentModel())\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Hourly regression algorithm trading ADAUSDT binance futures long and short asserting the behavior", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateCryptoFutureHourlyAlgorithm(QCAlgorithm):\n # \n # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.\n # \n\n def initialize(self):\n self.set_start_date(2022, 12, 13)\n self.set_end_date(2022, 12, 13)\n\n self.set_time_zone(TimeZones.UTC)\n\n try:\n self.set_brokerage_model(BrokerageName.BINANCE_COIN_FUTURES, AccountType.CASH)\n except:\n # expected, we don't allow cash account type\n pass\n\n self.set_brokerage_model(BrokerageName.BINANCE_COIN_FUTURES, AccountType.MARGIN)\n\n self.ada_usdt = self.add_crypto_future(\"ADAUSDT\", Resolution.HOUR)\n\n self.fast = self.ema(self.ada_usdt.symbol, 3, Resolution.HOUR)\n self.slow = self.ema(self.ada_usdt.symbol, 6, Resolution.HOUR)\n\n self.interest_per_symbol = {self.ada_usdt.symbol: 0}\n\n # Default USD cash, set 1M but it wont be used\n self.set_cash(1000000)\n\n # the amount of USDT we need to hold to trade 'ADAUSDT'\n self.ada_usdt.quote_currency.set_amount(200)\n\n # \n # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n # \n # Slice object keyed by symbol containing the stock data\n def on_data(self, slice):\n interest_rates = slice.get(MarginInterestRate);\n for interest_rate in interest_rates:\n self.interest_per_symbol[interest_rate.key] += 1\n self.cached_interest_rate = self.securities[interest_rate.key].cache.get_data(MarginInterestRate)\n if self.cached_interest_rate != interest_rate.value:\n raise AssertionError(f\"Unexpected cached margin interest rate for {interest_rate.key}!\")\n\n if self.fast > self.slow:\n if self.portfolio.invested == False and self.transactions.orders_count == 0:\n self.ticket = self.buy(self.ada_usdt.symbol, 100000)\n if self.ticket.status != OrderStatus.INVALID:\n raise AssertionError(f\"Unexpected valid order {self.ticket}, should fail due to margin not sufficient\")\n\n self.buy(self.ada_usdt.symbol, 1000)\n\n self.margin_used = self.portfolio.total_margin_used\n\n self.ada_usdt_holdings = self.ada_usdt.holdings\n\n # USDT/BUSD futures value is based on it's price\n self.holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 1000\n\n if abs(self.ada_usdt_holdings.total_sale_volume - self.holdings_value_usdt) > 1:\n raise AssertionError(f\"Unexpected TotalSaleVolume {self.ada_usdt_holdings.total_sale_volume}\")\n\n if abs(self.ada_usdt_holdings.absolute_holdings_cost - self.holdings_value_usdt) > 1:\n raise AssertionError(f\"Unexpected holdings cost {self.ada_usdt_holdings.holdings_cost}\")\n\n if (abs(self.ada_usdt_holdings.absolute_holdings_cost * 0.05 - self.margin_used) > 1) or (BuyingPowerModelExtensions.get_maintenance_margin(self.ada_usdt.buying_power_model, self.ada_usdt) != self.margin_used):\n raise AssertionError(f\"Unexpected margin used {self.margin_used}\")\n\n # position just opened should be just spread here\n self.profit = self.portfolio.total_unrealized_profit\n\n if (5 - abs(self.profit)) < 0:\n raise AssertionError(f\"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}\")\n\n if (self.portfolio.total_profit != 0):\n raise AssertionError(f\"Unexpected TotalProfit {self.portfolio.total_profit}\")\n\n else:\n # let's revert our position and double\n if self.time.hour > 10 and self.transactions.orders_count == 2:\n self.sell(self.ada_usdt.symbol, 3000)\n\n self.ada_usdt_holdings = self.ada_usdt.holdings\n\n # USDT/BUSD futures value is based on it's price\n self.holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 2000\n\n if abs(self.ada_usdt_holdings.absolute_holdings_cost - self.holdings_value_usdt) > 1:\n raise AssertionError(f\"Unexpected holdings cost {self.ada_usdt_holdings.holdings_cost}\")\n\n # position just opened should be just spread here\n self.profit = self.portfolio.total_unrealized_profit\n if (5 - abs(self.profit)) < 0:\n raise AssertionError(f\"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}\")\n\n # we barely did any difference on the previous trade\n if (5 - abs(self.portfolio.total_profit)) < 0:\n raise AssertionError(f\"Unexpected TotalProfit {self.portfolio.total_profit}\")\n\n if self.time.hour >= 22 and self.transactions.orders_count == 3:\n self.liquidate()\n\n def on_end_of_algorithm(self):\n if self.interest_per_symbol[self.ada_usdt.symbol] != 1:\n raise AssertionError(f\"Unexpected interest rate count {self.interest_per_symbol[self.ada_usdt.symbol]}\")\n\n def on_order_event(self, order_event):\n self.debug(\"{0} {1}\".format(self.time, order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: EMA cross with SP500 E-mini futures\nIn this example, we demostrate how to trade futures contracts using\na equity to generate the trading signals\nIt also shows how you can prefilter contracts easily based on expirations.\nIt also shows how you can inspect the futures chain to pick a specific contract to trade.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FuturesMomentumAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2016, 1, 1)\n self.set_end_date(2016, 8, 18)\n self.set_cash(100000)\n fast_period = 20\n slow_period = 60\n self._tolerance = 1 + 0.001\n self.is_up_trend = False\n self.is_down_trend = False\n self.set_warm_up(max(fast_period, slow_period))\n\n # Adds SPY to be used in our EMA indicators\n equity = self.add_equity(\"SPY\", Resolution.DAILY)\n self._fast = self.ema(equity.symbol, fast_period, Resolution.DAILY)\n self._slow = self.ema(equity.symbol, slow_period, Resolution.DAILY)\n # Adds the future that will be traded and\n # set our expiry filter for this futures chain\n future = self.add_future(Futures.Indices.SP_500_E_MINI)\n future.set_filter(timedelta(0), timedelta(182))\n\n def on_data(self, slice):\n if self._slow.is_ready and self._fast.is_ready:\n self.is_up_trend = self._fast.current.value > self._slow.current.value * self._tolerance\n self.is_down_trend = self._fast.current.value < self._slow.current.value * self._tolerance\n if (not self.portfolio.invested) and self.is_up_trend:\n for chain in slice.futures_chains:\n # find the front contract expiring no earlier than in 90 days\n contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))\n # if there is any contract, trade the front contract\n if len(contracts) == 0: continue\n contract = sorted(contracts, key = lambda x: x.expiry, reverse=True)[0]\n self.market_order(contract.symbol , 1)\n\n if self.portfolio.invested and self.is_down_trend:\n self.liquidate()\n\n def on_end_of_day(self, symbol):\n if self.is_up_trend:\n self.plot(\"Indicator Signal\", \"EOD\",1)\n elif self.is_down_trend:\n self.plot(\"Indicator Signal\", \"EOD\",-1)\n elif self._slow.is_ready and self._fast.is_ready:\n self.plot(\"Indicator Signal\", \"EOD\",0)\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm is expected to stop executing after Initialization. Related to GH 6168 issue", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass QuitInInitializationRegressionAlgorithm(QCAlgorithm):\n '''Basic template algorithm simply initializes the date range and cash'''\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self.add_equity(\"SPY\", Resolution.DAILY)\n self.quit()\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n raise ValueError(\"Algorithm should of stopped!\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Tests filtering in coarse selection by shortable quantity", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AllShortableSymbolsCoarseSelectionRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self._20140325 = datetime(2014, 3, 25)\n self._20140326 = datetime(2014, 3, 26)\n self._20140327 = datetime(2014, 3, 27)\n self._20140328 = datetime(2014, 3, 28)\n self._20140329 = datetime(2014, 3, 29)\n self.last_trade_date = date(1,1,1)\n\n self._aapl = Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA)\n self._bac = Symbol.create(\"BAC\", SecurityType.EQUITY, Market.USA)\n self._gme = Symbol.create(\"GME\", SecurityType.EQUITY, Market.USA)\n self._goog = Symbol.create(\"GOOG\", SecurityType.EQUITY, Market.USA)\n self._qqq = Symbol.create(\"QQQ\", SecurityType.EQUITY, Market.USA)\n self._spy = Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n\n self.coarse_selected = { self._20140325: False, self._20140326: False, self._20140327:False, self._20140328:False }\n self.expected_symbols = { self._20140325: [ self._bac, self._qqq, self._spy ],\n self._20140326: [ self._spy ],\n self._20140327: [ self._aapl, self._bac, self._gme, self._qqq, self._spy ],\n self._20140328: [ self._goog ],\n self._20140329: []}\n\n self.set_start_date(2014, 3, 25)\n self.set_end_date(2014, 3, 29)\n self.set_cash(10000000)\n self.shortable_provider = RegressionTestShortableProvider()\n self.security = self.add_equity(self._spy)\n\n self.add_universe(self.coarse_selection)\n self.universe_settings.resolution = Resolution.DAILY\n\n self.set_brokerage_model(AllShortableSymbolsRegressionAlgorithmBrokerageModel(self.shortable_provider))\n\n def on_data(self, data):\n if self.time.date() == self.last_trade_date:\n return\n\n for (symbol, security) in {x.key: x.value for x in sorted(self.active_securities, key = lambda kvp:kvp.key)}.items():\n if security.invested:\n continue\n shortable_quantity = security.shortable_provider.shortable_quantity(symbol, self.time)\n if not shortable_quantity:\n raise AssertionError(f\"Expected {symbol} to be shortable on {self.time.strftime('%Y%m%d')}\")\n\n \"\"\"\n Buy at least once into all Symbols. Since daily data will always use\n MOO orders, it makes the testing of liquidating buying into Symbols difficult.\n \"\"\"\n self.market_order(symbol, -shortable_quantity)\n self.last_trade_date = self.time.date()\n\n def coarse_selection(self, coarse):\n shortable_symbols = self.shortable_provider.all_shortable_symbols(self.time)\n selected_symbols = list(sorted(filter(lambda x: (x in shortable_symbols.keys()) and (shortable_symbols[x] >= 500), map(lambda x: x.symbol, coarse)), key= lambda x: x.value))\n\n expected_missing = 0\n if self.time.date() == self._20140327.date():\n gme = Symbol.create(\"GME\", SecurityType.EQUITY, Market.USA)\n if gme not in shortable_symbols.keys():\n raise AssertionError(\"Expected unmapped GME in shortable symbols list on 2014-03-27\")\n if \"GME\" not in list(map(lambda x: x.symbol.value, coarse)):\n raise AssertionError(\"Expected mapped GME in coarse symbols on 2014-03-27\")\n\n expected_missing = 1\n\n missing = list(filter(lambda x: x not in selected_symbols, self.expected_symbols[self.time]))\n if len(missing) != expected_missing:\n raise AssertionError(f\"Expected Symbols selected on {self.time.strftime('%Y%m%d')} to match expected Symbols, but the following Symbols were missing: {', '.join(list(map(lambda x:x.value, missing)))}\")\n\n self.coarse_selected[self.time] = True\n return selected_symbols\n\n def on_end_of_algorithm(self):\n if not all(x for x in self.coarse_selected.values()):\n raise AssertionError(f\"Expected coarse selection on all dates, but didn't run on: {', '.join(list(map(lambda x: x[0].strftime('%Y%m%d'), filter(lambda x:not x[1], self.coarse_selected.items()))))}\")\n\nclass AllShortableSymbolsRegressionAlgorithmBrokerageModel(DefaultBrokerageModel):\n def __init__(self, shortable_provider):\n self.shortable_provider = shortable_provider\n super().__init__()\n\n def get_shortable_provider(self, security):\n return self.shortable_provider\n\nclass RegressionTestShortableProvider(LocalDiskShortableProvider):\n def __init__(self):\n super().__init__(\"testbrokerage\")\n\n \"\"\"\n Gets a list of all shortable Symbols, including the quantity shortable as a Dictionary.\n \"\"\"\n def all_shortable_symbols(self, localtime):\n shortable_data_directory = os.path.join(Globals.data_folder, \"equity\", Market.USA, \"shortable\", self.brokerage)\n all_symbols = {}\n\n \"\"\"\n Check backwards up to one week to see if we can source a previous file.\n If not, then we return a list of all Symbols with quantity set to zero.\n \"\"\"\n i = 0\n while i <= 7:\n shortable_list_file = os.path.join(shortable_data_directory, \"dates\", f\"{(localtime - timedelta(days=i)).strftime('%Y%m%d')}.csv\")\n\n for line in Extensions.read_lines(self.data_provider, shortable_list_file):\n csv = line.split(',')\n ticker = csv[0]\n\n symbol = Symbol(SecurityIdentifier.generate_equity(ticker, Market.USA, mapping_resolve_date = localtime), ticker)\n quantity = int(csv[1])\n all_symbols[symbol] = quantity\n\n if len(all_symbols) > 0:\n return all_symbols\n\n i += 1\n\n # Return our empty dictionary if we did not find a file to extract\n return all_symbols\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of the parameter system of QuantConnect. Using parameters you can pass the values required into C# algorithms for optimization.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ParameterizedAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013, 10, 7) #Set Start Date\n self.set_end_date(2013, 10, 11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\")\n\n # Receive parameters from the Job\n fast_period = self.get_parameter(\"ema-fast\", 100)\n slow_period = self.get_parameter(\"ema-slow\", 200)\n\n self.fast = self.ema(\"SPY\", fast_period)\n self.slow = self.ema(\"SPY\", slow_period)\n\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n\n # wait for our indicators to ready\n if not self.fast.is_ready or not self.slow.is_ready:\n return\n\n fast = self.fast.current.value\n slow = self.slow.current.value\n\n if fast > slow * 1.001:\n self.set_holdings(\"SPY\", 1)\n elif fast < slow * 0.999:\n self.liquidate(\"SPY\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting the behavior of a ScheduledUniverse", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10, 8)\n \n self._spy = Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n self._selection_time =[ datetime(2013, 10, 7, 1, 0, 0), datetime(2013, 10, 8, 1, 0, 0)]\n\n self.add_universe(ScheduledUniverse(self.date_rules.every_day(), self.time_rules.at(1, 0), self.select_assets))\n\n\n def select_assets(self, time):\n self.debug(f\"Universe selection called: {Time}\")\n expected_time = self._selection_time.pop(0)\n if expected_time != self.time:\n raise ValueError(f\"Unexpected selection time {self.time} expected {expected_time}\")\n\n return [ self._spy ]\n \n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(self._spy, 1)\n\n def on_end_of_algorithm(self):\n if len(self._selection_time) > 0:\n raise ValueError(\"Unexpected selection times\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to get access to futures history for a given root symbol.\nIt also shows how you can prefilter contracts easily based on expirations, and inspect the futures\nchain to pick a specific contract to trade.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateFuturesHistoryAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 8)\n self.set_end_date(2013, 10, 9)\n self.set_cash(1000000)\n\n extended_market_hours = self.get_extended_market_hours()\n\n # Subscribe and set our expiry filter for the futures chain\n # find the front contract expiring no earlier than in 90 days\n future_es = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, extended_market_hours=extended_market_hours)\n future_es.set_filter(timedelta(0), timedelta(182))\n\n future_gc = self.add_future(Futures.Metals.GOLD, Resolution.MINUTE, extended_market_hours=extended_market_hours)\n future_gc.set_filter(timedelta(0), timedelta(182))\n\n self.set_benchmark(lambda x: 1000000)\n\n self.schedule.on(self.date_rules.every_day(), self.time_rules.every(timedelta(hours=1)), self.make_history_call)\n self._success_count = 0\n\n def make_history_call(self):\n history = self.history(self.securities.keys(), 10, Resolution.MINUTE)\n if len(history) < 10:\n raise AssertionError(f'Empty history at {self.time}')\n self._success_count += 1\n\n def on_end_of_algorithm(self):\n if self._success_count < self.get_expected_history_call_count():\n raise AssertionError(f'Scheduled Event did not assert history call as many times as expected: {self._success_count}/49')\n\n def on_data(self,slice):\n if self.portfolio.invested: return\n for chain in slice.future_chains:\n for contract in chain.value:\n self.log(f'{contract.symbol.value},' +\n f'Bid={contract.bid_price} ' +\n f'Ask={contract.ask_price} ' +\n f'Last={contract.last_price} ' +\n f'OI={contract.open_interest}')\n\n def on_securities_changed(self, changes):\n for change in changes.added_securities:\n history = self.history(change.symbol, 10, Resolution.MINUTE).sort_index(level='time', ascending=False)[:3]\n\n for index, row in history.iterrows():\n self.log(f'History: {index[1]} : {index[2]:%m/%d/%Y %I:%M:%S %p} > {row.close}')\n\n def on_order_event(self, order_event):\n # Order fill event handler. On an order fill update the resulting information is passed to this method.\n # Order event details containing details of the events\n self.log(f'{order_event}')\n\n def get_extended_market_hours(self):\n return False\n\n def get_expected_history_call_count(self):\n return 42\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm illustrating the usage of the \nmethod to get multiple futures chains.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FuturesChainsMultipleFullDataRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 7)\n\n es_future = self.add_future(Futures.Indices.SP_500_E_MINI).symbol\n gc_future = self.add_future(Futures.Metals.GOLD).symbol\n\n chains = self.futures_chains([es_future, gc_future], flatten=True)\n\n self._es_contract = self.get_contract(chains, es_future)\n self._gc_contract = self.get_contract(chains, gc_future)\n\n self.add_future_contract(self._es_contract)\n self.add_future_contract(self._gc_contract)\n\n def get_contract(self, chains: FuturesChains, canonical: Symbol) -> Symbol:\n df = chains.data_frame\n\n # Index by the requested underlying, by getting all data with canonicals which underlying is the requested underlying symbol:\n canonicals = df.index.get_level_values('canonical')\n condition = [symbol for symbol in canonicals if symbol == canonical]\n contracts = df.loc[condition]\n\n # Get contracts expiring within 6 months, with the latest expiration date, and lowest price\n contracts = contracts.loc[(df.expiry <= self.time + timedelta(days=180))]\n contracts = contracts.sort_values(['expiry', 'lastprice'], ascending=[False, True])\n\n return contracts.index[0][1]\n\n def on_data(self, data):\n # Do some trading with the selected contract for sample purposes\n if not self.portfolio.invested:\n self.set_holdings(self._es_contract, 0.25)\n self.set_holdings(self._gc_contract, 0.25)\n else:\n self.liquidate()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Futures framework algorithm that uses open interest to select the active contract.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OpenInterestFuturesRegressionAlgorithm(QCAlgorithm):\n\n expected_expiry_dates = {datetime(2013, 12, 27), datetime(2014,2,26)}\n\n def initialize(self):\n self.universe_settings.resolution = Resolution.TICK\n self.set_start_date(2013,10,8)\n self.set_end_date(2013,10,11)\n self.set_cash(10000000)\n\n # set framework models\n universe = OpenInterestFutureUniverseSelectionModel(self, lambda date_time: [Symbol.create(Futures.Metals.GOLD, SecurityType.FUTURE, Market.COMEX)], None, len(self.expected_expiry_dates))\n self.set_universe_selection(universe)\n\n def on_data(self,data):\n if self.transactions.orders_count == 0 and data.has_data:\n matched = list(filter(lambda s: not (s.id.date in self.expected_expiry_dates) and not s.is_canonical(), data.keys()))\n if len(matched) != 0:\n raise AssertionError(f\"{len(matched)}/{len(data.keys())} were unexpected expiry date(s): \" + \", \".join(list(map(lambda x: x.id.date, matched))))\n\n for symbol in data.keys():\n self.market_order(symbol, 1)\n elif any(p.value.invested for p in self.portfolio):\n self.liquidate()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests Out of The Money (OTM) future option expiry for calls.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, buy ES Call Option (expiring OTM)\n - contract expires worthless, not exercised, so never opened a position in the underlying\n\n * Liquidation of worthless ES call option (expiring OTM)\n\nAdditionally, we test delistings for future options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionCallOTMExpiryRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 6, 30)\n\n self.es19m20 = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 6, 19)),\n Resolution.MINUTE).symbol\n\n # Select a future option expiring ITM, and adds it to the algorithm.\n self.es_option = self.add_future_option_contract(\n list(\n sorted(\n [x for x in self.option_chain(self.es19m20)\n if x.id.strike_price >= 3300.0 and x.id.option_right == OptionRight.CALL],\n key=lambda x: x.id.strike_price\n )\n )[0], Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3300.0, datetime(2020, 6, 19))\n if self.es_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n # Place order after regular market opens\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)\n\n def scheduled_market_order(self):\n self.market_order(self.es_option, 1)\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2020, 6, 19):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2020, 6, 20):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if not self.securities.contains_key(order_event.symbol):\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.es19m20:\n raise AssertionError(\"Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM\")\n\n # Expected contract is ES19M20 Call Option expiring OTM @ 3300\n if (security.symbol == self.expected_contract):\n self.assert_future_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n self.log(f\"{order_event}\")\n\n\n def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:\n raise AssertionError(\"Holdings were found after a filled option exercise\")\n\n if order_event.direction == OrderDirection.SELL and \"OTM\" not in order_event.message:\n raise AssertionError(\"Contract did not expire OTM\")\n\n if \"Exercise\" in order_event.message:\n raise AssertionError(\"Exercised option, even though it expires OTM\")\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting we can specify a custom Shortable Provider", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomShortableProviderRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n self.set_cash(10000000)\n self.set_start_date(2013,10,4)\n self.set_end_date(2013,10,6)\n self._spy = self.add_security(SecurityType.EQUITY, \"SPY\", Resolution.DAILY)\n self._spy.set_shortable_provider(CustomShortableProvider())\n\n def on_data(self, data: Slice) -> None:\n spy_shortable_quantity = self._spy.shortable_provider.shortable_quantity(self._spy.symbol, self.time)\n if spy_shortable_quantity and spy_shortable_quantity > 1000:\n self._order_id = self.sell(\"SPY\", int(spy_shortable_quantity)).order_id\n\n def on_end_of_algorithm(self) -> None:\n transactions = self.transactions.orders_count\n if transactions != 1:\n raise AssertionError(\"Algorithm should have just 1 order, but was \" + str(transactions))\n\n order_quantity = self.transactions.get_order_by_id(self._order_id).quantity\n if order_quantity != -1001:\n raise AssertionError(f\"Quantity of order {self._order_id} should be -1001 but was {order_quantity}\")\n \n fee_rate = self._spy.shortable_provider.fee_rate(self._spy.symbol, self.time)\n if fee_rate != 0.0025:\n raise AssertionError(f\"Fee rate should be 0.0025, but was {fee_rate}\")\n rebate_rate = self._spy.shortable_provider.rebate_rate(self._spy.symbol, self.time)\n if rebate_rate != 0.0507:\n raise AssertionError(f\"Rebate rate should be 0.0507, but was {rebate_rate}\")\n\nclass CustomShortableProvider(NullShortableProvider):\n def fee_rate(self, symbol: Symbol, local_time: datetime) -> float:\n return 0.0025\n def rebate_rate(self, symbol: Symbol, local_time: datetime) -> float:\n return 0.0507\n def shortable_quantity(self, symbol: Symbol, local_time: datetime) -> int:\n if local_time < datetime(2013,10,4,16,0,0):\n return 10\n return 1001\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm testing history requests for type work as expected\nand return the same data as the option chain provider.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionUniverseHistoryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2015, 12, 25)\n self.set_end_date(2015, 12, 25)\n\n option = self.add_option(\"GOOG\").symbol\n\n historical_options_data_df = self.history(option, 3, flatten=True)\n\n # Level 0 of the multi-index is the date, we expect 3 dates, 3 option chains\n if historical_options_data_df.index.levshape[0] != 3:\n raise AssertionError(f\"Expected 3 option chains from history request, but got {historical_options_data_df.index.levshape[1]}\")\n\n for date in historical_options_data_df.index.levels[0]:\n expected_chain = list(self.option_chain_provider.get_option_contract_list(option, date))\n expected_chain_count = len(expected_chain)\n\n actual_chain = historical_options_data_df.loc[date]\n actual_chain_count = len(actual_chain)\n\n if expected_chain_count != actual_chain_count:\n raise AssertionError(f\"Expected {expected_chain_count} options in chain on {date}, but got {actual_chain_count}\")\n\n for i, symbol in enumerate(actual_chain.index):\n expected_symbol = expected_chain[i]\n if symbol != expected_symbol:\n raise AssertionError(f\"Expected symbol {expected_symbol} at index {i} on {date}, but got {symbol}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template framework algorithm uses framework components to define the algorithm.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateFrameworkAlgorithm(QCAlgorithm):\n '''Basic template framework algorithm uses framework components to define the algorithm.'''\n\n def initialize(self):\n '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.MINUTE\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n # Find more symbols here: http://quantconnect.com/data\n # Forex, CFD, Equities Resolutions: Tick, Second, Minute, Hour, Daily.\n # Futures Resolution: Tick, Second, Minute\n # Options Resolution: Minute Only.\n symbols = [ Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA) ]\n\n # set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel(symbols))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))\n\n # We can define how often the EWPCM will rebalance if no new insight is submitted using:\n # Resolution Enum:\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY))\n # timedelta\n # self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(timedelta(2)))\n # A lamdda datetime -> datetime. In this case, we can use the pre-defined func at Expiry helper class\n # self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Expiry.END_OF_WEEK))\n\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))\n\n self.debug(\"numpy test >>> print numpy.pi: \" + str(np.pi))\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n self.debug(\"Purchased Stock: {0}\".format(order_event.symbol))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to test universe additions and removals with open positions", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass InceptionDateSelectionRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013,10,1)\n self.set_end_date(2013,10,31)\n self.set_cash(100000)\n\n self.changes = None\n self.universe_settings.resolution = Resolution.HOUR\n\n # select IBM once a week, empty universe the other days\n self.add_universe_selection(CustomUniverseSelectionModel(\"my-custom-universe\", lambda dt: [\"IBM\"] if dt.day % 7 == 0 else []))\n # Adds SPY 5 days after StartDate and keep it in Universe\n self.add_universe_selection(InceptionDateUniverseSelectionModel(\"spy-inception\", {\"SPY\": self.start_date + timedelta(5)}))\n\n\n def on_data(self, slice):\n if self.changes is None:\n return\n\n # we'll simply go long each security we added to the universe\n for security in self.changes.added_securities:\n self.set_holdings(security.symbol, .5)\n\n self.changes = None\n\n def on_securities_changed(self, changes):\n # liquidate removed securities\n for security in changes.removed_securities:\n self.liquidate(security.symbol, \"Removed from Universe\")\n\n self.changes = changes\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of the Market On Close order for US Equities.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MarketOnOpenOnCloseAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.equity = self.add_equity(\"SPY\", Resolution.SECOND, fill_forward = True, extended_market_hours = True)\n self.__submitted_market_on_close_today = False\n self.__last = datetime.min\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n if self.time.date() != self.__last.date(): # each morning submit a market on open order\n self.__submitted_market_on_close_today = False\n self.market_on_open_order(\"SPY\", 100)\n self.__last = self.time\n\n if not self.__submitted_market_on_close_today and self.equity.exchange.exchange_open: # once the exchange opens submit a market on close order\n self.__submitted_market_on_close_today = True\n self.market_on_close_order(\"SPY\", -100)\n\n def on_order_event(self, fill):\n order = self.transactions.get_order_by_id(fill.order_id)\n self.log(\"{0} - {1}:: {2}\".format(self.time, order.type, fill))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm illustrating the usage of the method\nto get an option chain, which contains additional data besides the symbols, including prices, implied volatility and greeks.\nIt also shows how this data can be used to filter the contracts based on certain criteria.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom datetime import timedelta\n\nclass OptionChainFullDataRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n self.set_cash(100000)\n\n goog = self.add_equity(\"GOOG\").symbol\n\n option_chain = self.option_chain(goog, flatten=True)\n\n # Demonstration using data frame:\n df = option_chain.data_frame\n # Get contracts expiring within 10 days, with an implied volatility greater than 0.5 and a delta less than 0.5\n contracts = df.loc[(df.expiry <= self.time + timedelta(days=10)) & (df.impliedvolatility > 0.5) & (df.delta < 0.5)]\n\n # Get the contract with the latest expiration date.\n # Note: the result of df.loc[] is a series, and its name is a tuple with a single element (contract symbol)\n self._option_contract = contracts.loc[contracts.expiry.idxmax()].name\n\n self.add_option_contract(self._option_contract)\n\n def on_data(self, data):\n # Do some trading with the selected contract for sample purposes\n if not self.portfolio.invested:\n self.market_order(self._option_contract, 1)\n else:\n self.liquidate()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression test is a version of \"MarketOnCloseOrderBufferRegressionAlgorithm\"", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm(QCAlgorithm):\n '''This regression test is a version of \"MarketOnCloseOrderBufferRegressionAlgorithm\"\n where we test market-on-close modeling with data from the post market.'''\n _valid_order_ticket = None\n _invalid_order_ticket = None\n _valid_order_ticket_extended_market_hours = None\n\n def initialize(self) -> None:\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,8) #Set End Date\n\n self.add_equity(\"SPY\", Resolution.MINUTE, extended_market_hours = True)\n\n def moc_at_mid_night():\n self._valid_order_ticket_at_midnight = self.market_on_close_order(\"SPY\", 2)\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.midnight, moc_at_mid_night)\n\n # Modify our submission buffer time to 10 minutes\n MarketOnCloseOrder.submission_time_buffer = timedelta(minutes=10)\n\n def on_data(self, data: Slice) -> None:\n # Test our ability to submit MarketOnCloseOrders\n # Because we set our buffer to 10 minutes, any order placed\n # before 3:50PM should be accepted, any after marked invalid\n\n # Will not throw an order error and execute\n if self.time.hour == 15 and self.time.minute == 49 and not self._valid_order_ticket:\n self._valid_order_ticket = self.market_on_close_order(\"SPY\", 2)\n\n # Will throw an order error and be marked invalid\n if self.time.hour == 15 and self.time.minute == 51 and not self._invalid_order_ticket:\n self._invalid_order_ticket = self.market_on_close_order(\"SPY\", 2)\n\n # Will not throw an order error and execute\n if self.time.hour == 16 and self.time.minute == 48 and not self._valid_order_ticket_extended_market_hours:\n self._valid_order_ticket_extended_market_hours = self.market_on_close_order(\"SPY\", 2)\n\n def on_end_of_algorithm(self) -> None:\n # Set it back to default for other regressions\n MarketOnCloseOrder.submission_time_buffer = MarketOnCloseOrder.DEFAULT_SUBMISSION_TIME_BUFFER\n\n if self._valid_order_ticket.status != OrderStatus.FILLED:\n raise AssertionError(\"Valid order failed to fill\")\n\n if self._invalid_order_ticket.status != OrderStatus.INVALID:\n raise AssertionError(\"Invalid order was not rejected\")\n\n if self._valid_order_ticket_extended_market_hours.status != OrderStatus.FILLED:\n raise AssertionError(\"Valid order during extended market hours failed to fill\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm testing history requests for type work as expected\nand return the same data as the futures chain provider.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionUniverseHistoryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 11)\n self.set_end_date(2013, 10, 11)\n\n future = self.add_future(Futures.Indices.SP_500_E_MINI).symbol\n\n historical_futures_data_df = self.history(FutureUniverse, future, 3, flatten=True)\n\n # Level 0 of the multi-index is the date, we expect 3 dates, 3 future chains\n if historical_futures_data_df.index.levshape[0] != 3:\n raise RegressionTestException(f\"Expected 3 futures chains from history request, \"\n f\"but got {historical_futures_data_df.index.levshape[1]}\")\n\n for date in historical_futures_data_df.index.levels[0]:\n expected_chain = list(self.future_chain_provider.get_future_contract_list(future, date))\n expected_chain_count = len(expected_chain)\n\n actual_chain = historical_futures_data_df.loc[date]\n actual_chain_count = len(actual_chain)\n\n if expected_chain_count != actual_chain_count:\n raise RegressionTestException(f\"Expected {expected_chain_count} futures in chain on {date}, \"\n f\"but got {actual_chain_count}\")\n\n for i, symbol in enumerate(actual_chain.index):\n expected_symbol = expected_chain[i]\n if symbol != expected_symbol:\n raise RegressionTestException(f\"Expected symbol {expected_symbol} at index \"\n f\" {i} on {date}, but got {symbol}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: def initialize(self) -> None:", "output": "```python\n\n\nfrom AlgorithmImports import *\n\n# \n# Regression algorithm to test the behaviour of ARMA versus AR models at the same order of differencing.\n# In particular, an ARIMA(1,1,1) and ARIMA(1,1,0) are instantiated while orders are placed if their difference\n# is sufficiently large (which would be due to the inclusion of the MA(1) term).\n# \nclass AutoRegressiveIntegratedMovingAverageRegressionAlgorithm(QCAlgorithm):\n def initialize(self) -> None:\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2013, 1, 7)\n self.set_end_date(2013, 12, 11)\n self.settings.automatic_indicator_warm_up = True\n self.add_equity(\"SPY\", Resolution.DAILY)\n self._arima = self.arima(\"SPY\", 1, 1, 1, 50)\n self._ar = self.arima(\"SPY\", 1, 1, 0, 50)\n self._last = None\n\n def on_data(self, data: Slice) -> None:\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if self._arima.is_ready:\n if abs(self._arima.current.value - self._ar.current.value) > 1:\n if self._arima.current.value > self._last:\n self.market_order(\"SPY\", 1)\n else:\n self.market_order(\"SPY\", -1)\n self._last = self._arima.current.value\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: In this algorithm we show how you can easily use the universe selection feature to fetch symbols\nto be traded using the BaseData custom data system in combination with the AddUniverse{T} method.\nAddUniverse{T} requires a function that will return the symbols to be traded.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass DropboxBaseDataUniverseSelectionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n self.universe_settings.resolution = Resolution.DAILY\n\n # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.\n # Commented so regression algorithm is more sensitive\n #self.settings.minimum_order_margin_portfolio_percentage = 0.005\n\n self.set_start_date(2017, 7, 6)\n self.set_end_date(2018, 7, 4)\n\n universe = self.add_universe(StockDataSource, self.stock_data_source)\n\n historical_selection_data = self.history(universe, 3)\n if len(historical_selection_data) != 3:\n raise ValueError(f\"Unexpected universe data count {len(historical_selection_data)}\")\n\n for universe_data in historical_selection_data[\"symbols\"]:\n if len(universe_data) != 5:\n raise ValueError(f\"Unexpected universe data receieved\")\n\n self._changes = None\n\n def stock_data_source(self, data: list[DynamicData]) -> list[Symbol]:\n list = []\n for item in data:\n for symbol in item[\"Symbols\"]:\n list.append(symbol)\n return list\n\n def on_data(self, slice: Slice) -> None:\n if slice.bars.count == 0:\n return\n if not self._changes:\n return\n\n # start fresh\n self.liquidate()\n\n percentage = 1 / slice.bars.count\n for trade_bar in slice.bars.values():\n self.set_holdings(trade_bar.symbol, percentage)\n\n # reset changes\n self._changes = None\n\n def on_securities_changed(self, changes: SecurityChanges) -> None:\n self._changes = changes\n\nclass StockDataSource(PythonData):\n\n def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:\n url = \"https://www.dropbox.com/s/2l73mu97gcehmh7/daily-stock-picker-live.csv?dl=1\" if is_live_mode else \\\n \"https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1\"\n return SubscriptionDataSource(url, SubscriptionTransportMedium.REMOTE_FILE)\n\n def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData:\n if not (line.strip() and line[0].isdigit()):\n return None\n\n stocks = StockDataSource()\n stocks.symbol = config.symbol\n\n csv = line.split(',')\n if is_live_mode:\n stocks.time = date\n stocks[\"Symbols\"] = csv\n else:\n stocks.time = datetime.strptime(csv[0], \"%Y%m%d\")\n stocks[\"Symbols\"] = csv[1:]\n return stocks\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm checks that adding data via AddData\nworks as expected", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom QuantConnect.Data.Custom.IconicTypes import *\n\nclass CustomDataIconicTypesAddDataRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(100000)\n\n twx_equity = self.add_equity(\"TWX\", Resolution.DAILY).symbol\n custom_twx_symbol = self.add_data(LinkedData, twx_equity, Resolution.DAILY).symbol\n\n self.googl_equity = self.add_equity(\"GOOGL\", Resolution.DAILY).symbol\n custom_googl_symbol = self.add_data(LinkedData, \"GOOGL\", Resolution.DAILY).symbol\n\n unlinked_data_symbol = self.add_data(UnlinkedData, \"GOOGL\", Resolution.DAILY).symbol\n unlinked_data_symbol_underlying_equity = Symbol.create(\"MSFT\", SecurityType.EQUITY, Market.USA)\n unlinked_data_symbol_underlying = self.add_data(UnlinkedData, unlinked_data_symbol_underlying_equity, Resolution.DAILY).symbol\n\n option_symbol = self.add_option(\"TWX\", Resolution.MINUTE).symbol\n custom_option_symbol = self.add_data(LinkedData, option_symbol, Resolution.DAILY).symbol\n\n if custom_twx_symbol.underlying != twx_equity:\n raise AssertionError(f\"Underlying symbol for {custom_twx_symbol} is not equal to TWX equity. Expected {twx_equity} got {custom_twx_symbol.underlying}\")\n if custom_googl_symbol.underlying != self.googl_equity:\n raise AssertionError(f\"Underlying symbol for {custom_googl_symbol} is not equal to GOOGL equity. Expected {self.googl_equity} got {custom_googl_symbol.underlying}\")\n if unlinked_data_symbol.has_underlying:\n raise AssertionError(f\"Unlinked data type (no underlying) has underlying when it shouldn't. Found {unlinked_data_symbol.underlying}\")\n if not unlinked_data_symbol_underlying.has_underlying:\n raise AssertionError(\"Unlinked data type (with underlying) has no underlying Symbol even though we added with Symbol\")\n if unlinked_data_symbol_underlying.underlying != unlinked_data_symbol_underlying_equity:\n raise AssertionError(f\"Unlinked data type underlying does not equal equity Symbol added. Expected {unlinked_data_symbol_underlying_equity} got {unlinked_data_symbol_underlying.underlying}\")\n if custom_option_symbol.underlying != option_symbol:\n raise AssertionError(f\"Option symbol not equal to custom underlying symbol. Expected {option_symbol} got {custom_option_symbol.underlying}\")\n\n try:\n custom_data_no_cache = self.add_data(LinkedData, \"AAPL\", Resolution.DAILY)\n raise AssertionError(\"AAPL was found in the SymbolCache, though it should be missing\")\n except InvalidOperationException as e:\n return\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested and len(self.transactions.get_open_orders()) == 0:\n self.set_holdings(self.googl_equity, 0.5)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Using rolling windows for efficient storage of historical data; which automatically clears after a period of time.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass RollingWindowAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10,1) #Set Start Date\n self.set_end_date(2013,11,1) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\", Resolution.DAILY)\n\n # Creates a Rolling Window indicator to keep the 2 TradeBar\n self._window = RollingWindow(2) # For other security types, use QuoteBar\n\n # Creates an indicator and adds to a rolling window when it is updated\n self._sma = self.sma(\"SPY\", 5)\n self._sma.updated += self._sma_updated\n self._sma_win = RollingWindow(5)\n\n\n def _sma_updated(self, sender, updated):\n '''Adds updated values to rolling window'''\n self._sma_win.add(updated)\n\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''\n\n # Add SPY TradeBar in rollling window\n self._window.add(data[\"SPY\"])\n\n # Wait for windows to be ready.\n if not (self._window.is_ready and self._sma_win.is_ready): return\n\n curr_bar = self._window[0] # Current bar had index zero.\n past_bar = self._window[1] # Past bar has index one.\n self.log(f\"Price: {past_bar.time} -> {past_bar.close} ... {curr_bar.time} -> {curr_bar.close}\")\n\n curr_sma = self._sma_win[0] # Current SMA had index zero.\n past_sma = self._sma_win[self._sma_win.count-1] # Oldest SMA has index of window count minus 1.\n self.log(f\"SMA: {past_sma.time} -> {past_sma.value} ... {curr_sma.time} -> {curr_sma.value}\")\n\n if not self.portfolio.invested and curr_sma.value > past_sma.value:\n self.set_holdings(\"SPY\", 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to implement a cross moving average for the futures front contract", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass EmaCrossFuturesFrontMonthAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 8)\n self.set_end_date(2013, 10, 10)\n self.set_cash(1000000)\n\n future = self.add_future(Futures.Metals.GOLD)\n\n # Only consider the front month contract\n # Update the universe once per day to improve performance\n future.set_filter(lambda x: x.front_month().only_apply_filter_at_market_open())\n\n # Symbol of the current contract\n self._symbol = None\n\n # Create two exponential moving averages\n self.fast = ExponentialMovingAverage(100)\n self.slow = ExponentialMovingAverage(300)\n self.tolerance = 0.001\n self.consolidator = None\n\n # Add a custom chart to track the EMA cross\n chart = Chart('EMA Cross')\n chart.add_series(Series('Fast', SeriesType.LINE, 0))\n chart.add_series(Series('Slow', SeriesType.LINE, 0))\n self.add_chart(chart)\n\n def on_data(self,slice):\n\n holding = None if self._symbol is None else self.portfolio.get(self._symbol)\n if holding is not None:\n # Buy the futures' front contract when the fast EMA is above the slow one\n if self.fast.current.value > self.slow.current.value * (1 + self.tolerance):\n if not holding.invested:\n self.set_holdings(self._symbol, .1)\n self.plot_ema()\n elif holding.invested:\n self.liquidate(self._symbol)\n self.plot_ema()\n\n def on_securities_changed(self, changes):\n if len(changes.removed_securities) > 0:\n # Remove the consolidator for the previous contract\n # and reset the indicators\n if self._symbol is not None and self.consolidator is not None:\n self.subscription_manager.remove_consolidator(self._symbol, self.consolidator)\n self.fast.reset()\n self.slow.reset()\n # We don't need to call Liquidate(_symbol),\n # since its positions are liquidated because the contract has expired.\n\n # Only one security will be added: the new front contract\n self._symbol = changes.added_securities[0].symbol\n\n # Create a new consolidator and register the indicators to it\n self.consolidator = self.resolve_consolidator(self._symbol, Resolution.MINUTE)\n self.register_indicator(self._symbol, self.fast, self.consolidator)\n self.register_indicator(self._symbol, self.slow, self.consolidator)\n\n # Warm up the indicators\n self.warm_up_indicator(self._symbol, self.fast, Resolution.MINUTE)\n self.warm_up_indicator(self._symbol, self.slow, Resolution.MINUTE)\n\n self.plot_ema()\n\n def plot_ema(self):\n self.plot('EMA Cross', 'Fast', self.fast.current.value)\n self.plot('EMA Cross', 'Slow', self.slow.current.value)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: The demonstration algorithm shows some of the most common order methods when working with CFD assets.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\n\nclass BasicTemplateCfdAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_account_currency('EUR')\n\n self.set_start_date(2019, 2, 20)\n self.set_end_date(2019, 2, 21)\n self.set_cash('EUR', 100000)\n\n self._symbol = self.add_cfd('DE30EUR').symbol\n\n # Historical Data\n history = self.history(self._symbol, 60, Resolution.DAILY)\n self.log(f\"Received {len(history)} bars from CFD historical data call.\")\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n Arguments:\n slice: Slice object keyed by symbol containing the stock data\n '''\n # Access Data\n if data.quote_bars.contains_key(self._symbol):\n quote_bar = data.quote_bars[self._symbol]\n self.log(f\"{quote_bar.end_time} :: {quote_bar.close}\")\n\n if not self.portfolio.invested:\n self.set_holdings(self._symbol, 1)\n\n def on_order_event(self, order_event):\n self.debug(\"{} {}\".format(self.time, order_event.to_string()))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm tests and demonstrates EUREX futures subscription and trading:\n- It tests contracts rollover by adding a continuous future and asserting that mapping happens at some point.\n- It tests basic trading by buying a contract and holding it until expiration.\n- It tests delisting and asserts the holdings are liquidated after that.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateEurexFuturesAlgorithm(QCAlgorithm):\n def __init__(self):\n super().__init__()\n self._continuous_contract = None\n self._mapped_symbol = None\n self._contract_to_trade = None\n self._mappings_count = 0\n self._bought_quantity = 0\n self._liquidated_quantity = 0\n self._delisted = False\n\n def initialize(self):\n self.set_start_date(2024, 5, 30)\n self.set_end_date(2024, 6, 23)\n\n self.set_account_currency(Currencies.EUR);\n self.set_cash(1000000)\n\n self._continuous_contract = self.add_future(\n Futures.Indices.EURO_STOXX_50,\n Resolution.MINUTE,\n data_normalization_mode=DataNormalizationMode.BACKWARDS_RATIO,\n data_mapping_mode=DataMappingMode.FIRST_DAY_MONTH,\n contract_depth_offset=0,\n )\n self._continuous_contract.set_filter(timedelta(days=0), timedelta(days=180))\n self._mapped_symbol = self._continuous_contract.mapped\n\n benchmark = self.add_index(\"SX5E\")\n self.set_benchmark(benchmark.symbol)\n\n func_seeder = FuncSecuritySeeder(self.get_last_known_prices)\n self.set_security_initializer(lambda security: func_seeder.seed_security(security))\n\n def on_data(self, slice):\n for changed_event in slice.symbol_changed_events.values():\n self._mappings_count += 1\n if self._mappings_count > 1:\n raise AssertionError(f\"{self.time} - Unexpected number of symbol changed events (mappings): {self._mappings_count}. Expected only 1.\")\n\n self.debug(f\"{self.time} - SymbolChanged event: {changed_event}\")\n\n if changed_event.old_symbol != str(self._mapped_symbol.id):\n raise AssertionError(f\"{self.time} - Unexpected symbol changed event old symbol: {changed_event}\")\n\n if changed_event.new_symbol != str(self._continuous_contract.mapped.id):\n raise AssertionError(f\"{self.time} - Unexpected symbol changed event new symbol: {changed_event}\")\n\n # Let's trade the previous mapped contract, so we can hold it until expiration for testing\n # (will be sooner than the new mapped contract)\n self._contract_to_trade = self._mapped_symbol\n self._mapped_symbol = self._continuous_contract.mapped\n\n # Let's trade after the mapping is done\n if self._contract_to_trade is not None and self._bought_quantity == 0 and self.securities[self._contract_to_trade].exchange.exchange_open:\n self.buy(self._contract_to_trade, 1)\n\n if self._contract_to_trade is not None and slice.delistings.contains_key(self._contract_to_trade):\n delisting = slice.delistings[self._contract_to_trade]\n if delisting.type == DelistingType.DELISTED:\n self._delisted = True\n\n if self.portfolio.invested:\n raise AssertionError(f\"{self.time} - Portfolio should not be invested after the traded contract is delisted.\")\n\n def on_order_event(self, order_event):\n if order_event.symbol != self._contract_to_trade:\n raise AssertionError(f\"{self.time} - Unexpected order event symbol: {order_event.symbol}. Expected {self._contract_to_trade}\")\n\n if order_event.direction == OrderDirection.BUY:\n if order_event.status == OrderStatus.FILLED:\n if self._bought_quantity != 0 and self._liquidated_quantity != 0:\n raise AssertionError(f\"{self.time} - Unexpected buy order event status: {order_event.status}\")\n\n self._bought_quantity = order_event.quantity\n elif order_event.direction == OrderDirection.SELL:\n if order_event.status == OrderStatus.FILLED:\n if self._bought_quantity <= 0 and self._liquidated_quantity != 0:\n raise AssertionError(f\"{self.time} - Unexpected sell order event status: {order_event.status}\")\n\n self._liquidated_quantity = order_event.quantity\n if self._liquidated_quantity != -self._bought_quantity:\n raise AssertionError(f\"{self.time} - Unexpected liquidated quantity: {self._liquidated_quantity}. Expected: {-self._bought_quantity}\")\n\n def on_securities_changed(self, changes):\n for added_security in changes.added_securities:\n if added_security.symbol.security_type == SecurityType.FUTURE and added_security.symbol.is_canonical():\n self._mapped_symbol = self._continuous_contract.mapped\n\n def on_end_of_algorithm(self):\n if self._mappings_count == 0:\n raise AssertionError(f\"Unexpected number of symbol changed events (mappings): {self._mappings_count}. Expected 1.\")\n\n if not self._delisted:\n raise AssertionError(\"Contract was not delisted\")\n\n # Make sure we traded and that the position was liquidated on delisting\n if self._bought_quantity <= 0 or self._liquidated_quantity >= 0:\n raise AssertionError(f\"Unexpected sold quantity: {self._bought_quantity} and liquidated quantity: {self._liquidated_quantity}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Strategy example algorithm using CAPE - a bubble indicator dataset saved in dropbox. CAPE is based on a macroeconomic indicator(CAPE Ratio),\nwe are looking for entry/exit points for momentum stocks CAPE data: January 1990 - December 2014\nGoals:\nCapitalize in overvalued markets by generating returns with momentum and selling before the crash\nCapitalize in undervalued markets by purchasing stocks at bottom of trough", "output": "```python\n\n # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.\n# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom AlgorithmImports import *\n\nclass BubbleAlgorithm(QCAlgorithm):\n\n def initialize(self):\n\n self.set_cash(100000)\n self.set_start_date(1998,1,1)\n self.set_end_date(2014,6,1)\n self._symbols = []\n self._macd_dic, self._rsi_dic = {},{}\n self._new_low, self._curr_cape = None, None\n self._counter, self._counter2 = 0, 0\n self._c, self._c_copy = np.empty([4]), np.empty([4])\n self._symbols.append(\"SPY\")\n # add CAPE data\n self.add_data(Cape, \"CAPE\")\n \n # # Present Social Media Stocks:\n # self._symbols.append(\"FB\"), self._symbols.append(\"LNKD\"),self._symbols.append(\"GRPN\"), self._symbols.append(\"TWTR\")\n # self.set_start_date(2011, 1, 1)\n # self.set_end_date(2014, 12, 1)\n \n # # 2008 Financials\n # self._symbols.append(\"C\"), self._symbols.append(\"AIG\"), self._symbols.append(\"BAC\"), self._symbols.append(\"HBOS\")\n # self.set_start_date(2003, 1, 1)\n # self.set_end_date(2011, 1, 1)\n \n # # 2000 Dot.com\n # self._symbols.append(\"IPET\"), self._symbols.append(\"WBVN\"), self._symbols.append(\"GCTY\")\n # self.set_start_date(1998, 1, 1)\n # self.set_end_date(2000, 1, 1)\n \n \n for stock in self._symbols:\n self.add_security(SecurityType.EQUITY, stock, Resolution.MINUTE)\n self._macd = self.macd(stock, 12, 26, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY)\n self._macd_dic[stock] = self._macd\n self._rsi = self.rsi(stock, 14, MovingAverageType.EXPONENTIAL, Resolution.DAILY)\n self._rsi_dic[stock] = self._rsi\n \n # Trying to find if current Cape is the lowest Cape in three months to indicate selling period\n def on_data(self, data):\n \n if self._curr_cape and self._new_low is not None: \n try:\n # Bubble territory\n if self._curr_cape > 20 and self._new_low == False:\n for stock in self._symbols:\n # Order stock based on MACD\n # During market hours, stock is trading, and sufficient cash\n if self.securities[stock].holdings.quantity == 0 and self._rsi_dic[stock].current.value < 70 \\\n and self.securities[stock].price != 0 \\\n and self.portfolio.cash > self.securities[stock].price * 100 \\\n and self.time.hour == 9 and self.time.minute == 31:\n self.buy_stock(stock)\n # Utilize RSI for overbought territories and liquidate that stock\n if self._rsi_dic[stock].current.value > 70 and self.securities[stock].holdings.quantity > 0 \\\n and self.time.hour == 9 and self.time.minute == 31:\n self.sell_stock(stock)\n \n # Undervalued territory \n elif self._new_low:\n for stock in self._symbols:\n # Sell stock based on MACD\n if self.securities[stock].holdings.quantity > 0 and self._rsi_dic[stock].current.value > 30 \\\n and self.time.hour == 9 and self.time.minute == 31:\n self.sell_stock(stock)\n # Utilize RSI and MACD to understand oversold territories\n elif self.securities[stock].holdings.quantity == 0 and self._rsi_dic[stock].current.value < 30 \\\n and self.securities[stock].price != 0 and self.portfolio.cash > self.securities[stock].price * 100 \\\n and self.time.hour == 9 and self.time.minute == 31:\n self.buy_stock(stock)\n \n # Cape Ratio is missing from original data\n # Most recent cape data is most likely to be missing \n elif self._curr_cape == 0:\n self.debug(\"Exiting due to no CAPE!\")\n self.quit(\"CAPE ratio not supplied in data, exiting.\")\n \n except:\n # Do nothing\n return None \n\n if not data.contains_key(\"CAPE\"): return\n self._new_low = False\n # Adds first four Cape Ratios to array c\n self._curr_cape = data[\"CAPE\"].cape\n if self._counter < 4:\n self._c[self._counter] = self._curr_cape\n self._counter +=1\n # Replaces oldest Cape with current Cape\n # Checks to see if current Cape is lowest in the previous quarter\n # Indicating a sell off\n else:\n self._c_copy = self._c \n self._c_copy = np.sort(self._c_copy)\n if self._c_copy[0] > self._curr_cape:\n self._new_low = True\n self._c[self._counter2] = self._curr_cape\n self._counter2 += 1\n if self._counter2 == 4: self._counter2 = 0\n self.debug(\"Current Cape: \" + str(self._curr_cape) + \" on \" + str(self.time))\n if self._new_low:\n self.debug(\"New Low has been hit on \" + str(self.time))\n\n # Buy this symbol\n def buy_stock(self,symbol):\n s = self.securities[symbol].holdings\n if self._macd_dic[symbol].current.value>0:\n self.set_holdings(symbol, 1)\n self.debug(\"Purchasing: \" + str(symbol) + \" MACD: \" + str(self._macd_dic[symbol]) + \" RSI: \" + str(self._rsi_dic[symbol])\n + \" Price: \" + str(round(self.securities[symbol].price, 2)) + \" Quantity: \" + str(s.quantity))\n\n # Sell this symbol\n def sell_stock(self,symbol):\n s = self.securities[symbol].holdings\n if s.quantity > 0 and self._macd_dic[symbol].current.value < 0:\n self.liquidate(symbol)\n self.debug(\"Selling: \" + str(symbol) + \" at sell MACD: \" + str(self._macd_dic[symbol]) + \" RSI: \" + str(self._rsi_dic[symbol])\n + \" Price: \" + str(round(self.securities[symbol].price, 2)) + \" Profit from sale: \" + str(s.last_trade_profit))\n\n\n# CAPE Ratio for SP500 PE Ratio for avg inflation adjusted earnings for previous ten years Custom Data from DropBox\n# Original Data from: http://www.econ.yale.edu/~shiller/data.htm\nclass Cape(PythonData):\n \n # Return the URL string source of the file. This will be converted to a stream\n # Configuration object\n # Date of this source file\n # true if we're in live mode, false for backtesting mode\n # String URL of source file.\n\n def get_source(self, config, date, is_live_mode):\n # Remember to add the \"?dl=1\" for dropbox links\n return SubscriptionDataSource(\"https://www.dropbox.com/s/ggt6blmib54q36e/CAPE.csv?dl=1\", SubscriptionTransportMedium.REMOTE_FILE)\n \n \n ''' Reader Method : using set of arguments we specify read out type. Enumerate until \n the end of the data stream or file. E.g. Read CSV file line by line and convert into data types. '''\n \n # BaseData type set by Subscription Method.\n # Config.\n # Line.\n # Date.\n # true if we're in live mode, false for backtesting mode\n \n def reader(self, config, line, date, is_live_mode):\n if not (line.strip() and line[0].isdigit()): return None\n \n # New Nifty object\n index = Cape()\n index.symbol = config.symbol\n \n try:\n # Example File Format:\n # Date | Price | Div | Earning | CPI | FractionalDate | Interest Rate | RealPrice | RealDiv | RealEarnings | CAPE\n # 2014.06 1947.09 37.38 103.12 238.343 2014.37 2.6 1923.95 36.94 101.89 25.55\n data = line.split(',')\n # Dates must be in the format YYYY-MM-DD. If your data source does not have this format, you must use\n # DateTime.parse_exact() and explicit declare the format your data source has.\n index.time = datetime.strptime(data[0], \"%Y-%m\")\n index[\"Cape\"] = float(data[10]) \n index.value = data[10]\n \n \n except ValueError:\n # Do nothing\n return None\n \n return index\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to add futures for a given underlying asset.\nIt also shows how you can prefilter contracts easily based on expirations, and how you\ncan inspect the futures chain to pick a specific contract to trade.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateFuturesAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 8)\n self.set_end_date(2013, 10, 10)\n self.set_cash(1000000)\n\n self.contract_symbol = None\n\n # Subscribe and set our expiry filter for the futures chain\n futureSP500 = self.add_future(Futures.Indices.SP_500_E_MINI)\n future_gold = self.add_future(Futures.Metals.GOLD)\n\n # set our expiry filter for this futures chain\n # SetFilter method accepts timedelta objects or integer for days.\n # The following statements yield the same filtering criteria\n futureSP500.set_filter(timedelta(0), timedelta(182))\n future_gold.set_filter(0, 182)\n\n benchmark = self.add_equity(\"SPY\")\n self.set_benchmark(benchmark.symbol)\n\n seeder = FuncSecuritySeeder(self.get_last_known_prices)\n self.set_security_initializer(lambda security: seeder.seed_security(security))\n\n def on_data(self,slice):\n if not self.portfolio.invested:\n for chain in slice.future_chains:\n # Get contracts expiring no earlier than in 90 days\n contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))\n\n # if there is any contract, trade the front contract\n if len(contracts) == 0: continue\n front = sorted(contracts, key = lambda x: x.expiry, reverse=True)[0]\n\n self.contract_symbol = front.symbol\n self.market_order(front.symbol , 1)\n else:\n self.liquidate()\n\n def on_end_of_algorithm(self):\n # Get the margin requirements\n buying_power_model = self.securities[self.contract_symbol].buying_power_model\n name = type(buying_power_model).__name__\n if name != 'FutureMarginModel':\n raise AssertionError(f\"Invalid buying power model. Found: {name}. Expected: FutureMarginModel\")\n\n initial_overnight = buying_power_model.initial_overnight_margin_requirement\n maintenance_overnight = buying_power_model.maintenance_overnight_margin_requirement\n initial_intraday = buying_power_model.initial_intraday_margin_requirement\n maintenance_intraday = buying_power_model.maintenance_intraday_margin_requirement\n\n def on_securities_changed(self, changes):\n for added_security in changes.added_securities:\n if added_security.symbol.security_type == SecurityType.FUTURE and not added_security.symbol.is_canonical() and not added_security.has_data:\n raise AssertionError(f\"Future contracts did not work up as expected: {added_security.symbol}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Example algorithm using and asserting the behavior of auxiliary data handlers", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AuxiliaryDataHandlersRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n self.set_start_date(2007, 5, 16)\n self.set_end_date(2015, 1, 1)\n\n self.universe_settings.resolution = Resolution.DAILY\n\n # will get delisted\n self.add_equity(\"AAA.1\")\n\n # get's remapped\n self.add_equity(\"SPWR\")\n\n # has a split & dividends\n self.add_equity(\"AAPL\")\n\n def on_delistings(self, delistings: Delistings):\n self._on_delistings_called = True\n\n def on_symbol_changed_events(self, symbolsChanged: SymbolChangedEvents):\n self._on_symbol_changed_events = True\n\n def on_splits(self, splits: Splits):\n self._on_splits = True\n\n def on_dividends(self, dividends: Dividends):\n self._on_dividends = True\n\n def on_end_of_algorithm(self):\n if not self._on_delistings_called:\n raise ValueError(\"OnDelistings was not called!\")\n if not self._on_symbol_changed_events:\n raise ValueError(\"OnSymbolChangedEvents was not called!\")\n if not self._on_splits:\n raise ValueError(\"OnSplits was not called!\")\n if not self._on_dividends:\n raise ValueError(\"OnDividends was not called!\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting slice.get() works for both the alpha and the algorithm", "output": "```python\n\n\nfrom AlgorithmImports import *\n\ntrade_flag = False\n\nclass SliceGetByTypeRegressionAlgorithm(QCAlgorithm):\n def initialize(self) -> None:\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n\n self.add_equity(\"SPY\", Resolution.MINUTE)\n self.set_alpha(TestAlphaModel())\n\n def on_data(self, data: Slice) -> None:\n if \"SPY\" in data:\n tb = data.get(TradeBar)[\"SPY\"]\n global trade_flag\n if not self.portfolio.invested and trade_flag:\n self.set_holdings(\"SPY\", 1)\n\nclass TestAlphaModel(AlphaModel):\n def update(self, algorithm: QCAlgorithm, data: Slice) -> list[Insight]:\n insights = []\n\n if \"SPY\" in data:\n tb = data.get(TradeBar)[\"SPY\"]\n global trade_flag\n trade_flag = True\n\n return insights\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm illustrating how to request history data for continuous contracts with different depth offsets.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 6)\n self.set_end_date(2014, 1, 1)\n self._continuous_contract_symbol = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.DAILY).symbol\n\n def on_end_of_algorithm(self):\n contract_depth_offsets = range(3)\n history_results = [\n self.history([self._continuous_contract_symbol], self.start_date, self.end_date, Resolution.DAILY, contract_depth_offset=contract_depth_offset)\n .droplevel(0, axis=0)\n .loc[self._continuous_contract_symbol]\n .close\n for contract_depth_offset in contract_depth_offsets\n ]\n\n if any(x.size == 0 or x.size != history_results[0].size for x in history_results):\n raise AssertionError(\"History results are empty or bar counts did not match\")\n\n # Check that prices at each time are different for different contract depth offsets\n for j in range(history_results[0].size):\n close_prices = set(history_results[i][j] for i in range(len(history_results)))\n if len(close_prices) != len(contract_depth_offsets):\n raise AssertionError(\"History results close prices should have been different for each data mapping mode at each time\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm testing portfolio construction model control over rebalancing,\nspecifying a date rules, see GH 4075.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass PortfolioRebalanceOnDateRulesRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.universe_settings.resolution = Resolution.DAILY\n\n # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.\n # Commented so regression algorithm is more sensitive\n #self.settings.minimum_order_margin_portfolio_percentage = 0.005\n\n # let's use 0 minimum order margin percentage so we can assert trades are only submitted immediately after rebalance on Wednesday\n # if not, due to TPV variations happening every day we might no cross the minimum on wednesday but yes another day of the week\n self.settings.minimum_order_margin_portfolio_percentage = 0\n\n self.set_start_date(2015,1,1)\n self.set_end_date(2017,1,1)\n\n self.settings.rebalance_portfolio_on_insight_changes = False\n self.settings.rebalance_portfolio_on_security_changes = False\n\n self.set_universe_selection(CustomUniverseSelectionModel(\"CustomUniverseSelectionModel\", lambda time: [ \"AAPL\", \"IBM\", \"FB\", \"SPY\" ]))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, TimeSpan.from_minutes(20), 0.025, None))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(self.date_rules.every(DayOfWeek.WEDNESDAY)))\n self.set_execution(ImmediateExecutionModel())\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.SUBMITTED:\n self.debug(str(order_event))\n if self.utc_time.weekday() != 2:\n raise ValueError(str(self.utc_time) + \" \" + str(order_event.symbol) + \" \" + str(self.utc_time.weekday()))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of how to initialize and use the Classic RenkoConsolidator", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ClassicRenkoConsolidatorAlgorithm(QCAlgorithm):\n '''Demonstration of how to initialize and use the RenkoConsolidator'''\n\n def initialize(self) -> None:\n self.set_start_date(2012, 1, 1)\n self.set_end_date(2013, 1, 1)\n\n self.add_equity(\"SPY\", Resolution.DAILY)\n\n # this is the simple constructor that will perform the\n # renko logic to the Value property of the data it receives.\n\n # break SPY into $2.5 renko bricks and send that data to our 'OnRenkoBar' method\n renko_close = ClassicRenkoConsolidator(2.5)\n renko_close.data_consolidated += self.handle_renko_close\n self.subscription_manager.add_consolidator(\"SPY\", renko_close)\n\n # this is the full constructor that can accept a value selector and a volume selector\n # this allows us to perform the renko logic on values other than Close, even computed values!\n\n # break SPY into (2*o + h + l + 3*c)/7\n renko7bar = ClassicRenkoConsolidator(2.5, lambda x: (2 * x.open + x.high + x.low + 3 * x.close) / 7, lambda x: x.volume)\n renko7bar.data_consolidated += self.handle_renko7_bar\n self.subscription_manager.add_consolidator(\"SPY\", renko7bar)\n\n\n # We're doing our analysis in the on_renko_bar method, but the framework verifies that this method exists, so we define it.\n def on_data(self, data: Slice) -> None:\n pass\n\n\n def handle_renko_close(self, sender: object, data: RenkoBar) -> None:\n '''This function is called by our renko_close consolidator defined in Initialize()\n Args:\n data: The new renko bar produced by the consolidator'''\n if not self.portfolio.invested:\n self.set_holdings(data.symbol, 1)\n\n self.log(f\"CLOSE - {data.time} - {data.open} {data.close}\")\n\n\n def handle_renko7_bar(self, sender: object, data: RenkoBar) -> None:\n '''This function is called by our renko7bar consolidator defined in Initialize()\n Args:\n data: The new renko bar produced by the consolidator'''\n if self.portfolio.invested:\n self.liquidate(data.symbol)\n self.log(f\"7BAR - {data.time} - {data.open} {data.close}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm demonstrate how to use Option Strategies (e.g. OptionStrategies.STRADDLE) helper classes to batch send orders for common strategies.\nIt also shows how you can prefilter contracts easily based on strikes and expirations, and how you can inspect the\noption chain to pick a specific option contract to trade.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateOptionStrategyAlgorithm(QCAlgorithm):\n\n def initialize(self):\n # Set the cash we'd like to use for our backtest\n self.set_cash(1000000)\n\n # Start and end dates for the backtest.\n self.set_start_date(2015,12,24)\n self.set_end_date(2015,12,24)\n\n # Add assets you'd like to see\n option = self.add_option(\"GOOG\")\n self.option_symbol = option.symbol\n\n # set our strike/expiry filter for this option chain\n # SetFilter method accepts timedelta objects or integer for days.\n # The following statements yield the same filtering criteria\n option.set_filter(-2, +2, 0, 180)\n # option.set_filter(-2,2, timedelta(0), timedelta(180))\n\n # use the underlying equity as the benchmark\n self.set_benchmark(\"GOOG\")\n\n def on_data(self,slice):\n if not self.portfolio.invested:\n for kvp in slice.option_chains:\n chain = kvp.value\n contracts = sorted(sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike)),\n key = lambda x: x.expiry, reverse=False)\n\n if len(contracts) == 0: continue\n atm_straddle = contracts[0]\n if atm_straddle != None:\n self.sell(OptionStrategies.straddle(self.option_symbol, atm_straddle.strike, atm_straddle.expiry), 2)\n else:\n self.liquidate()\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to test we can liquidate our portfolio holdings using order properties", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CanLiquidateWithOrderPropertiesRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2014, 6, 5)\n self.set_end_date(2014, 6, 6)\n self.set_cash(100000)\n \n self.open_exchange = datetime(2014, 6, 6, 10, 0, 0)\n self.close_exchange = datetime(2014, 6, 6, 16, 0, 0)\n self.add_equity(\"AAPL\", resolution = Resolution.MINUTE)\n \n def on_data(self, slice):\n if self.time > self.open_exchange and self.time < self.close_exchange:\n if not self.portfolio.invested:\n self.market_order(\"AAPL\", 10)\n else:\n order_properties = OrderProperties()\n order_properties.time_in_force = TimeInForce.DAY\n tickets = self.liquidate(asynchronous = True, order_properties = order_properties)\n for ticket in tickets:\n if ticket.submit_request.order_properties.time_in_force != TimeInForce.DAY:\n raise AssertionError(f\"The TimeInForce for all orders should be daily, but it was {ticket.submit_request.order_properties.time_in_force}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression test to demonstrate importing and trading on custom data.", "output": "```python\n\n\nimport json\nfrom AlgorithmImports import *\n\nclass CustomDataRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n self.set_start_date(2020,1,5) # Set Start Date\n self.set_end_date(2020,1,10) # Set End Date\n self.set_cash(100000) # Set Strategy Cash\n\n resolution = Resolution.SECOND if self.live_mode else Resolution.DAILY\n self.add_data(Bitcoin, \"BTC\", resolution)\n\n seeder = FuncSecuritySeeder(self.get_last_known_prices)\n self.set_security_initializer(lambda x: seeder.seed_security(x))\n self._warmed_up_checked = False\n\n def on_data(self, data: Slice) -> None:\n if not self.portfolio.invested:\n if data['BTC'].close != 0 :\n self.order('BTC', self.portfolio.margin_remaining/abs(data['BTC'].close + 1))\n\n def on_securities_changed(self, changes: SecurityChanges) -> None:\n changes.filter_custom_securities = False\n for added_security in changes.added_securities:\n if added_security.symbol.value == \"BTC\":\n self._warmed_up_checked = True\n if not added_security.has_data:\n raise ValueError(f\"Security {added_security.symbol} was not warmed up!\")\n\n def on_end_of_algorithm(self) -> None:\n if not self._warmed_up_checked:\n raise ValueError(\"Security was not warmed up!\")\n\nclass Bitcoin(PythonData):\n '''Custom Data Type: Bitcoin data from Quandl - https://data.nasdaq.com/databases/BCHAIN'''\n\n def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:\n if is_live_mode:\n return SubscriptionDataSource(\"https://www.bitstamp.net/api/ticker/\", SubscriptionTransportMedium.REST)\n\n #return \"http://my-ftp-server.com/futures-data-\" + date.to_string(\"Ymd\") + \".zip\"\n # OR simply return a fixed small data file. Large files will slow down your backtest\n subscription = SubscriptionDataSource(\"https://www.quantconnect.com/api/v2/proxy/nasdaq/api/v3/datatables/QDL/BITFINEX.csv?code=BTCUSD&api_key=WyAazVXnq7ATy_fefTqm\")\n subscription.sort = True\n return subscription\n\n def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData:\n coin = Bitcoin()\n coin.symbol = config.symbol\n\n if is_live_mode:\n # Example Line Format:\n # {\"high\": \"441.00\", \"last\": \"421.86\", \"timestamp\": \"1411606877\", \"bid\": \"421.96\", \"vwap\": \"428.58\", \"volume\": \"14120.40683975\", \"low\": \"418.83\", \"ask\": \"421.99\"}\n try:\n live_btc = json.loads(line)\n\n # If value is zero, return coin\n value = live_btc[\"last\"]\n if value == 0:\n return coin\n\n coin.time = datetime.now()\n coin.value = value\n coin[\"Open\"] = float(live_btc[\"open\"])\n coin[\"High\"] = float(live_btc[\"high\"])\n coin[\"Low\"] = float(live_btc[\"low\"])\n coin[\"Close\"] = float(live_btc[\"last\"])\n coin[\"Ask\"] = float(live_btc[\"ask\"])\n coin[\"Bid\"] = float(live_btc[\"bid\"])\n coin[\"VolumeBTC\"] = float(live_btc[\"volume\"])\n coin[\"WeightedPrice\"] = float(live_btc[\"vwap\"])\n return coin\n except ValueError:\n # Do nothing, possible error in json decoding\n return coin\n\n # Example Line Format:\n # code date high low mid last bid ask volume\n # BTCUSD 2024-10-08 63248.0 61940.0 62246.5 62245.0 62246.0 62247.0 477.91102114\n if not (line.strip() and line[7].isdigit()): return coin\n\n try:\n data = line.split(',')\n coin.time = datetime.strptime(data[1], \"%Y-%m-%d\")\n coin.end_time = coin.time + timedelta(days=1)\n coin.value = float(data[5])\n coin[\"High\"] = float(data[2])\n coin[\"Low\"] = float(data[3])\n coin[\"Mid\"] = float(data[4])\n coin[\"Close\"] = float(data[5])\n coin[\"Bid\"] = float(data[6])\n coin[\"Ask\"] = float(data[7])\n coin[\"VolumeBTC\"] = float(data[8])\n return coin\n\n except ValueError:\n # Do nothing, possible error in json decoding\n return coin\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to demonstrate the use of SetBenchmark() with custom data", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomDataBenchmarkRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2017, 8, 18) # Set Start Date\n self.set_end_date(2017, 8, 21) # Set End Date\n self.set_cash(100000) # Set Strategy Cash\n\n self.add_equity(\"SPY\", Resolution.HOUR)\n # Load benchmark data\n self.custom_symbol = self.add_data(ExampleCustomData, \"ExampleCustomData\", Resolution.HOUR).symbol\n self.set_benchmark(self.custom_symbol)\n\n def on_data(self, data):\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n\n def on_end_of_algorithm(self):\n security_benchmark = self.benchmark\n if security_benchmark.security.price == 0:\n raise AssertionError(\"Security benchmark price was not expected to be zero\")\n\nclass ExampleCustomData(PythonData):\n\n def get_source(self, config, date, is_live):\n source = \"https://www.dl.dropboxusercontent.com/s/d83xvd7mm9fzpk0/path_to_my_csv_data.csv?dl=0\"\n return SubscriptionDataSource(source, SubscriptionTransportMedium.REMOTE_FILE)\n\n def reader(self, config, line, date, is_live):\n data = line.split(',')\n obj_data = ExampleCustomData()\n obj_data.symbol = config.symbol\n obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S') + timedelta(hours=20)\n obj_data.value = float(data[4])\n obj_data[\"Open\"] = float(data[1])\n obj_data[\"High\"] = float(data[2])\n obj_data[\"Low\"] = float(data[3])\n obj_data[\"Close\"] = float(data[4])\n return obj_data\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm is expected to stop executing after Initialization. Related to GH 6168 issue", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass QuitAfterInitializationRegressionAlgorithm(QCAlgorithm):\n '''Basic template algorithm simply initializes the date range and cash'''\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n self.add_equity(\"SPY\", Resolution.DAILY)\n self._stopped = False\n\n def on_data(self, data):\n '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if self._stopped:\n raise ValueError(\"Algorithm should of stopped!\")\n self._stopped = True\n self.quit()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Minute resolution regression algorithm trading Coin and USDT binance futures long and short asserting the behavior", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateCryptoFutureAlgorithm(QCAlgorithm):\n # \n # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.\n # \n\n def initialize(self):\n self.set_start_date(2022, 12, 13)\n self.set_end_date(2022, 12, 13)\n\n self.set_time_zone(TimeZones.UTC)\n\n try:\n self.set_brokerage_model(BrokerageName.BINANCE_FUTURES, AccountType.CASH)\n except:\n # expected, we don't allow cash account type\n pass\n\n self.set_brokerage_model(BrokerageName.BINANCE_FUTURES, AccountType.MARGIN)\n\n self.btc_usd = self.add_crypto_future(\"BTCUSD\")\n self.ada_usdt = self.add_crypto_future(\"ADAUSDT\")\n\n self.fast = self.ema(self.btc_usd.symbol, 30, Resolution.MINUTE)\n self.slow = self.ema(self.btc_usd.symbol, 60, Resolution.MINUTE)\n\n self.interest_per_symbol = {self.btc_usd.symbol: 0, self.ada_usdt.symbol: 0}\n\n self.set_cash(1000000)\n\n # the amount of BTC we need to hold to trade 'BTCUSD'\n self.btc_usd.base_currency.set_amount(0.005)\n # the amount of USDT we need to hold to trade 'ADAUSDT'\n self.ada_usdt.quote_currency.set_amount(200)\n\n # \n # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n # \n # Slice object keyed by symbol containing the stock data\n def on_data(self, slice):\n interest_rates = slice.Get(MarginInterestRate)\n for interest_rate in interest_rates:\n self.interest_per_symbol[interest_rate.key] += 1\n self.cached_interest_rate = self.securities[interest_rate.key].cache.get_data(MarginInterestRate)\n if self.cached_interest_rate != interest_rate.value:\n raise AssertionError(f\"Unexpected cached margin interest rate for {interest_rate.key}!\")\n \n if self.fast > self.slow:\n if self.portfolio.invested == False and self.transactions.orders_count == 0:\n self.ticket = self.buy(self.btc_usd.symbol, 50)\n if self.ticket.status != OrderStatus.INVALID:\n raise AssertionError(f\"Unexpected valid order {self.ticket}, should fail due to margin not sufficient\")\n \n self.buy(self.btc_usd.symbol, 1)\n\n self.margin_used = self.portfolio.total_margin_used\n self.btc_usd_holdings = self.btc_usd.holdings\n # Coin futures value is 100 USD\n self.holdings_value_btc_usd = 100\n\n if abs(self.btc_usd_holdings.total_sale_volume - self.holdings_value_btc_usd) > 1:\n raise AssertionError(f\"Unexpected TotalSaleVolume {self.btc_usd_holdings.total_sale_volume}\")\n \n if abs(self.btc_usd_holdings.absolute_holdings_cost - self.holdings_value_btc_usd) > 1:\n raise AssertionError(f\"Unexpected holdings cost {self.btc_usd_holdings.holdings_cost}\")\n \n # margin used is based on the maintenance rate\n if (abs(self.btc_usd_holdings.absolute_holdings_cost * 0.05 - self.margin_used) > 1) or (BuyingPowerModelExtensions.get_maintenance_margin(self.btc_usd.buying_power_model, self.btc_usd) != self.margin_used):\n raise AssertionError(f\"Unexpected margin used {self.margin_used}\")\n \n self.buy(self.ada_usdt.symbol, 1000)\n\n self.margin_used = self.portfolio.total_margin_used - self.margin_used\n self.ada_usdt_holdings = self.ada_usdt.holdings\n\n # USDT/BUSD futures value is based on it's price\n self.holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 1000\n\n if abs(self.ada_usdt_holdings.total_sale_volume - self.holdings_value_usdt) > 1:\n raise AssertionError(f\"Unexpected TotalSaleVolume {self.ada_usdt_holdings.total_sale_volume}\")\n \n if abs(self.ada_usdt_holdings.absolute_holdings_cost - self.holdings_value_usdt) > 1:\n raise AssertionError(f\"Unexpected holdings cost {self.ada_usdt_holdings.holdings_cost}\")\n \n if (abs(self.ada_usdt_holdings.absolute_holdings_cost * 0.05 - self.margin_used) > 1) or (BuyingPowerModelExtensions.get_maintenance_margin(self.ada_usdt.buying_power_model, self.ada_usdt) != self.margin_used):\n raise AssertionError(f\"Unexpected margin used {self.margin_used}\")\n \n # position just opened should be just spread here\n self.profit = self.portfolio.total_unrealized_profit\n \n if (5 - abs(self.profit)) < 0:\n raise AssertionError(f\"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}\")\n\n if (self.portfolio.total_profit != 0):\n raise AssertionError(f\"Unexpected TotalProfit {self.portfolio.total_profit}\")\n \n else:\n if self.time.hour > 10 and self.transactions.orders_count == 3:\n self.sell(self.btc_usd.symbol, 3)\n self.btc_usd_holdings = self.btc_usd.holdings\n if abs(self.btc_usd_holdings.absolute_holdings_cost - 100 * 2) > 1:\n raise AssertionError(f\"Unexpected holdings cost {self.btc_usd_holdings.holdings_cost}\")\n\n self.sell(self.ada_usdt.symbol, 3000)\n ada_usdt_holdings = self.ada_usdt.holdings\n\n # USDT/BUSD futures value is based on it's price\n holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 2000\n\n if abs(ada_usdt_holdings.absolute_holdings_cost - holdings_value_usdt) > 1:\n raise AssertionError(f\"Unexpected holdings cost {ada_usdt_holdings.holdings_cost}\")\n\n # position just opened should be just spread here\n profit = self.portfolio.total_unrealized_profit\n if (5 - abs(profit)) < 0:\n raise AssertionError(f\"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}\")\n # we barely did any difference on the previous trade\n if (5 - abs(self.portfolio.total_profit)) < 0:\n raise AssertionError(f\"Unexpected TotalProfit {self.portfolio.total_profit}\")\n\n \n def on_end_of_algorithm(self):\n if self.interest_per_symbol[self.ada_usdt.symbol] != 1:\n raise AssertionError(f\"Unexpected interest rate count {self.interest_per_symbol[self.ada_usdt.symbol]}\")\n if self.interest_per_symbol[self.btc_usd.symbol] != 3:\n raise AssertionError(f\"Unexpected interest rate count {self.interest_per_symbol[self.btc_usd.symbol]}\")\n\n def on_order_event(self, order_event):\n self.debug(\"{0} {1}\".format(self.time, order_event))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm for the SpreadExecutionModel.\nThis algorithm shows how the execution model works to\nsubmit orders only when the price is on desirably tight spread.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Alphas.RsiAlphaModel import RsiAlphaModel\nfrom Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\nfrom Execution.SpreadExecutionModel import SpreadExecutionModel\n\nclass SpreadExecutionModelRegressionAlgorithm(QCAlgorithm):\n '''Regression algorithm for the SpreadExecutionModel.\n This algorithm shows how the execution model works to\n submit orders only when the price is on desirably tight spread.'''\n\n def initialize(self):\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,11)\n\n self.set_universe_selection(ManualUniverseSelectionModel([\n Symbol.create('AIG', SecurityType.EQUITY, Market.USA),\n Symbol.create('BAC', SecurityType.EQUITY, Market.USA),\n Symbol.create('IBM', SecurityType.EQUITY, Market.USA),\n Symbol.create('SPY', SecurityType.EQUITY, Market.USA)\n ]))\n\n # using hourly rsi to generate more insights\n self.set_alpha(RsiAlphaModel(14, Resolution.HOUR))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(SpreadExecutionModel())\n\n self.insights_generated += self.on_insights_generated\n\n def on_insights_generated(self, algorithm, data):\n self.log(f\"{self.time}: {', '.join(str(x) for x in data.insights)}\")\n\n def on_order_event(self, order_event):\n self.log(f\"{self.time}: {order_event}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstrates how to create a custom indicator and register it for automatic updated", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom collections import deque\n\nclass CustomIndicatorAlgorithm(QCAlgorithm):\n def initialize(self) -> None:\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,11)\n self.add_equity(\"SPY\", Resolution.SECOND)\n\n # Create a QuantConnect indicator and a python custom indicator for comparison\n self._sma = self.sma(\"SPY\", 60, Resolution.MINUTE)\n self._custom = CustomSimpleMovingAverage('custom', 60)\n\n # The python custom class must inherit from PythonIndicator to enable Updated event handler\n self._custom.updated += self.custom_updated\n\n self._custom_window = RollingWindow(5)\n self.register_indicator(\"SPY\", self._custom, Resolution.MINUTE)\n self.plot_indicator('CSMA', self._custom)\n\n def custom_updated(self, sender: object, updated: IndicatorDataPoint) -> None:\n self._custom_window.add(updated)\n\n def on_data(self, data: Slice) -> None:\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n\n if self.time.second == 0:\n self.log(f\" sma -> IsReady: {self._sma.is_ready}. Value: {self._sma.current.value}\")\n self.log(f\"custom -> IsReady: {self._custom.is_ready}. Value: {self._custom.value}\")\n\n # Regression test: test fails with an early quit\n diff = abs(self._custom.value - self._sma.current.value)\n if diff > 1e-10:\n self.quit(f\"Quit: indicators difference is {diff}\")\n\n def on_end_of_algorithm(self) -> None:\n for item in self._custom_window:\n self.log(f'{item}')\n\n# Python implementation of SimpleMovingAverage.\n# Represents the traditional simple moving average indicator (SMA).\nclass CustomSimpleMovingAverage(PythonIndicator):\n def __init__(self, name: str, period: int) -> None:\n super().__init__()\n self.name = name\n self.value = 0\n self._queue = deque(maxlen=period)\n\n # Update method is mandatory\n def update(self, input: IndicatorDataPoint) -> bool:\n self._queue.appendleft(input.value)\n count = len(self._queue)\n self.value = np.sum(self._queue) / count\n return count == self._queue.maxlen\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Show cases how to use the CompositeAlphaModel to define.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nfrom Alphas.RsiAlphaModel import RsiAlphaModel\nfrom Alphas.EmaCrossAlphaModel import EmaCrossAlphaModel\nfrom Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\n\nclass CompositeAlphaModelFrameworkAlgorithm(QCAlgorithm):\n '''Show cases how to use the CompositeAlphaModel to define.'''\n\n def initialize(self):\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n # even though we're using a framework algorithm, we can still add our securities\n # using the AddEquity/Forex/Crypto/ect methods and then pass them into a manual\n # universe selection model using securities.keys()\n self.add_equity(\"SPY\")\n self.add_equity(\"IBM\")\n self.add_equity(\"BAC\")\n self.add_equity(\"AIG\")\n\n # define a manual universe of all the securities we manually registered\n self.set_universe_selection(ManualUniverseSelectionModel())\n\n # define alpha model as a composite of the rsi and ema cross models\n self.set_alpha(CompositeAlphaModel(RsiAlphaModel(), EmaCrossAlphaModel()))\n\n # default models for the rest\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(NullRiskManagementModel())\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm for the VolumeWeightedAveragePriceExecutionModel.\nThis algorithm shows how the execution model works to split up orders and\nsubmit them only when the price is on the favorable side of the intraday VWAP.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Alphas.RsiAlphaModel import RsiAlphaModel\nfrom Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\nfrom Execution.VolumeWeightedAveragePriceExecutionModel import VolumeWeightedAveragePriceExecutionModel\n\nclass VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm(QCAlgorithm):\n '''Regression algorithm for the VolumeWeightedAveragePriceExecutionModel.\n This algorithm shows how the execution model works to split up orders and\n submit them only when the price is on the favorable side of the intraday VWAP.'''\n\n def initialize(self):\n\n self.universe_settings.resolution = Resolution.MINUTE\n\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,11)\n self.set_cash(1000000)\n\n self.set_universe_selection(ManualUniverseSelectionModel([\n Symbol.create('AIG', SecurityType.EQUITY, Market.USA),\n Symbol.create('BAC', SecurityType.EQUITY, Market.USA),\n Symbol.create('IBM', SecurityType.EQUITY, Market.USA),\n Symbol.create('SPY', SecurityType.EQUITY, Market.USA)\n ]))\n\n # using hourly rsi to generate more insights\n self.set_alpha(RsiAlphaModel(14, Resolution.HOUR))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n self.set_execution(VolumeWeightedAveragePriceExecutionModel())\n\n self.insights_generated += self.on_insights_generated\n\n def on_insights_generated(self, algorithm, data):\n self.log(f\"{self.time}: {', '.join(str(x) for x in data.insights)}\")\n\n def on_order_event(self, orderEvent):\n self.log(f\"{self.time}: {orderEvent}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CoarseFundamentalTop3Algorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2014,3,24) #Set Start Date\n self.set_end_date(2014,4,7) #Set End Date\n self.set_cash(50000) #Set Strategy Cash\n\n # what resolution should the data *added* to the universe be?\n self.universe_settings.resolution = Resolution.DAILY\n\n # this add universe method accepts a single parameter that is a function that\n # accepts an IEnumerable and returns IEnumerable\n self.add_universe(self.coarse_selection_function)\n\n self.__number_of_symbols = 3\n self._changes = None\n\n\n # sort the data by daily dollar volume and take the top '__number_of_symbols'\n def coarse_selection_function(self, coarse):\n # sort descending by daily dollar volume\n sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)\n\n # return the symbol objects of the top entries from our sorted collection\n return [ x.symbol for x in sorted_by_dollar_volume[:self.__number_of_symbols] ]\n\n\n def on_data(self, data):\n\n self.log(f\"OnData({self.utc_time}): Keys: {', '.join([key.value for key in data.keys()])}\")\n\n # if we have no changes, do nothing\n if self._changes is None: return\n\n # liquidate removed securities\n for security in self._changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n\n # we want 1/N allocation in each security in our universe\n for security in self._changes.added_securities:\n self.set_holdings(security.symbol, 1 / self.__number_of_symbols)\n\n self._changes = None\n\n\n # this event fires whenever we have changes to our universe\n def on_securities_changed(self, changes):\n self._changes = changes\n self.log(f\"OnSecuritiesChanged({self.utc_time}):: {changes}\")\n\n def on_order_event(self, fill):\n self.log(f\"OnOrderEvent({self.utc_time}):: {fill}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template framework algorithm uses framework components to define the algorithm.\nShows EqualWeightingPortfolioConstructionModel.long_only() application", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nfrom Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\nfrom Execution.ImmediateExecutionModel import ImmediateExecutionModel\nfrom Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel\n\nclass LongOnlyAlphaStreamAlgorithm(QCAlgorithm):\n\n def initialize(self):\n # 1. Required:\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n\n # 2. Required: Alpha Streams Models:\n self.set_brokerage_model(BrokerageName.ALPHA_STREAMS)\n\n # 3. Required: Significant AUM Capacity\n self.set_cash(1000000)\n\n # Only SPY will be traded\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY, PortfolioBias.LONG))\n self.set_execution(ImmediateExecutionModel())\n\n # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.\n # Commented so regression algorithm is more sensitive\n #self.settings.minimum_order_margin_portfolio_percentage = 0.005\n\n # Set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel(\n [Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in [\"SPY\", \"IBM\"]]))\n\n def on_data(self, slice):\n if self.portfolio.invested: return\n\n self.emit_insights(\n [\n Insight.price(\"SPY\", timedelta(1), InsightDirection.UP),\n Insight.price(\"IBM\", timedelta(1), InsightDirection.DOWN)\n ])\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n if self.securities[order_event.symbol].holdings.is_short:\n raise ValueError(\"Invalid position, should not be short\")\n self.debug(order_event)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm demonstrating FOREX asset types and requesting history on them in bulk. As FOREX uses\nQuoteBars you should request slices", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateForexAlgorithm(QCAlgorithm):\n\n def initialize(self):\n # Set the cash we'd like to use for our backtest\n self.set_cash(100000)\n\n # Start and end dates for the backtest.\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n\n # Add FOREX contract you want to trade\n # find available contracts here https://www.quantconnect.com/data#forex/oanda/cfd\n self.add_forex(\"EURUSD\", Resolution.MINUTE)\n self.add_forex(\"GBPUSD\", Resolution.MINUTE)\n self.add_forex(\"EURGBP\", Resolution.MINUTE)\n\n self.history(5, Resolution.DAILY)\n self.history(5, Resolution.HOUR)\n self.history(5, Resolution.MINUTE)\n\n history = self.history(TimeSpan.from_seconds(5), Resolution.SECOND)\n\n for data in sorted(history, key=lambda x: x.time):\n for key in data.keys():\n self.log(str(key.value) + \": \" + str(data.time) + \" > \" + str(data[key].value))\n\n def on_data(self, data):\n # Print to console to verify that data is coming in\n for key in data.keys():\n self.log(str(key.value) + \": \" + str(data.time) + \" > \" + str(data[key].value))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template algorithm that implements a fill model with combo orders\n", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ComboOrdersFillModelAlgorithm(QCAlgorithm):\n '''Basic template algorithm that implements a fill model with combo orders'''\n\n def initialize(self) -> None:\n self.set_start_date(2019, 1, 1)\n self.set_end_date(2019, 1, 20)\n\n self.spy = self.add_equity(\"SPY\", Resolution.HOUR)\n self.ibm = self.add_equity(\"IBM\", Resolution.HOUR)\n\n # Set the fill model\n self.spy.set_fill_model(CustomPartialFillModel())\n self.ibm.set_fill_model(CustomPartialFillModel())\n\n self._order_types = {}\n\n def on_data(self, data: Slice) -> None:\n if not self.portfolio.invested:\n legs = [Leg.create(self.spy.symbol, 1), Leg.create(self.ibm.symbol, -1)]\n self.combo_market_order(legs, 100)\n self.combo_limit_order(legs, 100, round(self.spy.bid_price))\n\n legs = [Leg.create(self.spy.symbol, 1, round(self.spy.bid_price) + 1), Leg.create(self.ibm.symbol, -1, round(self.ibm.bid_price) + 1)]\n self.combo_leg_limit_order(legs, 100)\n\n def on_order_event(self, order_event: OrderEvent) -> None:\n if order_event.status == OrderStatus.FILLED:\n order_type = self.transactions.get_order_by_id(order_event.order_id).type\n if order_type == OrderType.COMBO_MARKET and order_event.absolute_fill_quantity != 50:\n raise AssertionError(f\"The absolute quantity filled for all combo market orders should be 50, but for order {order_event.order_id} was {order_event.absolute_fill_quantity}\")\n elif order_type == OrderType.COMBO_LIMIT and order_event.absolute_fill_quantity != 20:\n raise AssertionError(f\"The absolute quantity filled for all combo limit orders should be 20, but for order {order_event.order_id} was {order_event.absolute_fill_quantity}\")\n elif order_type == OrderType.COMBO_LEG_LIMIT and order_event.absolute_fill_quantity != 10:\n raise AssertionError(f\"The absolute quantity filled for all combo leg limit orders should be 10, but for order {order_event.order_id} was {order_event.absolute_fill_quantity}\")\n\n self._order_types[order_type] = 1\n\n def on_end_of_algorithm(self) -> None:\n if len(self._order_types) != 3:\n raise AssertionError(f\"Just 3 different types of order were submitted in this algorithm, but the amount of order types was {len(self._order_types)}\")\n\n if OrderType.COMBO_MARKET not in self._order_types.keys():\n raise AssertionError(f\"One Combo Market Order should have been submitted but it was not\")\n\n if OrderType.COMBO_LIMIT not in self._order_types.keys():\n raise AssertionError(f\"One Combo Limit Order should have been submitted but it was not\")\n\n if OrderType.COMBO_LEG_LIMIT not in self._order_types.keys():\n raise AssertionError(f\"One Combo Leg Limit Order should have been submitted but it was not\")\n\n\nclass CustomPartialFillModel(FillModel):\n '''Implements a custom fill model that inherit from FillModel. Overrides combo_market_fill, combo_limit_fill and combo_leg_limit_fill\n methods to test FillModelPythonWrapper works as expected'''\n\n def __init__(self) -> None:\n self.absolute_remaining_by_order_id = {}\n\n def fill_orders_partially(self, parameters: FillModelParameters, fills: list[OrderEvent], quantity: int) -> list[OrderEvent]:\n partial_fills = []\n if len(fills) == 0:\n return partial_fills\n\n for kvp, fill in zip(sorted(parameters.securities_for_orders, key=lambda x: x.key.id), fills):\n order = kvp.key\n\n absolute_remaining = self.absolute_remaining_by_order_id.get(order.id, order.absolute_quantity)\n\n # Set the fill amount\n fill.fill_quantity = np.sign(order.quantity) * quantity\n\n if (min(abs(fill.fill_quantity), absolute_remaining) == absolute_remaining):\n fill.fill_quantity = np.sign(order.quantity) * absolute_remaining\n fill.status = OrderStatus.FILLED\n self.absolute_remaining_by_order_id.pop(order.id, None)\n else:\n fill.status = OrderStatus.PARTIALLY_FILLED\n self.absolute_remaining_by_order_id[order.id] = absolute_remaining - abs(fill.fill_quantity)\n price = fill.fill_price\n # self.algorithm.debug(f\"{self.algorithm.time} - Partial Fill - Remaining {self.absolute_remaining_by_order_id[order.id]} Price - {price}\")\n\n partial_fills.append(fill)\n\n return partial_fills\n\n def combo_market_fill(self, order: Order, parameters: FillModelParameters) -> list[OrderEvent]:\n fills = super().combo_market_fill(order, parameters)\n partial_fills = self.fill_orders_partially(parameters, fills, 50)\n return partial_fills\n\n def combo_limit_fill(self, order: Order, parameters: FillModelParameters) -> list[OrderEvent]:\n fills = super().combo_limit_fill(order, parameters)\n partial_fills = self.fill_orders_partially(parameters, fills, 20)\n return partial_fills\n\n def combo_leg_limit_fill(self, order: Order, parameters: FillModelParameters) -> list[OrderEvent]:\n fills = super().combo_leg_limit_fill(order, parameters)\n partial_fills = self.fill_orders_partially(parameters, fills, 10)\n return partial_fills\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This example demonstrates how to add futures for a given underlying asset.\nIt also shows how you can prefilter contracts easily based on expirations, and how you\ncan inspect the futures chain to pick a specific contract to trade.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateFuturesWithExtendedMarketAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 8)\n self.set_end_date(2013, 10, 10)\n self.set_cash(1000000)\n\n self.contract_symbol = None\n\n # Subscribe and set our expiry filter for the futures chain\n self.future_sp500 = self.add_future(Futures.Indices.SP_500_E_MINI, extended_market_hours = True)\n self.future_gold = self.add_future(Futures.Metals.GOLD, extended_market_hours = True)\n\n # set our expiry filter for this futures chain\n # SetFilter method accepts timedelta objects or integer for days.\n # The following statements yield the same filtering criteria\n self.future_sp500.set_filter(timedelta(0), timedelta(182))\n self.future_gold.set_filter(0, 182)\n\n benchmark = self.add_equity(\"SPY\")\n self.set_benchmark(benchmark.symbol)\n\n seeder = FuncSecuritySeeder(self.get_last_known_prices)\n self.set_security_initializer(lambda security: seeder.seed_security(security))\n\n def on_data(self,slice):\n if not self.portfolio.invested:\n for chain in slice.future_chains:\n # Get contracts expiring no earlier than in 90 days\n contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))\n\n # if there is any contract, trade the front contract\n if len(contracts) == 0: continue\n front = sorted(contracts, key = lambda x: x.expiry, reverse=True)[0]\n\n self.contract_symbol = front.symbol\n self.market_order(front.symbol , 1)\n else:\n self.liquidate()\n\n def on_end_of_algorithm(self):\n # Get the margin requirements\n buying_power_model = self.securities[self.contract_symbol].buying_power_model\n name = type(buying_power_model).__name__\n if name != 'FutureMarginModel':\n raise AssertionError(f\"Invalid buying power model. Found: {name}. Expected: FutureMarginModel\")\n\n initial_overnight = buying_power_model.initial_overnight_margin_requirement\n maintenance_overnight = buying_power_model.maintenance_overnight_margin_requirement\n initial_intraday = buying_power_model.initial_intraday_margin_requirement\n maintenance_intraday = buying_power_model.maintenance_intraday_margin_requirement\n\n def on_securities_changed(self, changes):\n for added_security in changes.added_securities:\n if added_security.symbol.security_type == SecurityType.FUTURE and not added_security.symbol.is_canonical() and not added_security.has_data:\n raise AssertionError(f\"Future contracts did not work up as expected: {added_security.symbol}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions in backtesting.\nQuantConnect allows you to model all orders as deeply and accurately as you need.", "output": "```python\n\n\nfrom AlgorithmImports import *\nimport random\n\nclass CustomModelsAlgorithm(QCAlgorithm):\n '''Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions in backtesting.\n QuantConnect allows you to model all orders as deeply and accurately as you need.'''\n\n def initialize(self):\n self.set_start_date(2013,10,1) # Set Start Date\n self.set_end_date(2013,10,31) # Set End Date\n self.security = self.add_equity(\"SPY\", Resolution.HOUR)\n self.spy = self.security.symbol\n\n # set our models\n self.security.set_fee_model(CustomFeeModel(self))\n self.security.set_fill_model(CustomFillModel(self))\n self.security.set_slippage_model(CustomSlippageModel(self))\n self.security.set_buying_power_model(CustomBuyingPowerModel(self))\n\n def on_data(self, data):\n open_orders = self.transactions.get_open_orders(self.spy)\n if len(open_orders) != 0: return\n\n if self.time.day > 10 and self.security.holdings.quantity <= 0:\n quantity = self.calculate_order_quantity(self.spy, .5)\n self.log(f\"MarketOrder: {quantity}\")\n self.market_order(self.spy, quantity, True) # async needed for partial fill market orders\n\n elif self.time.day > 20 and self.security.holdings.quantity >= 0:\n quantity = self.calculate_order_quantity(self.spy, -.5)\n self.log(f\"MarketOrder: {quantity}\")\n self.market_order(self.spy, quantity, True) # async needed for partial fill market orders\n\n# If we want to use methods from other models, you need to inherit from one of them\nclass CustomFillModel(ImmediateFillModel):\n def __init__(self, algorithm):\n super().__init__()\n self.algorithm = algorithm\n self.absolute_remaining_by_order_id = {}\n self.random = Random(387510346)\n\n def market_fill(self, asset, order):\n absolute_remaining = order.absolute_quantity\n\n if order.id in self.absolute_remaining_by_order_id.keys():\n absolute_remaining = self.absolute_remaining_by_order_id[order.id]\n\n fill = super().market_fill(asset, order)\n absolute_fill_quantity = int(min(absolute_remaining, self.random.next(0, 2*int(order.absolute_quantity))))\n fill.fill_quantity = np.sign(order.quantity) * absolute_fill_quantity\n\n if absolute_remaining == absolute_fill_quantity:\n fill.status = OrderStatus.FILLED\n if self.absolute_remaining_by_order_id.get(order.id):\n self.absolute_remaining_by_order_id.pop(order.id)\n else:\n absolute_remaining = absolute_remaining - absolute_fill_quantity\n self.absolute_remaining_by_order_id[order.id] = absolute_remaining\n fill.status = OrderStatus.PARTIALLY_FILLED\n self.algorithm.log(f\"CustomFillModel: {fill}\")\n return fill\n\nclass CustomFeeModel(FeeModel):\n def __init__(self, algorithm):\n super().__init__()\n self.algorithm = algorithm\n\n def get_order_fee(self, parameters):\n # custom fee math\n fee = max(1, parameters.security.price\n * parameters.order.absolute_quantity\n * 0.00001)\n self.algorithm.log(f\"CustomFeeModel: {fee}\")\n return OrderFee(CashAmount(fee, \"USD\"))\n\nclass CustomSlippageModel:\n def __init__(self, algorithm):\n self.algorithm = algorithm\n\n def get_slippage_approximation(self, asset, order):\n # custom slippage math\n slippage = asset.price * 0.0001 * np.log10(2*float(order.absolute_quantity))\n self.algorithm.log(f\"CustomSlippageModel: {slippage}\")\n return slippage\n\nclass CustomBuyingPowerModel(BuyingPowerModel):\n def __init__(self, algorithm):\n super().__init__()\n self.algorithm = algorithm\n\n def has_sufficient_buying_power_for_order(self, parameters):\n # custom behavior: this model will assume that there is always enough buying power\n has_sufficient_buying_power_for_order_result = HasSufficientBuyingPowerForOrderResult(True)\n self.algorithm.log(f\"CustomBuyingPowerModel: {has_sufficient_buying_power_for_order_result.is_sufficient}\")\n return has_sufficient_buying_power_for_order_result\n\n# The simple fill model shows how to implement a simpler version of\n# the most popular order fills: Market, Stop Market and Limit\nclass SimpleCustomFillModel(FillModel):\n def __init__(self):\n super().__init__()\n\n def _create_order_event(self, asset, order):\n utc_time = Extensions.convert_to_utc(asset.local_time, asset.exchange.time_zone)\n return OrderEvent(order, utc_time, OrderFee.ZERO)\n\n def _set_order_event_to_filled(self, fill, fill_price, fill_quantity):\n fill.status = OrderStatus.FILLED\n fill.fill_quantity = fill_quantity\n fill.fill_price = fill_price\n return fill\n\n def _get_trade_bar(self, asset, order_direction):\n trade_bar = asset.cache.get_data(TradeBar)\n if trade_bar: return trade_bar\n\n # Tick-resolution data doesn't have TradeBar, use the asset price\n price = asset.price\n return TradeBar(asset.local_time, asset.symbol, price, price, price, price, 0)\n\n def market_fill(self, asset, order):\n fill = self._create_order_event(asset, order)\n if order.status == OrderStatus.CANCELED: return fill\n\n return self._set_order_event_to_filled(fill,\n asset.cache.ask_price \\\n if order.direction == OrderDirection.BUY else asset.cache.bid_price,\n order.quantity)\n\n def stop_market_fill(self, asset, order):\n fill = self._create_order_event(asset, order)\n if order.status == OrderStatus.CANCELED: return fill\n\n stop_price = order.stop_price\n trade_bar = self._get_trade_bar(asset, order.direction)\n\n if order.direction == OrderDirection.SELL and trade_bar.low < stop_price:\n return self._set_order_event_to_filled(fill, stop_price, order.quantity)\n\n if order.direction == OrderDirection.BUY and trade_bar.high > stop_price:\n return self._set_order_event_to_filled(fill, stop_price, order.quantity)\n\n return fill\n\n def limit_fill(self, asset, order):\n fill = self._create_order_event(asset, order)\n if order.status == OrderStatus.CANCELED: return fill\n\n limit_price = order.limit_price\n trade_bar = self._get_trade_bar(asset, order.direction)\n\n if order.direction == OrderDirection.SELL and trade_bar.high > limit_price:\n return self._set_order_event_to_filled(fill, limit_price, order.quantity)\n\n if order.direction == OrderDirection.BUY and trade_bar.low < limit_price:\n return self._set_order_event_to_filled(fill, limit_price, order.quantity)\n\n return fill\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm asserting that security dynamic properties keep Python references to the Python class they are instances of,\nspecifically when this class is a subclass of a C# class.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom collections import deque\n\nimport numpy as np\n\nclass SecurityDynamicPropertyPythonClassAlgorithm(QCAlgorithm):\n def initialize(self) -> None:\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 7)\n\n self._spy = self.add_equity(\"SPY\", Resolution.MINUTE)\n\n custom_sma = CustomSimpleMovingAverage('custom', 60)\n self._spy.custom_sma = custom_sma\n custom_sma.security = self._spy\n\n self.register_indicator(self._spy.symbol, self._spy.custom_sma, Resolution.MINUTE)\n\n def on_warmup_finished(self) -> None:\n if type(self._spy.custom_sma) != CustomSimpleMovingAverage:\n raise AssertionError(\"spy.custom_sma is not an instance of CustomSimpleMovingAverage\")\n\n if not self._spy.custom_sma.security:\n raise AssertionError(\"spy.custom_sma.security is None\")\n else:\n self.debug(f\"spy.custom_sma.security.symbol: {self._spy.custom_sma.security.symbol}\")\n\n def on_data(self, slice: Slice) -> None:\n if self._spy.custom_sma.is_ready:\n self.debug(f\"CustomSMA: {self._spy.custom_sma.current.value}\")\n\nclass CustomSimpleMovingAverage(PythonIndicator):\n def __init__(self, name: str, period: int) -> None:\n super().__init__()\n self.name = name\n self.value = 0\n self._queue = deque(maxlen=period)\n\n def update(self, input: IndicatorDataPoint) -> bool:\n self._queue.appendleft(input.value)\n count = len(self._queue)\n self.value = np.sum(self._queue) / count\n return count == self._queue.maxlen\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: _valid_order_ticket = None", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MarketOnCloseOrderBufferRegressionAlgorithm(QCAlgorithm):\n _valid_order_ticket = None\n _invalid_order_ticket = None\n\n def initialize(self) -> None:\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,8) #Set End Date\n\n self.add_equity(\"SPY\", Resolution.MINUTE)\n\n def moc_at_post_market():\n self._valid_order_ticket_extended_market_hours = self.market_on_close_order(\"SPY\", 2)\n\n self.schedule.on(self.date_rules.today, self.time_rules.at(17,0), moc_at_post_market)\n \n # Modify our submission buffer time to 10 minutes\n MarketOnCloseOrder.submission_time_buffer = timedelta(minutes=10)\n\n def on_data(self, data: Slice) -> None:\n # Test our ability to submit MarketOnCloseOrders\n # Because we set our buffer to 10 minutes, any order placed\n # before 3:50PM should be accepted, any after marked invalid\n\n # Will not throw an order error and execute\n if self.time.hour == 15 and self.time.minute == 49 and not self._valid_order_ticket:\n self._valid_order_ticket = self.market_on_close_order(\"SPY\", 2)\n\n # Will throw an order error and be marked invalid\n if self.time.hour == 15 and self.time.minute == 51 and not self._invalid_order_ticket:\n self._invalid_order_ticket = self.market_on_close_order(\"SPY\", 2)\n\n def on_end_of_algorithm(self) -> None:\n # Set it back to default for other regressions\n MarketOnCloseOrder.submission_time_buffer = MarketOnCloseOrder.DEFAULT_SUBMISSION_TIME_BUFFER\n\n if self._valid_order_ticket.status != OrderStatus.FILLED:\n raise AssertionError(\"Valid order failed to fill\")\n\n if self._invalid_order_ticket.status != OrderStatus.INVALID:\n raise AssertionError(\"Invalid order was not rejected\")\n\n if self._valid_order_ticket_extended_market_hours.status != OrderStatus.FILLED:\n raise AssertionError(\"Valid order during extended market hours failed to fill\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm for testing that period-based history requests are not allowed with tick resolution", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013, 10, 8)\n self.set_end_date(2013, 10, 9)\n\n spy = self.add_equity(\"SPY\", Resolution.TICK).symbol\n\n # Tick resolution is not allowed for period-based history requests\n self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick](spy, 1),\n \"Tick history call with implicit tick resolution\")\n self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick](spy, 1, Resolution.TICK),\n \"Tick history call with explicit tick resolution\")\n self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick]([spy], 1),\n \"Tick history call with symbol array with implicit tick resolution\")\n self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick]([spy], 1, Resolution.TICK),\n \"Tick history call with symbol array with explicit tick resolution\")\n\n history = self.history[Tick](spy, TimeSpan.from_hours(12))\n # Check whether history has data without enumerating the whole list\n if not any(x for x in history):\n raise AssertionError(\"On history call with implicit tick resolution: history returned no results\")\n\n history = self.history[Tick](spy, TimeSpan.from_hours(12), Resolution.TICK)\n if not any(x for x in history):\n raise AssertionError(\"On history call with explicit tick resolution: history returned no results\")\n\n # We already tested what we wanted to test, we can quit now\n self.quit()\n\n def assert_that_history_throws_for_tick_resolution(self, history_call, history_call_description):\n try:\n history_call()\n raise AssertionError(f\"{history_call_description}: expected an exception to be thrown\")\n except InvalidOperationException:\n # expected\n pass\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Test algorithm using 'AccumulativeInsightPortfolioConstructionModel.py' and 'ConstantAlphaModel'\ngenerating a constant 'Insight'", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AccumulativeInsightPortfolioRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n # Set requested data resolution\n self.universe_settings.resolution = Resolution.MINUTE\n\n self.set_start_date(2013,10,7) #Set Start Date\n self.set_end_date(2013,10,11) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n\n symbols = [ Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA) ]\n\n # set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel(symbols))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, 0.25))\n self.set_portfolio_construction(AccumulativeInsightPortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n\n def on_end_of_algorithm(self):\n # holdings value should be 0.03 - to avoid price fluctuation issue we compare with 0.06 and 0.01\n if (self.portfolio.total_holdings_value > self.portfolio.total_portfolio_value * 0.06\n or self.portfolio.total_holdings_value < self.portfolio.total_portfolio_value * 0.01):\n raise ValueError(\"Unexpected Total Holdings Value: \" + str(self.portfolio.total_holdings_value))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: Regression algorithm to test ImmediateExecutionModel places orders with the\ncorrect quantity (taking into account the fee's) so that the fill quantity\nis the expected one.", "output": "```python\n\n\n# region imports\nfrom AlgorithmImports import *\nfrom Execution.ImmediateExecutionModel import ImmediateExecutionModel\nfrom QuantConnect.Orders import OrderEvent\n# endregion\n\nclass ImmediateExecutionModelWorksWithBinanceFeeModel(QCAlgorithm):\n\n def Initialize(self):\n # *** initial configurations and backtest ***\n self.set_start_date(2022, 12, 13) # Set Start Date\n self.set_end_date(2022, 12, 14) # Set End Date\n self.set_account_currency(\"BUSD\") # Set Account Currency\n self.set_cash(\"BUSD\", 100000, 1) # Set Strategy Cash\n\n self.universe_settings.resolution = Resolution.MINUTE\n\n symbols = [ Symbol.create(\"BTCBUSD\", SecurityType.CRYPTO, Market.BINANCE) ]\n\n # set algorithm framework models\n self.set_universe_selection(ManualUniverseSelectionModel(symbols))\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))\n\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.MINUTE))\n self.set_execution(ImmediateExecutionModel())\n \n \n self.set_brokerage_model(BrokerageName.BINANCE, AccountType.MARGIN)\n \n def on_order_event(self, order_event: OrderEvent) -> None:\n if order_event.status == OrderStatus.FILLED:\n if abs(order_event.quantity - 5.8) > 0.01:\n raise AssertionError(f\"The expected quantity was 5.8 but the quantity from the order was {order_event.quantity}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This algorithm sends a list of portfolio targets to vBsase API", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass VBaseSignalExportDemonstrationAlgorithm(QCAlgorithm):\n\n def initialize(self):\n ''' Initialize the date'''\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n self.set_cash(100000) # Set Strategy Cash\n\n self.vbase_apikey = \"YOUR VBASE API KEY\"\n self.vbase_collection_name = \"YOUR VBASE COLLECTION NAME\"\n\n self._symbols = [\n Symbol.create(\"SPY\", SecurityType.EQUITY, Market.USA)\n ]\n\n for symbol in self._symbols:\n self.add_equity(symbol)\n\n self._sentSignal = False\n self.signal_export.add_signal_export_provider(VBaseSignalExport(self.vbase_apikey, self.vbase_collection_name))\n\n def on_data(self, data):\n if self._sentSignal:\n return\n self._sentSignal = True\n\n self.targets = []\n for symbol in self._symbols:\n self.targets.append(PortfolioTarget(symbol, 0.25))\n self.signal_export.set_target_portfolio(self.targets)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template framework algorithm uses framework components to define the algorithm.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndiaDataRegressionAlgorithm(QCAlgorithm):\n '''Basic template framework algorithm uses framework components to define the algorithm.'''\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n \n self.set_account_currency(\"INR\")\n self.set_start_date(2004, 5, 20)\n self.set_end_date(2016, 7, 26) \n self._mapping_symbol = self.add_equity(\"3MINDIA\", Resolution.DAILY, Market.INDIA).symbol\n self._split_and_dividend_symbol = self.add_equity(\"CCCL\", Resolution.DAILY, Market.INDIA).symbol\n self._received_warning_event = False\n self._received_occurred_event = False\n self._initial_mapping = False\n self._execution_mapping = False\n self.debug(\"numpy test >>> print numpy.pi: \" + str(np.pi))\n\n def on_dividends(self, dividends: Dividends):\n if dividends.contains_key(self._split_and_dividend_symbol):\n dividend = dividends[self._split_and_dividend_symbol]\n if ((self.time.year == 2010 and self.time.month == 6 and self.time.day == 15) and\n (dividend.price != 0.5 or dividend.reference_price != 88.8 or dividend.distribution != 0.5)):\n raise AssertionError(\"Did not receive expected dividend values\")\n\n def on_splits(self, splits: Splits):\n if splits.contains_key(self._split_and_dividend_symbol):\n split = splits[self._split_and_dividend_symbol]\n if split.type == SplitType.WARNING:\n self._received_warning_event = True\n elif split.type == SplitType.SPLIT_OCCURRED:\n self._received_occurred_event = True\n if split.price != 421.0 or split.reference_price != 421.0 or split.split_factor != 0.2:\n raise AssertionError(\"Did not receive expected price values\")\n\n def on_symbol_changed_events(self, symbols_changed: SymbolChangedEvents):\n if symbols_changed.contains_key(self._mapping_symbol):\n mapping_event = [x.value for x in symbols_changed if x.key.security_type == 1][0]\n if self.time.year == 1999 and self.time.month == 1 and self.time.day == 1:\n self._initial_mapping = True\n elif self.time.year == 2004 and self.time.month == 6 and self.time.day == 15:\n if mapping_event.new_symbol == \"3MINDIA\" and mapping_event.old_symbol == \"BIRLA3M\":\n self._execution_mapping = True\n \n def on_end_of_algorithm(self):\n if self._initial_mapping:\n raise AssertionError(\"The ticker generated the initial rename event\")\n\n if not self._execution_mapping:\n raise AssertionError(\"The ticker did not rename throughout the course of its life even though it should have\")\n \n if not self._received_occurred_event:\n raise AssertionError(\"Did not receive expected split event\")\n\n if not self._received_warning_event:\n raise AssertionError(\"Did not receive expected split warning event\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests various overloads of the Consolidate method\nusing RenkoBar, VolumeRenkoBar, and RangeBar types,\nas well as common bars like TradeBar and QuoteBar with a maxCount parameter.\nIt ensures each overload behaves as expected and that the appropriate consolidator instances are correctly created and triggered.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ConsolidateWithSizeAttributeRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 7)\n self.set_cash(100000)\n self.add_equity(\"SPY\", Resolution.MINUTE)\n self.sma_indicators = [\n SimpleMovingAverage(\"RenkoBarSMA\", 10),\n SimpleMovingAverage(\"VolumeRenkoBarSMA\", 10),\n SimpleMovingAverage(\"RangeBarSMA\", 10),\n SimpleMovingAverage(\"TradeBarSMA\", 10),\n SimpleMovingAverage(\"QuoteBarSMA\", 10),\n SimpleMovingAverage(\"BaseDataSMA\", 10)\n ]\n self.consolidators = [\n self.consolidate(RenkoBar, \"SPY\", 0.1, None, lambda bar: self.update_with_renko_bar(bar, 0)),\n self.consolidate(VolumeRenkoBar, \"SPY\", 10000, None, lambda bar: self.update_with_volume_renko_bar(bar, 1)),\n self.consolidate(RangeBar, \"SPY\", 12, None, lambda bar: self.update_with_range_bar(bar, 2)),\n \n # Trade and Quote consolidators with max count\n self.consolidate(TradeBar, \"SPY\", 10, None, lambda bar: self.update_with_trade_bar(bar, 3)),\n self.consolidate(QuoteBar, \"SPY\", 10, None, lambda bar: self.update_with_quote_bar(bar, 4)),\n self.consolidate(BaseData, \"SPY\", 10, None, lambda bar: self.update_with_base_data(bar, 5))\n ]\n \n def update_with_base_data(self, base_data, position):\n self.sma_indicators[position].update(base_data.end_time, base_data.value)\n if type(base_data) != TradeBar:\n raise AssertionError(f\"The type of the bar should be Trade, but was {type(base_data)}\")\n \n def update_with_trade_bar(self, trade_bar, position):\n self.sma_indicators[position].update(trade_bar.end_time, trade_bar.high)\n if type(trade_bar) != TradeBar:\n raise AssertionError(f\"The type of the bar should be Trade, but was {type(trade_bar)}\")\n\n def update_with_quote_bar(self, quote_bar, position):\n self.sma_indicators[position].update(quote_bar.end_time, quote_bar.high)\n if type(quote_bar) != QuoteBar:\n raise AssertionError(f\"The type of the bar should be Quote, but was {type(quote_bar)}\")\n\n def update_with_renko_bar(self, renko_bar, position):\n self.sma_indicators[position].update(renko_bar.end_time, renko_bar.high)\n if type(renko_bar) != RenkoBar:\n raise AssertionError(f\"The type of the bar should be Renko, but was {type(renko_bar)}\")\n\n def update_with_volume_renko_bar(self, volume_renko_bar, position):\n self.sma_indicators[position].update(volume_renko_bar.end_time, volume_renko_bar.high)\n if type(volume_renko_bar) != VolumeRenkoBar:\n raise AssertionError(f\"The type of the bar should be VolumeRenko, but was {type(volume_renko_bar)}\")\n\n def update_with_range_bar(self, range_bar, position):\n self.sma_indicators[position].update(range_bar.end_time, range_bar.high)\n if type(range_bar) != RangeBar:\n raise AssertionError(f\"The type of the bar should be Range, but was {type(range_bar)}\")\n\n def on_end_of_algorithm(self):\n # Verifies that each SMA was updated and is ready, confirming the Consolidate overloads functioned correctly.\n for sma in self.sma_indicators:\n if (sma.samples == 0):\n raise AssertionError(f'The indicator {sma.name} did not receive any updates. This indicates the associated consolidator was not triggered.')\n if (not sma.is_ready):\n raise AssertionError(f'The indicator {sma.name} is not ready. It received only {sma.samples} samples, but requires at least {sma.period} to be ready.')\n \n expected_consolidator_types = [\n RenkoConsolidator,\n VolumeRenkoConsolidator,\n RangeConsolidator,\n TradeBarConsolidator,\n QuoteBarConsolidator,\n BaseDataConsolidator\n ]\n\n for i in range(len(self.consolidators)):\n consolidator = self.consolidators[i]\n if type(consolidator) != expected_consolidator_types[i]:\n raise AssertionError(f\"Expected consolidator type {expected_consolidator_types[i]} but received {type(consolidator)}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests Out of The Money (OTM) index option expiry for calls.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, buy SPX Call Option (expiring OTM)\n - contract expires worthless, not exercised, so never opened a position in the underlying\n\n * Liquidation of worthless SPX call option (expiring OTM)\n\nAdditionally, we test delistings for index options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndexOptionCallOTMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2021, 1, 4)\n self.set_end_date(2021, 1, 31)\n\n self.spx = self.add_index(\"SPX\", Resolution.MINUTE).symbol\n\n # Select a index option call expiring OTM, and adds it to the algorithm.\n self.spx_options = list(self.option_chain(self.spx))\n self.spx_options = [i for i in self.spx_options if i.id.strike_price >= 4250 and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1]\n self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price))[0]\n self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(\n self.spx,\n Market.USA,\n OptionStyle.EUROPEAN,\n OptionRight.CALL,\n 4250,\n datetime(2021, 1, 15)\n )\n\n if self.spx_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(\n self.date_rules.tomorrow,\n self.time_rules.after_market_open(self.spx, 1),\n lambda: self.market_order(self.spx_option, 1)\n )\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2021, 1, 15):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2021, 1, 16):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if order_event.symbol not in self.securities:\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.spx:\n raise AssertionError(\"Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM\")\n\n if security.symbol == self.expected_contract:\n self.assert_index_option_contract_order(order_event, security)\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):\n if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:\n raise AssertionError(f\"No holdings were created for option contract {option.symbol}\")\n if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:\n raise AssertionError(\"Holdings were found after a filled option exercise\")\n if order_event.direction == OrderDirection.SELL and not \"OTM\" in order_event.message:\n raise AssertionError(\"Contract did not expire OTM\")\n if \"Exercise\" in order_event.message:\n raise AssertionError(\"Exercised option, even though it expires OTM\")\n\n ### \n ### Ran at the end of the algorithm to ensure the algorithm has no holdings\n ### \n ### The algorithm has holdings\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to test universe additions and removals with open positions", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass WeeklyUniverseSelectionRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self) -> None:\n self.set_cash(100000)\n self.set_start_date(2013,10,1)\n self.set_end_date(2013,10,31)\n\n self.universe_settings.resolution = Resolution.HOUR\n\n # select IBM once a week, empty universe the other days\n self.add_universe(\"my-custom-universe\", lambda dt: [\"IBM\"] if dt.day % 7 == 0 else [])\n\n def on_data(self, slice: Slice) -> None:\n if not self._changes:\n return\n\n # liquidate removed securities\n for security in self._changes.removed_securities:\n if security.invested:\n self.log(\"{} Liquidate {}\".format(self.time, security.symbol))\n self.liquidate(security.symbol)\n\n # we'll simply go long each security we added to the universe\n for security in self._changes.added_securities:\n if not security.invested:\n self.log(\"{} Buy {}\".format(self.time, security.symbol))\n self.set_holdings(security.symbol, 1)\n\n self._changes = None\n\n def on_securities_changed(self, changes: SecurityChanges) -> None:\n self._changes = changes\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template futures framework algorithm uses framework components\nto define an algorithm that trades futures.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nfrom Alphas.ConstantAlphaModel import ConstantAlphaModel\nfrom Selection.FutureUniverseSelectionModel import FutureUniverseSelectionModel\n\nclass BasicTemplateFuturesFrameworkAlgorithm(QCAlgorithm):\n\n def initialize(self):\n\n self.universe_settings.resolution = Resolution.MINUTE\n self.universe_settings.extended_market_hours = self.get_extended_market_hours()\n\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(100000)\n\n # set framework models\n self.set_universe_selection(FrontMonthFutureUniverseSelectionModel(self.select_future_chain_symbols))\n self.set_alpha(ConstantFutureContractAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))\n self.set_portfolio_construction(SingleSharePortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(NullRiskManagementModel())\n\n\n def select_future_chain_symbols(self, utc_time):\n new_york_time = Extensions.convert_from_utc(utc_time, TimeZones.NEW_YORK)\n if new_york_time.date() < date(2013, 10, 9):\n return [ Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME) ]\n else:\n return [ Symbol.create(Futures.Metals.GOLD, SecurityType.FUTURE, Market.COMEX) ]\n\n def get_extended_market_hours(self):\n return False\n\nclass FrontMonthFutureUniverseSelectionModel(FutureUniverseSelectionModel):\n '''Creates futures chain universes that select the front month contract and runs a user\n defined future_chain_symbol_selector every day to enable choosing different futures chains'''\n def __init__(self, select_future_chain_symbols):\n super().__init__(timedelta(1), select_future_chain_symbols)\n\n def filter(self, filter):\n '''Defines the futures chain universe filter'''\n return (filter.front_month()\n .only_apply_filter_at_market_open())\n\nclass ConstantFutureContractAlphaModel(ConstantAlphaModel):\n '''Implementation of a constant alpha model that only emits insights for future symbols'''\n def __init__(self, _type, direction, period):\n super().__init__(_type, direction, period)\n\n def should_emit_insight(self, utc_time, symbol):\n # only emit alpha for future symbols and not underlying equity symbols\n if symbol.security_type != SecurityType.FUTURE:\n return False\n\n return super().should_emit_insight(utc_time, symbol)\n\nclass SingleSharePortfolioConstructionModel(PortfolioConstructionModel):\n '''Portfolio construction model that sets target quantities to 1 for up insights and -1 for down insights'''\n def create_targets(self, algorithm, insights):\n targets = []\n for insight in insights:\n targets.append(PortfolioTarget(insight.symbol, insight.direction))\n return targets\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of using custom margin interest rate model in backtesting.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomMarginInterestRateModelAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013, 10, 1)\n self.set_end_date(2013, 10, 31)\n\n security = self.add_equity(\"SPY\", Resolution.HOUR)\n self._spy = security.symbol\n\n # set the margin interest rate model\n self._margin_interest_rate_model = CustomMarginInterestRateModel()\n security.set_margin_interest_rate_model(self._margin_interest_rate_model)\n\n self._cash_after_order = 0\n\n def on_data(self, data: Slice):\n if not self.portfolio.invested:\n self.set_holdings(self._spy, 1)\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status == OrderStatus.FILLED:\n self._cash_after_order = self.portfolio.cash\n\n def on_end_of_algorithm(self):\n if self._margin_interest_rate_model.call_count == 0:\n raise AssertionError(\"CustomMarginInterestRateModel was not called\")\n\n expected_cash = self._cash_after_order * pow(1 + self._margin_interest_rate_model.interest_rate, self._margin_interest_rate_model.call_count)\n\n if abs(self.portfolio.cash - expected_cash) > 1e-10:\n raise AssertionError(f\"Expected cash {expected_cash} but got {self.portfolio.cash}\")\n\n\nclass CustomMarginInterestRateModel:\n def __init__(self):\n self.interest_rate = 0.01\n self.call_count = 0\n\n def apply_margin_interest_rate(self, parameters: MarginInterestRateParameters):\n security = parameters.security\n position_value = security.holdings.get_quantity_value(security.holdings.quantity)\n\n if position_value.amount > 0:\n position_value.cash.add_amount(self.interest_rate * position_value.cash.amount)\n self.call_count += 1\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm that asserts Stochastic indicator, registered with a different resolution consolidator,\nis warmed up properly by calling QCAlgorithm.WarmUpIndicator", "output": "```python\n\n\nfrom datetime import timedelta\nfrom AlgorithmImports import *\n\nclass StochasticIndicatorWarmsUpProperlyRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2020, 1, 1) # monday = holiday..\n self.set_end_date(2020, 2, 1)\n self.set_cash(100000)\n\n self.data_points_received = False\n self.spy = self.add_equity(\"SPY\", Resolution.HOUR).symbol\n\n self.daily_consolidator = TradeBarConsolidator(timedelta(days=1))\n\n self._rsi = RelativeStrengthIndex(14, MovingAverageType.WILDERS)\n self._sto = Stochastic(\"FIRST\", 10, 3, 3)\n self.register_indicator(self.spy, self._rsi, self.daily_consolidator)\n self.register_indicator(self.spy, self._sto, self.daily_consolidator)\n\n # warm_up indicator\n self.warm_up_indicator(self.spy, self._rsi, timedelta(days=1))\n self.warm_up_indicator(self.spy, self._sto, timedelta(days=1))\n \n\n self._rsi_history = RelativeStrengthIndex(14, MovingAverageType.WILDERS)\n self._sto_history = Stochastic(\"SECOND\", 10, 3, 3)\n self.register_indicator(self.spy, self._rsi_history, self.daily_consolidator)\n self.register_indicator(self.spy, self._sto_history, self.daily_consolidator)\n\n # history warm up\n history = self.history[TradeBar](self.spy, max(self._rsi_history.warm_up_period, self._sto_history.warm_up_period), Resolution.DAILY)\n for bar in history:\n self._rsi_history.update(bar.end_time, bar.close)\n if self._rsi_history.samples == 1:\n continue\n self._sto_history.update(bar)\n\n indicators = [self._rsi, self._sto, self._rsi_history, self._sto_history]\n for indicator in indicators:\n if not indicator.is_ready:\n raise AssertionError(f\"{indicator.name} should be ready, but it is not. Number of samples: {indicator.samples}\")\n\n def on_data(self, data: Slice):\n if self.is_warming_up:\n return\n\n if data.contains_key(self.spy):\n self.data_points_received = True\n if self._rsi.current.value != self._rsi_history.current.value:\n raise AssertionError(f\"Values of indicators differ: {self._rsi.name}: {self._rsi.current.value} | {self._rsi_history.name}: {self._rsi_history.current.value}\")\n \n if self._sto.stoch_k.current.value != self._sto_history.stoch_k.current.value:\n raise AssertionError(f\"Stoch K values of indicators differ: {self._sto.name}.StochK: {self._sto.stoch_k.current.value} | {self._sto_history.name}.StochK: {self._sto_history.stoch_k.current.value}\")\n \n if self._sto.stoch_d.current.value != self._sto_history.stoch_d.current.value:\n raise AssertionError(f\"Stoch D values of indicators differ: {self._sto.name}.StochD: {self._sto.stoch_d.current.value} | {self._sto_history.name}.StochD: {self._sto_history.stoch_d.current.value}\")\n\n def on_end_of_algorithm(self):\n if not self.data_points_received:\n raise AssertionError(\"No data points received\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template algorithm that implements a fill model with partial fills\n", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomPartialFillModelAlgorithm(QCAlgorithm):\n '''Basic template algorithm that implements a fill model with partial fills'''\n\n def initialize(self):\n self.set_start_date(2019, 1, 1)\n self.set_end_date(2019, 3, 1)\n\n equity = self.add_equity(\"SPY\", Resolution.HOUR)\n self.spy = equity.symbol\n self.holdings = equity.holdings\n\n # Set the fill model\n equity.set_fill_model(CustomPartialFillModel(self))\n\n\n def on_data(self, data):\n open_orders = self.transactions.get_open_orders(self.spy)\n if len(open_orders) != 0: return\n\n if self.time.day > 10 and self.holdings.quantity <= 0:\n self.market_order(self.spy, 105, True)\n\n elif self.time.day > 20 and self.holdings.quantity >= 0:\n self.market_order(self.spy, -100, True)\n\n\nclass CustomPartialFillModel(FillModel):\n '''Implements a custom fill model that inherit from FillModel. Override the MarketFill method to simulate partially fill orders'''\n\n def __init__(self, algorithm):\n self.algorithm = algorithm\n self.absolute_remaining_by_order_id = {}\n\n def market_fill(self, asset, order):\n absolute_remaining = self.absolute_remaining_by_order_id.get(order.id, order. AbsoluteQuantity)\n\n # Create the object\n fill = super().market_fill(asset, order)\n\n # Set the fill amount\n fill.fill_quantity = np.sign(order.quantity) * 10\n\n if (min(abs(fill.fill_quantity), absolute_remaining) == absolute_remaining):\n fill.fill_quantity = np.sign(order.quantity) * absolute_remaining\n fill.status = OrderStatus.FILLED\n self.absolute_remaining_by_order_id.pop(order.id, None)\n else:\n fill.status = OrderStatus.PARTIALLY_FILLED\n self.absolute_remaining_by_order_id[order.id] = absolute_remaining - abs(fill.fill_quantity)\n price = fill.fill_price\n # self.algorithm.debug(f\"{self.algorithm.time} - Partial Fill - Remaining {self.absolute_remaining_by_order_id[order.id]} Price - {price}\")\n\n return fill\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests Out of The Money (OTM) future option expiry for short puts.\nWe expect 2 orders from the algorithm, which are:\n\n * Initial entry, sell ES Put Option (expiring OTM)\n - Profit the option premium, since the option was not assigned.\n\n * Liquidation of ES put OTM contract on the last trade date\n\nAdditionally, we test delistings for future options and assert that our\nportfolio holdings reflect the orders the algorithm has submitted.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FutureOptionShortPutOTMExpiryRegressionAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2020, 1, 5)\n self.set_end_date(2020, 6, 30)\n\n self.es19m20 = self.add_future_contract(\n Symbol.create_future(\n Futures.Indices.SP_500_E_MINI,\n Market.CME,\n datetime(2020, 6, 19)),\n Resolution.MINUTE).symbol\n\n # Select a future option expiring ITM, and adds it to the algorithm.\n self.es_option = self.add_future_option_contract(\n list(\n sorted(\n [x for x in self.option_chain(self.es19m20) if x.id.strike_price <= 3000.0 and x.id.option_right == OptionRight.PUT],\n key=lambda x: x.id.strike_price,\n reverse=True\n )\n )[0], Resolution.MINUTE).symbol\n\n self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3000.0, datetime(2020, 6, 19))\n if self.es_option != self.expected_contract:\n raise AssertionError(f\"Contract {self.expected_contract} was not found in the chain\")\n\n self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)\n\n def scheduled_market_order(self):\n self.market_order(self.es_option, -1)\n\n def on_data(self, data: Slice):\n # Assert delistings, so that we can make sure that we receive the delisting warnings at\n # the expected time. These assertions detect bug #4872\n for delisting in data.delistings.values():\n if delisting.type == DelistingType.WARNING:\n if delisting.time != datetime(2020, 6, 19):\n raise AssertionError(f\"Delisting warning issued at unexpected date: {delisting.time}\")\n\n if delisting.type == DelistingType.DELISTED:\n if delisting.time != datetime(2020, 6, 20):\n raise AssertionError(f\"Delisting happened at unexpected date: {delisting.time}\")\n\n def on_order_event(self, order_event: OrderEvent):\n if order_event.status != OrderStatus.FILLED:\n # There's lots of noise with OnOrderEvent, but we're only interested in fills.\n return\n\n if not self.securities.contains_key(order_event.symbol):\n raise AssertionError(f\"Order event Symbol not found in Securities collection: {order_event.symbol}\")\n\n security = self.securities[order_event.symbol]\n if security.symbol == self.es19m20:\n raise AssertionError(f\"Expected no order events for underlying Symbol {security.symbol}\")\n\n if security.symbol == self.expected_contract:\n self.assert_future_option_contract_order(order_event, security)\n\n else:\n raise AssertionError(f\"Received order event for unknown Symbol: {order_event.symbol}\")\n\n self.log(f\"{order_event}\")\n\n def assert_future_option_contract_order(self, order_event: OrderEvent, option_contract: Security):\n if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1:\n raise AssertionError(f\"No holdings were created for option contract {option_contract.symbol}\")\n\n if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:\n raise AssertionError(\"Expected no options holdings after closing position\")\n\n if order_event.is_assignment:\n raise AssertionError(f\"Assignment was not expected for {order_event.symbol}\")\n\n def on_end_of_algorithm(self):\n if self.portfolio.invested:\n raise AssertionError(f\"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: # Keep new created instance of stop_market_order", "output": "```python\n\n\nfrom AlgorithmImports import *\n\n# \n# This example demonstrates how to create future 'stop_market_order' in extended Market Hours time\n# \n\nclass FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm(QCAlgorithm):\n # Keep new created instance of stop_market_order\n _stop_market_ticket = None\n \n # Initialize the Algorithm and Prepare Required Data\n def initialize(self) -> None:\n self.set_start_date(2013, 10, 6)\n self.set_end_date(2013, 10, 12)\n\n # Add mini SP500 future with extended Market hours flag\n self._sp_500_e_mini = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, extended_market_hours=True)\n\n # Init new schedule event with params: every_day, 19:00:00 PM, what should to do\n self.schedule.on(self.date_rules.every_day(),self.time_rules.at(19, 0),self.make_market_and_stop_market_order)\n\n # This method is opened 2 new orders by scheduler\n def make_market_and_stop_market_order(self) -> None:\n # Don't place orders at the end of the last date, the market-on-stop order won't have time to fill\n if self.time.date() == self.end_date.date() - timedelta(1) or not self._sp_500_e_mini.mapped:\n return\n\n self.market_order(self._sp_500_e_mini.mapped, 1)\n self._stop_market_ticket = self.stop_market_order(self._sp_500_e_mini.mapped, -1, self._sp_500_e_mini.price * 1.1)\n\n # New Data Event handler receiving all subscription data in a single event\n def on_data(self, slice: Slice) -> None:\n if (self._stop_market_ticket == None or self._stop_market_ticket.status != OrderStatus.SUBMITTED):\n return None\n\n self.stop_price = self._stop_market_ticket.get(OrderField.STOP_PRICE)\n self.bar = self.securities[self._stop_market_ticket.symbol].cache.get_data()\n\n # An order fill update the resulting information is passed to this method.\n def on_order_event(self, order_event: OrderEvent) -> None:\n if self.transactions.get_order_by_id(order_event.order_id).type is not OrderType.STOP_MARKET:\n return None\n\n if order_event.status == OrderStatus.FILLED:\n # Get Exchange Hours for specific security\n exchange_hours = self.market_hours_database.get_exchange_hours(self._sp_500_e_mini.subscription_data_config)\n\n # Validate, Exchange is opened explicitly\n if (not exchange_hours.is_open(order_event.utc_time, self._sp_500_e_mini.is_extended_market_hours)):\n raise AssertionError(\"The Exchange hours was closed, verify 'extended_market_hours' flag in Initialize() when added new security(ies)\")\n\n def on_end_of_algorithm(self) -> None:\n self.stop_market_orders = self.transactions.get_orders(lambda o: o.type is OrderType.STOP_MARKET)\n\n for o in self.stop_market_orders:\n if o.status != OrderStatus.FILLED:\n raise AssertionError(\"The Algorithms was not handled any StopMarketOrders\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression test for history and warm up using the data available in open source.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass IndicatorWarmupAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013, 10, 8) #Set Start Date\n self.set_end_date(2013, 10, 11) #Set End Date\n self.set_cash(1000000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\")\n self.add_equity(\"IBM\")\n self.add_equity(\"BAC\")\n self.add_equity(\"GOOG\", Resolution.DAILY)\n self.add_equity(\"GOOGL\", Resolution.DAILY)\n\n self.__sd = { }\n for security in self.securities:\n self.__sd[security.key] = self.SymbolData(security.key, self)\n\n # we want to warm up our algorithm\n self.set_warmup(self.SymbolData.REQUIRED_BARS_WARMUP)\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n # we are only using warmup for indicator spooling, so wait for us to be warm then continue\n if self.is_warming_up: return\n\n for sd in self.__sd.values():\n last_price_time = sd.close.current.time\n if self.round_down(last_price_time, sd.security.subscription_data_config.increment):\n sd.update()\n\n def on_order_event(self, fill):\n sd = self.__sd.get(fill.symbol, None)\n if sd is not None:\n sd.on_order_event(fill)\n\n def round_down(self, time, increment):\n if increment.days != 0:\n return time.hour == 0 and time.minute == 0 and time.second == 0\n else:\n return time.second == 0\n\n class SymbolData:\n REQUIRED_BARS_WARMUP = 40\n PERCENT_TOLERANCE = 0.001\n PERCENT_GLOBAL_STOP_LOSS = 0.01\n LOT_SIZE = 10\n\n def __init__(self, symbol, algorithm):\n self.symbol = symbol\n self.__algorithm = algorithm # if we're receiving daily\n\n self.__current_stop_loss = None\n\n self.security = algorithm.securities[symbol]\n self.close = algorithm.identity(symbol)\n self._adx = algorithm.adx(symbol, 14)\n self._ema = algorithm.ema(symbol, 14)\n self._macd = algorithm.macd(symbol, 12, 26, 9)\n\n self.is_ready = self.close.is_ready and self._adx.is_ready and self._ema.is_ready and self._macd.is_ready\n self.is_uptrend = False\n self.is_downtrend = False\n\n def update(self):\n self.is_ready = self.close.is_ready and self._adx.is_ready and self._ema.is_ready and self._macd.is_ready\n\n tolerance = 1 - self.PERCENT_TOLERANCE\n self.is_uptrend = self._macd.signal.current.value > self._macd.current.value * tolerance and\\\n self._ema.current.value > self.close.current.value * tolerance\n\n self.is_downtrend = self._macd.signal.current.value < self._macd.current.value * tolerance and\\\n self._ema.current.value < self.close.current.value * tolerance\n\n self.try_enter()\n self.try_exit()\n\n def try_enter(self):\n # can't enter if we're already in\n if self.security.invested: return False\n\n qty = 0\n limit = 0.0\n\n if self.is_uptrend:\n # 100 order lots\n qty = self.LOT_SIZE\n limit = self.security.low\n elif self.is_downtrend:\n qty = -self.LOT_SIZE\n limit = self.security.high\n\n if qty != 0:\n ticket = self.__algorithm.limit_order(self.symbol, qty, limit, tag=\"TryEnter at: {0}\".format(limit))\n\n def try_exit(self):\n # can't exit if we haven't entered\n if not self.security.invested: return\n\n limit = 0\n qty = self.security.holdings.quantity\n exit_tolerance = 1 + 2 * self.PERCENT_TOLERANCE\n if self.security.holdings.is_long and self.close.current.value * exit_tolerance < self._ema.current.value:\n limit = self.security.high\n elif self.security.holdings.is_short and self.close.current.value > self._ema.current.value * exit_tolerance:\n limit = self.security.low\n\n if limit != 0:\n ticket = self.__algorithm.limit_order(self.symbol, -qty, limit, tag=\"TryExit at: {0}\".format(limit))\n\n def on_order_event(self, fill):\n if fill.status != OrderStatus.FILLED: return\n\n qty = self.security.holdings.quantity\n\n # if we just finished entering, place a stop loss as well\n if self.security.invested:\n stop = fill.fill_price*(1 - self.PERCENT_GLOBAL_STOP_LOSS) if self.security.holdings.is_long \\\n else fill.fill_price*(1 + self.PERCENT_GLOBAL_STOP_LOSS)\n\n self.__current_stop_loss = self.__algorithm.stop_market_order(self.symbol, -qty, stop, tag=\"StopLoss at: {0}\".format(stop))\n\n # check for an exit, cancel the stop loss\n elif (self.__current_stop_loss is not None and self.__current_stop_loss.status is not OrderStatus.FILLED):\n # cancel our current stop loss\n self.__current_stop_loss.cancel(\"Exited position\")\n self.__current_stop_loss = None\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: In this algorithm we demonstrate how to use the coarse fundamental data to define a universe as the top dollar volume and set the algorithm to use raw prices", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass RawPricesCoarseUniverseAlgorithm(QCAlgorithm):\n\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n # what resolution should the data *added* to the universe be?\n self.universe_settings.resolution = Resolution.DAILY\n\n self.set_start_date(2014,1,1) #Set Start Date\n self.set_end_date(2015,1,1) #Set End Date\n self.set_cash(50000) #Set Strategy Cash\n\n # Set the security initializer with the characteristics defined in CustomSecurityInitializer\n self.set_security_initializer(self.custom_security_initializer)\n\n # this add universe method accepts a single parameter that is a function that\n # accepts an IEnumerable and returns IEnumerable\n self.add_universe(self.coarse_selection_function)\n\n self.__number_of_symbols = 5\n\n def custom_security_initializer(self, security):\n '''Initialize the security with raw prices and zero fees \n Args:\n security: Security which characteristics we want to change'''\n security.set_data_normalization_mode(DataNormalizationMode.RAW)\n security.set_fee_model(ConstantFeeModel(0))\n\n # sort the data by daily dollar volume and take the top 'NumberOfSymbols'\n def coarse_selection_function(self, coarse):\n # sort descending by daily dollar volume\n sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)\n\n # return the symbol objects of the top entries from our sorted collection\n return [ x.symbol for x in sorted_by_dollar_volume[:self.__number_of_symbols] ]\n\n\n # this event fires whenever we have changes to our universe\n def on_securities_changed(self, changes):\n # liquidate removed securities\n for security in changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n\n # we want 20% allocation in each security in our universe\n for security in changes.added_securities:\n self.set_holdings(security.symbol, 0.2)\n\n def on_order_event(self, order_event):\n if order_event.status == OrderStatus.FILLED:\n self.log(f\"OnOrderEvent({self.utc_time}):: {order_event}\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm to assert the behavior of .", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm\nfrom Risk.CompositeRiskManagementModel import CompositeRiskManagementModel\nfrom Risk.MaximumDrawdownPercentPortfolio import MaximumDrawdownPercentPortfolio\n\nclass MaximumDrawdownPercentPortfolioFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):\n\n def initialize(self):\n super().initialize()\n self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA)))\n\n # define risk management model as a composite of several risk management models\n self.set_risk_management(CompositeRiskManagementModel(\n MaximumDrawdownPercentPortfolio(0.01), # Avoid loss of initial capital\n MaximumDrawdownPercentPortfolio(0.015, True) # Avoid profit losses\n ))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm for testing ScheduledUniverseSelectionModel scheduling functions.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ScheduledUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):\n '''Regression algorithm for testing ScheduledUniverseSelectionModel scheduling functions.'''\n\n def initialize(self):\n\n self.universe_settings.resolution = Resolution.HOUR\n\n # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.\n # Commented so regression algorithm is more sensitive\n #self.settings.minimum_order_margin_portfolio_percentage = 0.005\n\n self.set_start_date(2017, 1, 1)\n self.set_end_date(2017, 2, 1)\n\n # selection will run on mon/tues/thurs at 00:00/06:00/12:00/18:00\n self.set_universe_selection(ScheduledUniverseSelectionModel(\n self.date_rules.every(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.THURSDAY),\n self.time_rules.every(timedelta(hours = 12)),\n self.select_symbols\n ))\n\n self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n\n # some days of the week have different behavior the first time -- less securities to remove\n self.seen_days = []\n\n def select_symbols(self, dateTime):\n\n symbols = []\n weekday = dateTime.weekday()\n\n if weekday == 0 or weekday == 1:\n symbols.append(Symbol.create('SPY', SecurityType.EQUITY, Market.USA))\n elif weekday == 2:\n # given the date/time rules specified in Initialize, this symbol will never be selected (not invoked on wednesdays)\n symbols.append(Symbol.create('AAPL', SecurityType.EQUITY, Market.USA))\n else:\n symbols.append(Symbol.create('IBM', SecurityType.EQUITY, Market.USA))\n\n if weekday == 1 or weekday == 3:\n symbols.append(Symbol.create('EURUSD', SecurityType.FOREX, Market.OANDA))\n elif weekday == 4:\n # given the date/time rules specified in Initialize, this symbol will never be selected (every 6 hours never lands on hour==1)\n symbols.append(Symbol.create('EURGBP', SecurityType.FOREX, Market.OANDA))\n else:\n symbols.append(Symbol.create('NZDUSD', SecurityType.FOREX, Market.OANDA))\n\n return symbols\n\n def on_securities_changed(self, changes):\n self.log(\"{}: {}\".format(self.time, changes))\n\n weekday = self.time.weekday()\n\n if weekday == 0:\n self.expect_additions(changes, 'SPY', 'NZDUSD')\n if weekday not in self.seen_days:\n self.seen_days.append(weekday)\n self.expect_removals(changes, None)\n else:\n self.expect_removals(changes, 'EURUSD', 'IBM')\n\n if weekday == 1:\n self.expect_additions(changes, 'EURUSD')\n if weekday not in self.seen_days:\n self.seen_days.append(weekday)\n self.expect_removals(changes, 'NZDUSD')\n else:\n self.expect_removals(changes, 'NZDUSD')\n\n if weekday == 2 or weekday == 4:\n # selection function not invoked on wednesdays (2) or friday (4)\n self.expect_additions(changes, None)\n self.expect_removals(changes, None)\n\n if weekday == 3:\n self.expect_additions(changes, \"IBM\")\n self.expect_removals(changes, \"SPY\")\n\n\n def on_order_event(self, orderEvent):\n self.log(\"{}: {}\".format(self.time, orderEvent))\n\n def expect_additions(self, changes, *tickers):\n if tickers is None and changes.added_securities.count > 0:\n raise AssertionError(\"{}: Expected no additions: {}\".format(self.time, self.time.weekday()))\n\n for ticker in tickers:\n if ticker is not None and ticker not in [s.symbol.value for s in changes.added_securities]:\n raise AssertionError(\"{}: Expected {} to be added: {}\".format(self.time, ticker, self.time.weekday()))\n\n def expect_removals(self, changes, *tickers):\n if tickers is None and changes.removed_securities.count > 0:\n raise AssertionError(\"{}: Expected no removals: {}\".format(self.time, self.time.weekday()))\n\n for ticker in tickers:\n if ticker is not None and ticker not in [s.symbol.value for s in changes.removed_securities]:\n raise AssertionError(\"{}: Expected {} to be removed: {}\".format(self.time, ticker, self.time.weekday()))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of requesting daily resolution data for US Equities.\nThis is a simple regression test algorithm using a skeleton algorithm and requesting daily data.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass BasicTemplateDailyAlgorithm(QCAlgorithm):\n '''Basic template algorithm simply initializes the date range and cash'''\n\n def initialize(self):\n '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10,8) #Set Start Date\n self.set_end_date(2013,10,17) #Set End Date\n self.set_cash(100000) #Set Strategy Cash\n # Find more symbols here: http://quantconnect.com/data\n self.add_equity(\"SPY\", Resolution.DAILY)\n\n\n def on_data(self, data):\n '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n\n Arguments:\n data: Slice object keyed by symbol containing the stock data\n '''\n if not self.portfolio.invested:\n self.set_holdings(\"SPY\", 1)\n self.debug(\"Purchased Stock\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Demonstration of the Option Chain Provider -- a much faster mechanism for manually specifying the option contracts you'd like to recieve\ndata for and manually subscribing to them.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\n\nclass OptionChainProviderAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2015, 12, 24)\n self.set_end_date(2015, 12, 24)\n self.set_cash(100000)\n # add the underlying asset\n self.equity = self.add_equity(\"GOOG\", Resolution.MINUTE)\n self.equity.set_data_normalization_mode(DataNormalizationMode.RAW)\n # initialize the option contract with empty string\n self.contract = str()\n self.contracts_added = set()\n\n def on_data(self, data):\n\n if not self.portfolio[self.equity.symbol].invested:\n self.market_order(self.equity.symbol, 100)\n\n if not (self.securities.contains_key(self.contract) and self.portfolio[self.contract].invested):\n self.contract = self.options_filter(data)\n\n if self.securities.contains_key(self.contract) and not self.portfolio[self.contract].invested:\n self.market_order(self.contract, -1)\n\n def options_filter(self, data):\n ''' OptionChainProvider gets a list of option contracts for an underlying symbol at requested date.\n Then you can manually filter the contract list returned by GetOptionContractList.\n The manual filtering will be limited to the information included in the Symbol\n (strike, expiration, type, style) and/or prices from a History call '''\n\n contracts = self.option_chain_provider.get_option_contract_list(self.equity.symbol, data.time)\n self.underlying_price = self.securities[self.equity.symbol].price\n # filter the out-of-money call options from the contract list which expire in 10 to 30 days from now on\n otm_calls = [i for i in contracts if i.id.option_right == OptionRight.CALL and\n i.id.strike_price - self.underlying_price > 0 and\n 10 < (i.id.date - data.time).days < 30]\n if len(otm_calls) > 0:\n contract = sorted(sorted(otm_calls, key = lambda x: x.id.date),\n key = lambda x: x.id.strike_price - self.underlying_price)[0]\n if contract not in self.contracts_added:\n self.contracts_added.add(contract)\n # use AddOptionContract() to subscribe the data for specified contract\n self.add_option_contract(contract, Resolution.MINUTE)\n return contract\n else:\n return str()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This regression algorithm tests option exercise and assignment functionality\nWe open two positions and go with them into expiration. We expect to see our long position exercised and short position assigned.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass OptionExerciseAssignRegressionAlgorithm(QCAlgorithm):\n\n underlying_ticker = \"GOOG\"\n\n def initialize(self):\n self.set_cash(100000)\n self.set_start_date(2015,12,24)\n self.set_end_date(2015,12,28)\n\n self.equity = self.add_equity(self.underlying_ticker)\n self.option = self.add_option(self.underlying_ticker)\n\n # set our strike/expiry filter for this option chain\n self.option.set_filter(self.universe_func)\n\n self.set_benchmark(self.equity.symbol)\n self._assigned_option = False\n\n def on_data(self, slice):\n if self.portfolio.invested: return\n for kvp in slice.option_chains:\n chain = kvp.value\n # find the call options expiring today\n contracts = filter(lambda x:\n x.expiry.date() == self.time.date() and\n x.strike < chain.underlying.price and\n x.right == OptionRight.CALL, chain)\n \n # sorted the contracts by their strikes, find the second strike under market price \n sorted_contracts = sorted(contracts, key = lambda x: x.strike, reverse = True)[:2]\n\n if sorted_contracts:\n self.market_order(sorted_contracts[0].symbol, 1)\n self.market_order(sorted_contracts[1].symbol, -1)\n\n # set our strike/expiry filter for this option chain\n def universe_func(self, universe):\n return universe.include_weeklys().strikes(-2, 2).expiration(timedelta(0), timedelta(10))\n\n def on_order_event(self, order_event):\n self.log(str(order_event))\n\n def on_assignment_order_event(self, assignment_event):\n self.log(str(assignment_event))\n self._assigned_option = True\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Algorithm asserting the correct values for the deployment target and algorithm mode.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass AlgorithmModeAndDeploymentTargetAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n self.set_cash(100000)\n\n #translate commented code from c# to python\n self.debug(f\"Algorithm Mode: {self.algorithm_mode}. Is Live Mode: {self.live_mode}. Deployment Target: {self.deployment_target}.\")\n\n if self.algorithm_mode != AlgorithmMode.BACKTESTING:\n raise AssertionError(f\"Algorithm mode is not backtesting. Actual: {self.algorithm_mode}\")\n\n if self.live_mode:\n raise AssertionError(\"Algorithm should not be live\")\n\n if self.deployment_target != DeploymentTarget.LOCAL_PLATFORM:\n raise AssertionError(f\"Algorithm deployment target is not local. Actual{self.deployment_target}\")\n\n # For a live deployment these checks should pass:\n # if self.algorithm_mode != AlgorithmMode.LIVE: raise AssertionError(\"Algorithm mode is not live\")\n # if not self.live_mode: raise AssertionError(\"Algorithm should be live\")\n\n # For a cloud deployment these checks should pass:\n # if self.deployment_target != DeploymentTarget.CLOUD_PLATFORM: raise AssertionError(\"Algorithm deployment target is not cloud\")\n\n self.quit()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Basic template options framework algorithm uses framework components\nto define an algorithm that trades options.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nfrom Alphas.ConstantAlphaModel import ConstantAlphaModel\nfrom Selection.OptionUniverseSelectionModel import OptionUniverseSelectionModel\nfrom Execution.ImmediateExecutionModel import ImmediateExecutionModel\nfrom Risk.NullRiskManagementModel import NullRiskManagementModel\n\n\nclass BasicTemplateOptionsFrameworkAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.universe_settings.resolution = Resolution.MINUTE\n\n self.set_start_date(2014, 6, 5)\n self.set_end_date(2014, 6, 9)\n self.set_cash(100000)\n\n # set framework models\n self.set_universe_selection(EarliestExpiringWeeklyAtTheMoneyPutOptionUniverseSelectionModel(self.select_option_chain_symbols))\n self.set_alpha(ConstantOptionContractAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(hours = 0.5)))\n self.set_portfolio_construction(SingleSharePortfolioConstructionModel())\n self.set_execution(ImmediateExecutionModel())\n self.set_risk_management(NullRiskManagementModel())\n\n\n def select_option_chain_symbols(self, utc_time):\n new_york_time = Extensions.convert_from_utc(utc_time, TimeZones.NEW_YORK)\n ticker = \"TWX\" if new_york_time.date() < date(2014, 6, 6) else \"AAPL\"\n return [ Symbol.create(ticker, SecurityType.OPTION, Market.USA, f\"?{ticker}\") ]\n\nclass EarliestExpiringWeeklyAtTheMoneyPutOptionUniverseSelectionModel(OptionUniverseSelectionModel):\n '''Creates option chain universes that select only the earliest expiry ATM weekly put contract\n and runs a user defined option_chain_symbol_selector every day to enable choosing different option chains'''\n def __init__(self, select_option_chain_symbols):\n super().__init__(timedelta(1), select_option_chain_symbols)\n\n def filter(self, filter):\n '''Defines the option chain universe filter'''\n return (filter.strikes(+1, +1)\n # Expiration method accepts timedelta objects or integer for days.\n # The following statements yield the same filtering criteria\n .expiration(0, 7)\n # .expiration(timedelta(0), timedelta(7))\n .weeklys_only()\n .puts_only()\n .only_apply_filter_at_market_open())\n\nclass ConstantOptionContractAlphaModel(ConstantAlphaModel):\n '''Implementation of a constant alpha model that only emits insights for option symbols'''\n def __init__(self, type, direction, period):\n super().__init__(type, direction, period)\n\n def should_emit_insight(self, utc_time, symbol):\n # only emit alpha for option symbols and not underlying equity symbols\n if symbol.security_type != SecurityType.OPTION:\n return False\n\n return super().should_emit_insight(utc_time, symbol)\n\nclass SingleSharePortfolioConstructionModel(PortfolioConstructionModel):\n '''Portfolio construction model that sets target quantities to 1 for up insights and -1 for down insights'''\n def create_targets(self, algorithm, insights):\n targets = []\n for insight in insights:\n targets.append(PortfolioTarget(insight.symbol, insight.direction))\n return targets\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Live Trading Functionality Demonstration algorithm including SMS, Email and Web hook notifications.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\n\nclass LiveTradingFeaturesAlgorithm(QCAlgorithm):\n\n ### Initialize the Algorithm and Prepare Required Data\n def initialize(self):\n\n self.set_start_date(2013, 10, 7)\n self.set_end_date(2013, 10, 11)\n self.set_cash(25000)\n\n ##Equity Data for US Markets\n self.add_security(SecurityType.EQUITY, 'IBM', Resolution.SECOND)\n\n ##FOREX Data for Weekends: 24/6\n self.add_security(SecurityType.FOREX, 'EURUSD', Resolution.MINUTE)\n\n ##Custom/Bitcoin Live Data: 24/7\n self.add_data(Bitcoin, 'BTC', Resolution.SECOND, TimeZones.UTC)\n\n ##if the algorithm is connected to the brokerage\n self.is_connected = True\n\n ### Raises the data event\n def on_data(self, data):\n if (not self.portfolio['IBM'].hold_stock) and data.contains_key('IBM'):\n quantity = int(np.floor(self.portfolio.margin_remaining / data['IBM'].close))\n self.market_order('IBM',quantity)\n self.debug('Purchased IBM on ' + str(self.time.strftime(\"%m/%d/%Y\")))\n self.notify.email(\"myemail@gmail.com\", \"Test\", \"Test Body\", \"test attachment\")\n\n if \"BTC\" in data:\n btcData = data['BTC']\n if self.live_mode:\n self.set_runtime_statistic('BTC', str(btcData.close))\n\n if not self.portfolio.hold_stock:\n self.market_order('BTC', 100)\n\n ##Send a notification email/SMS/web request on events:\n self.notify.email(\"myemail@gmail.com\", \"Test\", \"Test Body\", \"test attachment\")\n self.notify.sms(\"+11233456789\", str(btcData.time) + \">> Test message from live BTC server.\")\n self.notify.web(\"http://api.quantconnect.com\", str(btcData.time) + \">> Test data packet posted from live BTC server.\")\n self.notify.ftp(\"ftp.quantconnect.com\", \"username\", \"password\", \"path/to/file.txt\",\n str(btcData.time) + \">> Test file from live BTC server.\")\n self.notify.sftp(\"ftp.quantconnect.com\", \"username\", \"password\", \"path/to/file.txt\",\n str(btcData.time) + \">> Test file from live BTC server.\")\n self.notify.sftp(\"ftp.quantconnect.com\", \"username\", \"privatekey\", \"optionalprivatekeypassphrase\", \"path/to/file.txt\",\n str(btcData.time) + \">> Test file from live BTC server.\")\n\n # Brokerage message event handler. This method is called for all types of brokerage messages.\n def on_brokerage_message(self, message_event):\n self.debug(f\"Brokerage meesage received - {message_event.to_string()}\")\n\n # Brokerage disconnected event handler. This method is called when the brokerage connection is lost.\n def on_brokerage_disconnect(self):\n self.is_connected = False\n self.debug(f\"Brokerage disconnected!\")\n\n # Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.\n def on_brokerage_reconnect(self):\n self.is_connected = True\n self.debug(f\"Brokerage reconnected!\")\n\nclass Bitcoin(PythonData):\n\n def get_source(self, config, date, is_live_mode):\n if is_live_mode:\n return SubscriptionDataSource(\"https://www.bitstamp.net/api/ticker/\", SubscriptionTransportMedium.REST)\n\n return SubscriptionDataSource(\"https://www.quandl.com/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc\", SubscriptionTransportMedium.REMOTE_FILE)\n\n\n def reader(self, config, line, date, is_live_mode):\n coin = Bitcoin()\n coin.symbol = config.symbol\n\n if is_live_mode:\n # Example Line Format:\n # {\"high\": \"441.00\", \"last\": \"421.86\", \"timestamp\": \"1411606877\", \"bid\": \"421.96\", \"vwap\": \"428.58\", \"volume\": \"14120.40683975\", \"low\": \"418.83\", \"ask\": \"421.99\"}\n try:\n live_btc = json.loads(line)\n\n # If value is zero, return None\n value = live_btc[\"last\"]\n if value == 0: return None\n\n coin.time = datetime.now()\n coin.value = value\n coin[\"Open\"] = float(live_btc[\"open\"])\n coin[\"High\"] = float(live_btc[\"high\"])\n coin[\"Low\"] = float(live_btc[\"low\"])\n coin[\"Close\"] = float(live_btc[\"last\"])\n coin[\"Ask\"] = float(live_btc[\"ask\"])\n coin[\"Bid\"] = float(live_btc[\"bid\"])\n coin[\"VolumeBTC\"] = float(live_btc[\"volume\"])\n coin[\"WeightedPrice\"] = float(live_btc[\"vwap\"])\n return coin\n except ValueError:\n # Do nothing, possible error in json decoding\n return None\n\n # Example Line Format:\n # Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price\n # 2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356\n if not (line.strip() and line[0].isdigit()): return None\n\n try:\n data = line.split(',')\n coin.time = datetime.strptime(data[0], \"%Y-%m-%d\")\n coin.value = float(data[4])\n coin[\"Open\"] = float(data[1])\n coin[\"High\"] = float(data[2])\n coin[\"Low\"] = float(data[3])\n coin[\"Close\"] = float(data[4])\n coin[\"VolumeBTC\"] = float(data[5])\n coin[\"VolumeUSD\"] = float(data[6])\n coin[\"WeightedPrice\"] = float(data[7])\n return coin\n\n except ValueError:\n # Do nothing, possible error in json decoding\n return None\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Tests a custom filter function when creating an ETF constituents universe for SPY", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ETFConstituentUniverseFilterFunctionRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_start_date(2020, 12, 1)\n self.set_end_date(2021, 1, 31)\n self.set_cash(100000)\n\n self.filtered = False\n self.securities_changed = False\n self.received_data = False\n self.etf_constituent_data = {}\n self.etf_rebalanced = False\n self.rebalance_count = 0\n self.rebalance_asset_count = 0\n\n self.universe_settings.resolution = Resolution.HOUR\n\n self.spy = self.add_equity(\"SPY\", Resolution.HOUR).symbol\n self.aapl = Symbol.create(\"AAPL\", SecurityType.EQUITY, Market.USA)\n\n self.add_universe(self.universe.etf(self.spy, self.universe_settings, self.filter_etfs))\n\n def filter_etfs(self, constituents):\n constituents_data = list(constituents)\n constituents_symbols = [i.symbol for i in constituents_data]\n self.etf_constituent_data = {i.symbol: i for i in constituents_data}\n\n if len(constituents_data) == 0:\n raise AssertionError(f\"Constituents collection is empty on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')}\")\n if self.aapl not in constituents_symbols:\n raise AssertionError(\"AAPL is not int he constituents data provided to the algorithm\")\n\n aapl_data = [i for i in constituents_data if i.symbol == self.aapl][0]\n if aapl_data.weight == 0.0:\n raise AssertionError(\"AAPL weight is expected to be a non-zero value\")\n\n self.filtered = True\n self.etf_rebalanced = True\n\n return constituents_symbols\n\n def on_data(self, data):\n if not self.filtered and len(data.bars) != 0 and self.aapl in data.bars:\n raise AssertionError(\"AAPL TradeBar data added to algorithm before constituent universe selection took place\")\n\n if len(data.bars) == 1 and self.spy in data.bars:\n return\n\n if len(data.bars) != 0 and self.aapl not in data.bars:\n raise AssertionError(f\"Expected AAPL TradeBar data on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')}\")\n\n self.received_data = True\n\n if not self.etf_rebalanced:\n return\n\n for bar in data.bars.values():\n constituent_data = self.etf_constituent_data.get(bar.symbol)\n if constituent_data is not None and constituent_data.weight is not None and constituent_data.weight >= 0.0001:\n # If the weight of the constituent is less than 1%, then it will be set to 1%\n # If the weight of the constituent exceeds more than 5%, then it will be capped to 5%\n # Otherwise, if the weight falls in between, then we use that value.\n bounded_weight = max(0.01, min(constituent_data.weight, 0.05))\n\n self.set_holdings(bar.symbol, bounded_weight)\n\n if self.etf_rebalanced:\n self.rebalance_count += 1\n\n self.etf_rebalanced = False\n self.rebalance_asset_count += 1\n\n\n def on_securities_changed(self, changes):\n if self.filtered and not self.securities_changed and len(changes.added_securities) < 500:\n raise AssertionError(f\"Added SPY S&P 500 ETF to algorithm, but less than 500 equities were loaded (added {len(changes.added_securities)} securities)\")\n\n self.securities_changed = True\n\n def on_end_of_algorithm(self):\n if self.rebalance_count != 2:\n raise AssertionError(f\"Expected 2 rebalance, instead rebalanced: {self.rebalance_count}\")\n\n if self.rebalance_asset_count != 8:\n raise AssertionError(f\"Invested in {self.rebalance_asset_count} assets (expected 8)\")\n\n if not self.filtered:\n raise AssertionError(\"Universe selection was never triggered\")\n\n if not self.securities_changed:\n raise AssertionError(\"Security changes never propagated to the algorithm\")\n\n if not self.received_data:\n raise AssertionError(\"Data was never loaded for the S&P 500 constituent AAPL\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Provides an example where WarmUpIndicator method is used to warm up indicators", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass SmaCrossUniverseSelectionAlgorithm(QCAlgorithm):\n '''Provides an example where WarmUpIndicator method is used to warm up indicators\n after their security is added and before (Universe Selection scenario)'''\n\n _count = 10\n _tolerance = 0.01\n _target_percent = 1 / _count\n _averages = dict()\n\n def initialize(self) -> None:\n self.universe_settings.leverage = 2\n self.universe_settings.resolution = Resolution.DAILY\n\n self.set_start_date(2018, 1, 1)\n self.set_end_date(2019, 1, 1)\n self.set_cash(1000000)\n\n self.settings.automatic_indicator_warm_up = True\n\n ibm = self.add_equity(\"IBM\", Resolution.HOUR).symbol\n ibm_sma = self.sma(ibm, 40)\n self.log(f\"{ibm_sma.name}: {ibm_sma.current.time} - {ibm_sma}. IsReady? {ibm_sma.is_ready}\")\n\n spy = self.add_equity(\"SPY\", Resolution.HOUR).symbol\n spy_sma = self.sma(spy, 10) # Data point indicator\n spy_atr = self.atr(spy, 10,) # Bar indicator\n spy_vwap = self.vwap(spy, 10) # TradeBar indicator\n self.log(f\"SPY - Is ready? SMA: {spy_sma.is_ready}, ATR: {spy_atr.is_ready}, VWAP: {spy_vwap.is_ready}\")\n\n eur = self.add_forex(\"EURUSD\", Resolution.HOUR).symbol\n eur_sma = self.sma(eur, 20, Resolution.DAILY)\n eur_atr = self.atr(eur, 20, MovingAverageType.SIMPLE, Resolution.DAILY)\n self.log(f\"EURUSD - Is ready? SMA: {eur_sma.is_ready}, ATR: {eur_atr.is_ready}\")\n\n self.add_universe(self.coarse_sma_selector)\n\n # Since the indicators are ready, we will receive error messages\n # reporting that the algorithm manager is trying to add old information\n self.set_warm_up(10)\n\n def coarse_sma_selector(self, coarse: list[Fundamental]) -> list[Symbol]:\n score = dict()\n for cf in coarse:\n if not cf.has_fundamental_data:\n continue\n symbol = cf.symbol\n price = cf.adjusted_price\n # grab the SMA instance for this symbol\n avg = self._averages.setdefault(symbol, SimpleMovingAverage(100))\n self.warm_up_indicator(symbol, avg, Resolution.DAILY)\n # Update returns true when the indicators are ready, so don't accept until they are\n if avg.update(cf.end_time, price):\n value = avg.current.value\n # only pick symbols who have their price over their 100 day sma\n if value > price * self._tolerance:\n score[symbol] = (value - price) / ((value + price) / 2)\n\n # prefer symbols with a larger delta by percentage between the two _averages\n sorted_score = sorted(score.items(), key=lambda kvp: kvp[1], reverse=True)\n return [x[0] for x in sorted_score[:self._count]]\n\n def on_securities_changed(self, changes: SecurityChanges) -> None:\n for security in changes.removed_securities:\n if security.invested:\n self.liquidate(security.symbol)\n\n for security in changes.added_securities:\n self.set_holdings(security.symbol, self._target_percent)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm asserting we can specify a custom security data filter", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomSecurityDataFilterRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n self.set_cash(2500000)\n self.set_start_date(2013,10,7)\n self.set_end_date(2013,10,7)\n\n security = self.add_security(SecurityType.EQUITY, \"SPY\")\n security.set_data_filter(CustomDataFilter())\n self.data_points = 0\n\n def on_data(self, data):\n self.data_points += 1\n self.set_holdings(\"SPY\", 0.2)\n if self.data_points > 5:\n raise AssertionError(\"There should not be more than 5 data points, but there were \" + str(self.data_points))\n\n\nclass CustomDataFilter(SecurityDataFilter):\n def filter(self, vehicle: Security, data: BaseData) -> bool:\n \"\"\"\n Skip data after 9:35am\n \"\"\"\n if data.time >= datetime(2013,10,7,9,35,0):\n return False\n else:\n return True\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: This demonstration imports indian NSE index \"NIFTY\" as a tradable security in addition to the USDINR currency pair. We move into the\nNSE market when the economy is performing well.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass CustomDataNIFTYAlgorithm(QCAlgorithm):\n\n def initialize(self):\n self.set_start_date(2008, 1, 8)\n self.set_end_date(2014, 7, 25)\n self.set_cash(100000)\n\n # Define the symbol and \"type\" of our generic data:\n rupee = self.add_data(DollarRupee, \"USDINR\", Resolution.DAILY).symbol\n nifty = self.add_data(Nifty, \"NIFTY\", Resolution.DAILY).symbol\n\n self.settings.automatic_indicator_warm_up = True\n rupee_sma = self.sma(rupee, 20)\n nifty_sma = self.sma(rupee, 20)\n self.log(f\"SMA - Is ready? USDINR: {rupee_sma.is_ready} NIFTY: {nifty_sma.is_ready}\")\n\n self.minimum_correlation_history = 50\n self.today = CorrelationPair()\n self.prices = []\n\n\n def on_data(self, data):\n if data.contains_key(\"USDINR\"):\n self.today = CorrelationPair(self.time)\n self.today.currency_price = data[\"USDINR\"].close\n\n if not data.contains_key(\"NIFTY\"): return\n\n self.today.nifty_price = data[\"NIFTY\"].close\n\n if self.today.date() == data[\"NIFTY\"].time.date():\n self.prices.append(self.today)\n if len(self.prices) > self.minimum_correlation_history:\n self.prices.pop(0)\n\n # Strategy\n if self.time.weekday() != 2: return\n\n cur_qnty = self.portfolio[\"NIFTY\"].quantity\n quantity = int(self.portfolio.margin_remaining * 0.9 / data[\"NIFTY\"].close)\n hi_nifty = max(price.nifty_price for price in self.prices)\n lo_nifty = min(price.nifty_price for price in self.prices)\n\n if data[\"NIFTY\"].open >= hi_nifty:\n code = self.order(\"NIFTY\", quantity - cur_qnty)\n self.debug(\"LONG {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}\".format(code, self.time, quantity, self.portfolio[\"NIFTY\"].quantity, data[\"NIFTY\"].close, self.portfolio.total_portfolio_value))\n elif data[\"NIFTY\"].open <= lo_nifty:\n code = self.order(\"NIFTY\", -quantity - cur_qnty)\n self.debug(\"SHORT {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}\".format(code, self.time, quantity, self.portfolio[\"NIFTY\"].quantity, data[\"NIFTY\"].close, self.portfolio.total_portfolio_value))\n\n\nclass Nifty(PythonData):\n '''NIFTY Custom Data Class'''\n def get_source(self, config, date, is_live_mode):\n return SubscriptionDataSource(\"https://www.dropbox.com/s/rsmg44jr6wexn2h/CNXNIFTY.csv?dl=1\", SubscriptionTransportMedium.REMOTE_FILE)\n\n\n def reader(self, config, line, date, is_live_mode):\n if not (line.strip() and line[0].isdigit()): return None\n\n # New Nifty object\n index = Nifty()\n index.symbol = config.symbol\n\n try:\n # Example File Format:\n # Date, Open High Low Close Volume Turnover\n # 2011-09-13 7792.9 7799.9 7722.65 7748.7 116534670 6107.78\n data = line.split(',')\n index.time = datetime.strptime(data[0], \"%Y-%m-%d\")\n index.end_time = index.time + timedelta(days=1)\n index.value = data[4]\n index[\"Open\"] = float(data[1])\n index[\"High\"] = float(data[2])\n index[\"Low\"] = float(data[3])\n index[\"Close\"] = float(data[4])\n\n\n except ValueError:\n # Do nothing\n return None\n\n return index\n\n\nclass DollarRupee(PythonData):\n '''Dollar Rupe is a custom data type we create for this algorithm'''\n def get_source(self, config, date, is_live_mode):\n return SubscriptionDataSource(\"https://www.dropbox.com/s/m6ecmkg9aijwzy2/USDINR.csv?dl=1\", SubscriptionTransportMedium.REMOTE_FILE)\n\n def reader(self, config, line, date, is_live_mode):\n if not (line.strip() and line[0].isdigit()): return None\n\n # New USDINR object\n currency = DollarRupee()\n currency.symbol = config.symbol\n\n try:\n data = line.split(',')\n currency.time = datetime.strptime(data[0], \"%Y-%m-%d\")\n currency.end_time = currency.time + timedelta(days=1)\n currency.value = data[1]\n currency[\"Close\"] = float(data[1])\n\n except ValueError:\n # Do nothing\n return None\n\n return currency\n\n\nclass CorrelationPair:\n '''Correlation Pair is a helper class to combine two data points which we'll use to perform the correlation.'''\n def __init__(self, *args):\n self.nifty_price = 0 # Nifty price for this correlation pair\n self.currency_price = 0 # Currency price for this correlation pair\n self._date = datetime.min # Date of the correlation pair\n if len(args) > 0: self._date = args[0]\n\n def date(self):\n return self._date.date()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN Algorithm that can be described like this\n: Regression algorithm show casing ad asserting security to symbol implicit conversion", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass SecurityToSymbolRegressionAlgorithm(QCAlgorithm):\n def initialize(self):\n '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''\n\n self.set_start_date(2013,10, 7)\n self.set_end_date(2013,10,11)\n\n asset = self.add_equity(\"SPY\", Resolution.MINUTE)\n\n self.schedule.on(self.date_rules.every_day(asset), self.time_rules.after_market_open(asset, 1), lambda: None if self.portfolio.invested else self.set_holdings(asset, 1))\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: Alpha Streams: Benchmark Alpha: Pick stocks according to Joel Greenblatt's Magic Formula", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel\n\nfrom math import ceil\nfrom itertools import chain\n\nclass GreenblattMagicFormulaAlpha(QCAlgorithm):\n ''' Alpha Streams: Benchmark Alpha: Pick stocks according to Joel Greenblatt's Magic Formula\n This alpha picks stocks according to Joel Greenblatt's Magic Formula.\n First, each stock is ranked depending on the relative value of the ratio EV/EBITDA. For example, a stock\n that has the lowest EV/EBITDA ratio in the security universe receives a score of one while a stock that has\n the tenth lowest EV/EBITDA score would be assigned 10 points.\n\n Then, each stock is ranked and given a score for the second valuation ratio, Return on Capital (ROC).\n Similarly, a stock that has the highest ROC value in the universe gets one score point.\n The stocks that receive the lowest combined score are chosen for insights.\n\n Source: Greenblatt, J. (2010) The Little Book That Beats the Market\n\n This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open\n sourced so the community and client funds can see an example of an alpha.'''\n\n def initialize(self):\n\n self.set_start_date(2018, 1, 1)\n self.set_cash(100000)\n\n #Set zero transaction fees\n self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))\n\n # select stocks using MagicFormulaUniverseSelectionModel\n self.set_universe_selection(GreenBlattMagicFormulaUniverseSelectionModel())\n\n # Use MagicFormulaAlphaModel to establish insights\n self.set_alpha(RateOfChangeAlphaModel())\n\n # Equally weigh securities in portfolio, based on insights\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n\n ## Set Immediate Execution Model\n self.set_execution(ImmediateExecutionModel())\n\n ## Set Null Risk Management Model\n self.set_risk_management(NullRiskManagementModel())\n\nclass RateOfChangeAlphaModel(AlphaModel):\n '''Uses Rate of Change (ROC) to create magnitude prediction for insights.'''\n\n def __init__(self, *args, **kwargs):\n self.lookback = kwargs.get('lookback', 1)\n self.resolution = kwargs.get('resolution', Resolution.DAILY)\n self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), self.lookback)\n self._symbol_data_by_symbol = {}\n\n def update(self, algorithm, data):\n insights = []\n for symbol, symbol_data in self._symbol_data_by_symbol.items():\n if symbol_data.can_emit:\n insights.append(Insight.price(symbol, self.prediction_interval, InsightDirection.UP, symbol_data.returns, None))\n return insights\n\n def on_securities_changed(self, algorithm, changes):\n\n # clean up data for removed securities\n for removed in changes.removed_securities:\n symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)\n if symbol_data is not None:\n symbol_data.remove_consolidators(algorithm)\n\n # initialize data for added securities\n symbols = [ x.symbol for x in changes.added_securities\n if x.symbol not in self._symbol_data_by_symbol]\n\n history = algorithm.history(symbols, self.lookback, self.resolution)\n if history.empty: return\n\n for symbol in symbols:\n symbol_data = SymbolData(algorithm, symbol, self.lookback, self.resolution)\n self._symbol_data_by_symbol[symbol] = symbol_data\n symbol_data.warm_up_indicators(history.loc[symbol])\n\n\nclass SymbolData:\n '''Contains data specific to a symbol required by this model'''\n def __init__(self, algorithm, symbol, lookback, resolution):\n self.previous = 0\n self._symbol = symbol\n self.roc = RateOfChange(f'{symbol}.roc({lookback})', lookback)\n self.consolidator = algorithm.resolve_consolidator(symbol, resolution)\n algorithm.register_indicator(symbol, self.roc, self.consolidator)\n\n def remove_consolidators(self, algorithm):\n algorithm.subscription_manager.remove_consolidator(self._symbol, self.consolidator)\n\n def warm_up_indicators(self, history):\n for tuple in history.itertuples():\n self.roc.update(tuple.Index, tuple.close)\n\n @property\n def returns(self):\n return self.roc.current.value\n\n @property\n def can_emit(self):\n if self.previous == self.roc.samples:\n return False\n\n self.previous = self.roc.samples\n return self.roc.is_ready\n\n def __str__(self, **kwargs):\n return f'{self.roc.name}: {(1 + self.returns)**252 - 1:.2%}'\n\n\nclass GreenBlattMagicFormulaUniverseSelectionModel(FundamentalUniverseSelectionModel):\n '''Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm.\n From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on Assets (ROA).\n '''\n\n def __init__(self,\n filter_fine_data = True,\n universe_settings = None):\n '''Initializes a new default instance of the MagicFormulaUniverseSelectionModel'''\n super().__init__(filter_fine_data, universe_settings)\n\n # Number of stocks in Coarse Universe\n self.number_of_symbols_coarse = 500\n # Number of sorted stocks in the fine selection subset using the valuation ratio, EV to EBITDA (EV/EBITDA)\n self.number_of_symbols_fine = 20\n # Final number of stocks in security list, after sorted by the valuation ratio, Return on Assets (ROA)\n self.number_of_symbols_in_portfolio = 10\n\n self.last_month = -1\n self.dollar_volume_by_symbol = {}\n\n def select_coarse(self, algorithm, coarse):\n '''Performs coarse selection for constituents.\n The stocks must have fundamental data'''\n month = algorithm.time.month\n if month == self.last_month:\n return Universe.UNCHANGED\n self.last_month = month\n\n # sort the stocks by dollar volume and take the top 1000\n top = sorted([x for x in coarse if x.has_fundamental_data],\n key=lambda x: x.dollar_volume, reverse=True)[:self.number_of_symbols_coarse]\n\n self.dollar_volume_by_symbol = { i.symbol: i.dollar_volume for i in top }\n\n return list(self.dollar_volume_by_symbol.keys())\n\n\n def select_fine(self, algorithm, fine):\n '''QC500: Performs fine selection for the coarse selection constituents\n The company's headquarter must in the U.S.\n The stock must be traded on either the NYSE or NASDAQ\n At least half a year since its initial public offering\n The stock's market cap must be greater than 500 million\n\n Magic Formula: Rank stocks by Enterprise Value to EBITDA (EV/EBITDA)\n Rank subset of previously ranked stocks (EV/EBITDA), using the valuation ratio Return on Assets (ROA)'''\n\n # QC500:\n ## The company's headquarter must in the U.S.\n ## The stock must be traded on either the NYSE or NASDAQ\n ## At least half a year since its initial public offering\n ## The stock's market cap must be greater than 500 million\n filtered_fine = [x for x in fine if x.company_reference.country_id == \"USA\"\n and (x.company_reference.primary_exchange_id == \"NYS\" or x.company_reference.primary_exchange_id == \"NAS\")\n and (algorithm.time - x.security_reference.ipo_date).days > 180\n and x.earning_reports.basic_average_shares.three_months * x.earning_reports.basic_eps.twelve_months * x.valuation_ratios.pe_ratio > 5e8]\n count = len(filtered_fine)\n if count == 0: return []\n\n my_dict = dict()\n percent = self.number_of_symbols_fine / count\n\n # select stocks with top dollar volume in every single sector\n for key in [\"N\", \"M\", \"U\", \"T\", \"B\", \"I\"]:\n value = [x for x in filtered_fine if x.company_reference.industry_template_code == key]\n value = sorted(value, key=lambda x: self.dollar_volume_by_symbol[x.symbol], reverse = True)\n my_dict[key] = value[:ceil(len(value) * percent)]\n\n # stocks in QC500 universe\n top_fine = chain.from_iterable(my_dict.values())\n\n # Magic Formula:\n ## Rank stocks by Enterprise Value to EBITDA (EV/EBITDA)\n ## Rank subset of previously ranked stocks (EV/EBITDA), using the valuation ratio Return on Assets (ROA)\n\n # sort stocks in the security universe of QC500 based on Enterprise Value to EBITDA valuation ratio\n sorted_by_ev_to_ebitda = sorted(top_fine, key=lambda x: x.valuation_ratios.ev_to_ebitda , reverse=True)\n\n # sort subset of stocks that have been sorted by Enterprise Value to EBITDA, based on the valuation ratio Return on Assets (ROA)\n sorted_by_roa = sorted(sorted_by_ev_to_ebitda[:self.number_of_symbols_fine], key=lambda x: x.valuation_ratios.forward_roa, reverse=False)\n\n # retrieve list of securites in portfolio\n return [f.symbol for f in sorted_by_roa[:self.number_of_symbols_in_portfolio]]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: The motivating idea for this Alpha Model is that a large price gap (here we use true outliers --", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass PriceGapMeanReversionAlpha(QCAlgorithm):\n '''The motivating idea for this Alpha Model is that a large price gap (here we use true outliers --\n price gaps that whose absolutely values are greater than 3 * Volatility) is due to rebound\n back to an appropriate price or at least retreat from its brief extreme. Using a Coarse Universe selection\n function, the algorithm selects the top x-companies by Dollar Volume (x can be any number you choose)\n to trade with, and then uses the Standard Deviation of the 100 most-recent closing prices to determine\n which price movements are outliers that warrant emitting insights.\n\n This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open\n sourced so the community and client funds can see an example of an alpha.'''\n\n def initialize(self):\n\n self.set_start_date(2018, 1, 1) #Set Start Date\n self.set_cash(100000) #Set Strategy Cash\n\n ## Initialize variables to be used in controlling frequency of universe selection\n self.week = -1\n\n ## Manual Universe Selection\n self.universe_settings.resolution = Resolution.MINUTE\n self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selection_function))\n\n ## Set trading fees to $0\n self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))\n\n ## Set custom Alpha Model\n self.set_alpha(PriceGapMeanReversionAlphaModel())\n\n ## Set equal-weighting Portfolio Construction Model\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n\n ## Set Execution Model\n self.set_execution(ImmediateExecutionModel())\n\n ## Set Risk Management Model\n self.set_risk_management(NullRiskManagementModel())\n\n\n def coarse_selection_function(self, coarse):\n ## If it isn't a new week, return the same symbols\n current_week = self.time.isocalendar()[1]\n if current_week == self.week:\n return Universe.UNCHANGED\n self.week = current_week\n\n ## If its a new week, then re-filter stocks by Dollar Volume\n sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)\n\n return [ x.symbol for x in sorted_by_dollar_volume[:25] ]\n\n\nclass PriceGapMeanReversionAlphaModel(AlphaModel):\n\n def __init__(self, *args, **kwargs):\n ''' Initialize variables and dictionary for Symbol Data to support algorithm's function '''\n self.lookback = 100\n self.resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.MINUTE\n self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), 5) ## Arbitrary\n self._symbol_data_by_symbol = {}\n\n def update(self, algorithm, data):\n insights = []\n\n ## Loop through all Symbol Data objects\n for symbol, symbol_data in self._symbol_data_by_symbol.items():\n ## Evaluate whether or not the price jump is expected to rebound\n if not symbol_data.is_trend(data):\n continue\n\n ## Emit insights accordingly to the price jump sign\n direction = InsightDirection.DOWN if symbol_data.price_jump > 0 else InsightDirection.UP\n insights.append(Insight.price(symbol, self.prediction_interval, direction, symbol_data.price_jump, None))\n\n return insights\n\n def on_securities_changed(self, algorithm, changes):\n # Clean up data for removed securities\n for removed in changes.removed_securities:\n symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)\n if symbol_data is not None:\n symbol_data.remove_consolidators(algorithm)\n\n symbols = [x.symbol for x in changes.added_securities\n if x.symbol not in self._symbol_data_by_symbol]\n\n history = algorithm.history(symbols, self.lookback, self.resolution)\n if history.empty: return\n\n ## Create and initialize SymbolData objects\n for symbol in symbols:\n symbol_data = SymbolData(algorithm, symbol, self.lookback, self.resolution)\n symbol_data.warm_up_indicators(history.loc[symbol])\n self._symbol_data_by_symbol[symbol] = symbol_data\n\n\nclass SymbolData:\n def __init__(self, algorithm, symbol, lookback, resolution):\n self._symbol = symbol\n self.close = 0\n self.last_price = 0\n self.price_jump = 0\n self.consolidator = algorithm.resolve_consolidator(symbol, resolution)\n self.volatility = StandardDeviation(f'{symbol}.std({lookback})', lookback)\n algorithm.register_indicator(symbol, self.volatility, self.consolidator)\n\n def remove_consolidators(self, algorithm):\n algorithm.subscription_manager.remove_consolidator(self._symbol, self.consolidator)\n\n def warm_up_indicators(self, history):\n self.close = history.iloc[-1].close\n for tuple in history.itertuples():\n self.volatility.update(tuple.Index, tuple.close)\n\n def is_trend(self, data):\n\n ## Check for any data events that would return a NoneBar in the Alpha Model Update() method\n if not data.bars.contains_key(self._symbol):\n return False\n\n self.last_price = self.close\n self.close = data.bars[self._symbol].close\n self.price_jump = (self.close / self.last_price) - 1\n return abs(100*self.price_jump) > 3*self.volatility.current.value\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: Alpha Benchmark Strategy capitalizing on ETF rebalancing causing momentum during trending markets.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass RebalancingLeveragedETFAlpha(QCAlgorithm):\n ''' Alpha Streams: Benchmark Alpha: Leveraged ETF Rebalancing\n Strategy by Prof. Shum, reposted by Ernie Chan.\n Source: http://epchan.blogspot.com/2012/10/a-leveraged-etfs-strategy.html'''\n\n def initialize(self):\n\n self.set_start_date(2017, 6, 1)\n self.set_end_date(2018, 8, 1)\n self.set_cash(100000)\n\n underlying = [\"SPY\",\"QLD\",\"DIA\",\"IJR\",\"MDY\",\"IWM\",\"QQQ\",\"IYE\",\"EEM\",\"IYW\",\"EFA\",\"GAZB\",\"SLV\",\"IEF\",\"IYM\",\"IYF\",\"IYH\",\"IYR\",\"IYC\",\"IBB\",\"FEZ\",\"USO\",\"TLT\"]\n ultra_long = [\"SSO\",\"UGL\",\"DDM\",\"SAA\",\"MZZ\",\"UWM\",\"QLD\",\"DIG\",\"EET\",\"ROM\",\"EFO\",\"BOIL\",\"AGQ\",\"UST\",\"UYM\",\"UYG\",\"RXL\",\"URE\",\"UCC\",\"BIB\",\"ULE\",\"UCO\",\"UBT\"]\n ultra_short = [\"SDS\",\"GLL\",\"DXD\",\"SDD\",\"MVV\",\"TWM\",\"QID\",\"DUG\",\"EEV\",\"REW\",\"EFU\",\"KOLD\",\"ZSL\",\"PST\",\"SMN\",\"SKF\",\"RXD\",\"SRS\",\"SCC\",\"BIS\",\"EPV\",\"SCO\",\"TBT\"]\n\n groups = []\n for i in range(len(underlying)):\n group = ETFGroup(self.add_equity(underlying[i], Resolution.MINUTE).symbol,\n self.add_equity(ultra_long[i], Resolution.MINUTE).symbol,\n self.add_equity(ultra_short[i], Resolution.MINUTE).symbol)\n groups.append(group)\n\n # Manually curated universe\n self.set_universe_selection(ManualUniverseSelectionModel())\n # Select the demonstration alpha model\n self.set_alpha(RebalancingLeveragedETFAlphaModel(groups))\n\n # Equally weigh securities in portfolio, based on insights\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n\n # Set Immediate Execution Model\n self.set_execution(ImmediateExecutionModel())\n\n # Set Null Risk Management Model\n self.set_risk_management(NullRiskManagementModel())\n\n\nclass RebalancingLeveragedETFAlphaModel(AlphaModel):\n\n '''\n If the underlying ETF has experienced a return >= 1% since the previous day's close up to the current time at 14:15,\n then buy it's ultra ETF right away, and exit at the close. If the return is <= -1%, sell it's ultra-short ETF.\n '''\n\n def __init__(self, ETFgroups):\n\n self.etfgroups = ETFgroups\n self.date = datetime.min.date\n self.name = \"RebalancingLeveragedETFAlphaModel\"\n\n def update(self, algorithm, data):\n '''Scan to see if the returns are greater than 1% at 2.15pm to emit an insight.'''\n\n insights = []\n magnitude = 0.0005\n # Paper suggests leveraged ETF's rebalance from 2.15pm - to close\n # giving an insight period of 105 minutes.\n period = timedelta(minutes=105)\n\n # Get yesterday's close price at the market open\n if algorithm.time.date() != self.date:\n self.date = algorithm.time.date()\n # Save yesterday's price and reset the signal\n for group in self.etfgroups:\n history = algorithm.history([group.underlying], 1, Resolution.DAILY)\n group.yesterday_close = None if history.empty else history.loc[str(group.underlying)]['close'][0]\n\n # Check if the returns are > 1% at 14.15\n if algorithm.time.hour == 14 and algorithm.time.minute == 15:\n for group in self.etfgroups:\n if group.yesterday_close == 0 or group.yesterday_close is None: continue\n returns = round((algorithm.portfolio[group.underlying].price - group.yesterday_close) / group.yesterday_close, 10)\n if returns > 0.01:\n insights.append(Insight.price(group.ultra_long, period, InsightDirection.UP, magnitude))\n elif returns < -0.01:\n insights.append(Insight.price(group.ultra_short, period, InsightDirection.DOWN, magnitude))\n\n return insights\n\nclass ETFGroup:\n '''\n Group the underlying ETF and it's ultra ETFs\n Args:\n underlying: The underlying index ETF\n ultra_long: The long-leveraged version of underlying ETF\n ultra_short: The short-leveraged version of the underlying ETF\n '''\n def __init__(self,underlying, ultra_long, ultra_short):\n self.underlying = underlying\n self.ultra_long = ultra_long\n self.ultra_short = ultra_short\n self.yesterday_close = 0\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: Contingent Claim Analysis is put forth by Robert Merton, recepient of the Noble Prize in Economics in 1997 for his work in contributing to", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nimport scipy.stats as sp\nfrom Risk.NullRiskManagementModel import NullRiskManagementModel\nfrom Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\nfrom Execution.ImmediateExecutionModel import ImmediateExecutionModel\n\nclass ContingentClaimsAnalysisDefaultPredictionAlpha(QCAlgorithm):\n ''' Contingent Claim Analysis is put forth by Robert Merton, recepient of the Noble Prize in Economics in 1997 for his work in contributing to\n Black-Scholes option pricing theory, which says that the equity market value of stockholders\u2019 equity is given by the Black-Scholes solution\n for a European call option. This equation takes into account Debt, which in CCA is the equivalent to a strike price in the BS solution. The probability\n of default on corporate debt can be calculated as the N(-d2) term, where d2 is a function of the interest rate on debt(\u00b5), face value of the debt (B), value of the firm's assets (V),\n standard deviation of the change in a firm's asset value (\u03c3), the dividend and interest payouts due (D), and the time to maturity of the firm's debt(\u03c4). N(*) is the cumulative\n distribution function of a standard normal distribution, and calculating N(-d2) gives us the probability of the firm's assets being worth less\n than the debt of the company at the time that the debt reaches maturity -- that is, the firm doesn't have enough in assets to pay off its debt and defaults.\n\n We use a Fine/Coarse Universe Selection model to select small cap stocks, who we postulate are more likely to default\n on debt in general than blue-chip companies, and extract Fundamental data to plug into the CCA formula.\n This Alpha emits insights based on whether or not a company is likely to default given its probability of default vs a default probability threshold that we set arbitrarily.\n\n Prob. default (on principal B at maturity T) = Prob(VT < B) = 1 - N(d2) = N(-d2) where -d2(\u00b5) = -{ln(V/B) + [(\u00b5 - D) - \u00bd\u03c32]\u03c4}/ \u03c3 \u221a\u03c4.\n N(d) = (univariate) cumulative standard normal distribution function (from -inf to d)\n B = face value (principal) of the debt\n D = dividend + interest payout\n V = value of firm\u2019s assets\n \u03c3 (sigma) = standard deviation of firm value changes (returns in V)\n \u03c4 (tau) = time to debt\u2019s maturity\n \u00b5 (mu) = interest rate\n\n This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open\n sourced so the community and client funds can see an example of an alpha.'''\n\n def initialize(self):\n\n ## Set requested data resolution and variables to help with Universe Selection control\n self.universe_settings.resolution = Resolution.DAILY\n self.month = -1\n\n ## Declare single variable to be passed in multiple places -- prevents issue with conflicting start dates declared in different places\n self.set_start_date(2018,1,1)\n self.set_cash(100000)\n\n ## SPDR Small Cap ETF is a better benchmark than the default SP500\n self.set_benchmark('IJR')\n\n ## Set Universe Selection Model\n self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.coarse_selection_function, self.fine_selection_function))\n self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))\n ## Set CCA Alpha Model\n self.set_alpha(ContingentClaimsAnalysisAlphaModel())\n\n ## Set Portfolio Construction Model\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n\n ## Set Execution Model\n self.set_execution(ImmediateExecutionModel())\n\n ## Set Risk Management Model\n self.set_risk_management(NullRiskManagementModel())\n\n\n def coarse_selection_function(self, coarse):\n ## Boolean controls so that our symbol universe is only updated once per month\n if self.time.month == self.month:\n return Universe.UNCHANGED\n self.month = self.time.month\n\n ## Sort by dollar volume, lowest to highest\n sorted_by_dollar_volume = sorted([x for x in coarse if x.has_fundamental_data],\n key=lambda x: x.dollar_volume, reverse=True)\n\n ## Return smallest 750 -- idea is that smaller companies are most likely to go bankrupt than blue-chip companies\n ## Filter for assets with fundamental data\n return [x.symbol for x in sorted_by_dollar_volume[:750]]\n\n def fine_selection_function(self, fine):\n\n def is_valid(x):\n statement = x.financial_statements\n sheet = statement.balance_sheet\n total_assets = sheet.total_assets\n ratios = x.operation_ratios\n\n return total_assets.one_month > 0 and \\\n total_assets.three_months > 0 and \\\n total_assets.six_months > 0 and \\\n total_assets.twelve_months > 0 and \\\n sheet.current_liabilities.twelve_months > 0 and \\\n sheet.interest_payable.twelve_months > 0 and \\\n ratios.total_assets_growth.one_year > 0 and \\\n statement.income_statement.gross_dividend_payment.twelve_months > 0 and \\\n ratios.roa.one_year > 0\n\n return [x.symbol for x in sorted(fine, key=lambda x: is_valid(x))]\n\n\nclass ContingentClaimsAnalysisAlphaModel(AlphaModel):\n\n def __init__(self, *args, **kwargs):\n self.probability_of_default_by_symbol = {}\n self.default_threshold = kwargs['default_threshold'] if 'default_threshold' in kwargs else 0.25\n\n def update(self, algorithm, data):\n '''Updates this alpha model with the latest data from the algorithm.\n This is called each time the algorithm receives data for subscribed securities\n Args:\n algorithm: The algorithm instance\n data: The new data available\n Returns:\n The new insights generated'''\n\n ## Build a list to hold our insights\n insights = []\n\n for symbol, pod in self.probability_of_default_by_symbol.items():\n\n ## If Prob. of Default is greater than our set threshold, then emit an insight indicating that this asset is trending downward\n if pod >= self.default_threshold and pod != 1.0:\n insights.append(Insight.price(symbol, timedelta(30), InsightDirection.DOWN, pod, None))\n\n return insights\n\n def on_securities_changed(self, algorithm, changes):\n\n for removed in changes.removed_securities:\n self.probability_of_default_by_symbol.pop(removed.symbol, None)\n\n # initialize data for added securities\n symbols = [ x.symbol for x in changes.added_securities ]\n\n for symbol in symbols:\n if symbol not in self.probability_of_default_by_symbol:\n ## CCA valuation\n pod = self.get_probability_of_default(algorithm, symbol)\n if pod is not None:\n self.probability_of_default_by_symbol[symbol] = pod\n\n def get_probability_of_default(self, algorithm, symbol):\n '''This model applies options pricing theory, Black-Scholes specifically,\n to fundamental data to give the probability of a default'''\n security = algorithm.securities[symbol]\n if security.fundamentals is None or security.fundamentals.financial_statements is None or security.fundamentals.operation_ratios is None:\n return None\n\n statement = security.fundamentals.financial_statements\n sheet = statement.balance_sheet\n total_assets = sheet.total_assets\n\n tau = 360 ## Days\n mu = security.fundamentals.operation_ratios.roa.one_year\n V = total_assets.twelve_months\n B = sheet.current_liabilities.twelve_months\n D = statement.income_statement.gross_dividend_payment.twelve_months + sheet.interest_payable.twelve_months\n\n series = pd.Series(\n [\n total_assets.one_month,\n total_assets.three_months,\n total_assets.six_months,\n V\n ])\n sigma = series.iloc[series.nonzero()[0]]\n sigma = np.std(sigma.pct_change()[1:len(sigma)])\n\n d2 = ((np.log(V) - np.log(B)) + ((mu - D) - 0.5*sigma**2.0)*tau)/ (sigma*np.sqrt(tau))\n return sp.norm.cdf(-d2)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: Alpha Streams: Benchmark Alpha: Identify \"pumped\" penny stocks and predict that the price of a \"pumped\" penny stock reverts to mean", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel\n\nclass SykesShortMicroCapAlpha(QCAlgorithm):\n ''' Alpha Streams: Benchmark Alpha: Identify \"pumped\" penny stocks and predict that the price of a \"pumped\" penny stock reverts to mean\n\n This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open\n sourced so the community and client funds can see an example of an alpha.'''\n\n def initialize(self):\n\n self.set_start_date(2018, 1, 1)\n self.set_cash(100000)\n\n # Set zero transaction fees\n self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))\n\n # select stocks using PennyStockUniverseSelectionModel\n self.universe_settings.resolution = Resolution.DAILY\n self.universe_settings.schedule.on(self.date_rules.month_start())\n self.set_universe_selection(PennyStockUniverseSelectionModel())\n\n # Use SykesShortMicroCapAlphaModel to establish insights\n self.set_alpha(SykesShortMicroCapAlphaModel())\n\n # Equally weigh securities in portfolio, based on insights\n self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())\n\n # Set Immediate Execution Model\n self.set_execution(ImmediateExecutionModel())\n\n # Set Null Risk Management Model\n self.set_risk_management(NullRiskManagementModel())\n\n\nclass SykesShortMicroCapAlphaModel(AlphaModel):\n '''Uses ranking of intraday percentage difference between open price and close price to create magnitude and direction prediction for insights'''\n\n def __init__(self, *args, **kwargs):\n lookback = kwargs['lookback'] if 'lookback' in kwargs else 1\n resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.DAILY\n self.prediction_interval = Time.multiply(Extensions.to_time_span(resolution), lookback)\n self.number_of_stocks = kwargs['number_of_stocks'] if 'number_of_stocks' in kwargs else 10\n\n def update(self, algorithm, data):\n insights = []\n symbols_ret = dict()\n\n for security in algorithm.active_securities.values:\n if security.has_data:\n open_ = security.open\n if open_ != 0:\n # Intraday price change for penny stocks\n symbols_ret[security.symbol] = security.close / open_ - 1\n\n # Rank penny stocks on one day price change and retrieve list of ten \"pumped\" penny stocks\n pumped_stocks = dict(sorted(symbols_ret.items(),\n key = lambda kv: (-round(kv[1], 6), kv[0]))[:self.number_of_stocks])\n\n # Emit \"down\" insight for \"pumped\" penny stocks\n for symbol, value in pumped_stocks.items():\n insights.append(Insight.price(symbol, self.prediction_interval, InsightDirection.DOWN, abs(value), None))\n\n return insights\n\n\nclass PennyStockUniverseSelectionModel(FundamentalUniverseSelectionModel):\n '''Defines a universe of penny stocks, as a universe selection model for the framework algorithm:\n The stocks must have fundamental data\n The stock must have positive previous-day close price\n The stock must have volume between $1000000 and $10000 on the previous trading day\n The stock must cost less than $5'''\n def __init__(self):\n super().__init__()\n\n # Number of stocks in Coarse Universe\n self.number_of_symbols_coarse = 500\n\n def select(self, algorithm, fundamental):\n # sort the stocks by dollar volume and take the top 500\n top = sorted([x for x in fundamental if x.has_fundamental_data\n and 5 > x.price > 0\n and 1000000 > x.volume > 10000],\n key=lambda x: x.dollar_volume, reverse=True)[:self.number_of_symbols_coarse]\n\n return [x.symbol for x in top]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN ExecutionModel that can be described like this\n: Execution model that submits orders while the current market prices is at least the configured number of standard", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass StandardDeviationExecutionModel(ExecutionModel):\n '''Execution model that submits orders while the current market prices is at least the configured number of standard\n deviations away from the mean in the favorable direction (below/above for buy/sell respectively)'''\n\n def __init__(self,\n period = 60,\n deviations = 2,\n resolution = Resolution.MINUTE,\n asynchronous=True):\n '''Initializes a new instance of the StandardDeviationExecutionModel class\n Args:\n period: Period of the standard deviation indicator\n deviations: The number of deviations away from the mean before submitting an order\n resolution: The resolution of the STD and SMA indicators\n asynchronous: If True, orders will be submitted asynchronously.'''\n super().__init__(asynchronous)\n self.period = period\n self.deviations = deviations\n self.resolution = resolution\n self.targets_collection = PortfolioTargetCollection()\n self._symbol_data = {}\n\n # Gets or sets the maximum order value in units of the account currency.\n # This defaults to $20,000. For example, if purchasing a stock with a price\n # of $100, then the maximum order size would be 200 shares.\n self.maximum_order_value = 20000\n\n\n def execute(self, algorithm, targets):\n '''Executes market orders if the standard deviation of price is more\n than the configured number of deviations in the favorable direction.\n Args:\n algorithm: The algorithm instance\n targets: The portfolio targets'''\n self.targets_collection.add_range(targets)\n\n # for performance we check count value, OrderByMarginImpact and ClearFulfilled are expensive to call\n if not self.targets_collection.is_empty:\n for target in self.targets_collection.order_by_margin_impact(algorithm):\n symbol = target.symbol\n\n # calculate remaining quantity to be ordered\n unordered_quantity = OrderSizing.get_unordered_quantity(algorithm, target)\n\n # fetch our symbol data containing our STD/SMA indicators\n data = self._symbol_data.get(symbol, None)\n if data is None: return\n\n # check order entry conditions\n if data.std.is_ready and self.price_is_favorable(data, unordered_quantity):\n # Adjust order size to respect the maximum total order value\n order_size = OrderSizing.get_order_size_for_maximum_value(data.security, self.maximum_order_value, unordered_quantity)\n\n if order_size != 0:\n algorithm.market_order(symbol, order_size, self.asynchronous, target.tag)\n\n self.targets_collection.clear_fulfilled(algorithm)\n\n\n def on_securities_changed(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n for added in changes.added_securities:\n if added.symbol not in self._symbol_data:\n self._symbol_data[added.symbol] = SymbolData(algorithm, added, self.period, self.resolution)\n\n for removed in changes.removed_securities:\n # clean up data from removed securities\n symbol = removed.symbol\n if symbol in self._symbol_data:\n if self.is_safe_to_remove(algorithm, symbol):\n data = self._symbol_data.pop(symbol)\n algorithm.subscription_manager.remove_consolidator(symbol, data.consolidator)\n\n\n def price_is_favorable(self, data, unordered_quantity):\n '''Determines if the current price is more than the configured\n number of standard deviations away from the mean in the favorable direction.'''\n sma = data.sma.current.value\n deviations = self.deviations * data.std.current.value\n if unordered_quantity > 0:\n return data.security.bid_price < sma - deviations\n else:\n return data.security.ask_price > sma + deviations\n\n\n def is_safe_to_remove(self, algorithm, symbol):\n '''Determines if it's safe to remove the associated symbol data'''\n # confirm the security isn't currently a member of any universe\n return not any([kvp.value.contains_member(symbol) for kvp in algorithm.universe_manager])\n\nclass SymbolData:\n def __init__(self, algorithm, security, period, resolution):\n symbol = security.symbol\n self.security = security\n self.consolidator = algorithm.resolve_consolidator(symbol, resolution)\n\n sma_name = algorithm.create_indicator_name(symbol, f\"SMA{period}\", resolution)\n self.sma = SimpleMovingAverage(sma_name, period)\n algorithm.register_indicator(symbol, self.sma, self.consolidator)\n\n std_name = algorithm.create_indicator_name(symbol, f\"STD{period}\", resolution)\n self.std = StandardDeviation(std_name, period)\n algorithm.register_indicator(symbol, self.std, self.consolidator)\n\n # warmup our indicators by pushing history through the indicators\n bars = algorithm.history[self.consolidator.input_type](symbol, period, resolution)\n for bar in bars:\n self.sma.update(bar.end_time, bar.close)\n self.std.update(bar.end_time, bar.close)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN ExecutionModel that can be described like this\n: Execution model that submits orders while the current market price is more favorable that the current volume weighted average price.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass VolumeWeightedAveragePriceExecutionModel(ExecutionModel):\n '''Execution model that submits orders while the current market price is more favorable that the current volume weighted average price.'''\n\n def __init__(self, asynchronous=True):\n '''Initializes a new instance of the VolumeWeightedAveragePriceExecutionModel class'''\n super().__init__(asynchronous)\n self.targets_collection = PortfolioTargetCollection()\n self.symbol_data = {}\n\n # Gets or sets the maximum order quantity as a percentage of the current bar's volume.\n # This defaults to 0.01m = 1%. For example, if the current bar's volume is 100,\n # then the maximum order size would equal 1 share.\n self.maximum_order_quantity_percent_volume = 0.01\n\n\n def execute(self, algorithm, targets):\n '''Executes market orders if the standard deviation of price is more\n than the configured number of deviations in the favorable direction.\n Args:\n algorithm: The algorithm instance\n targets: The portfolio targets'''\n # update the complete set of portfolio targets with the new targets\n self.targets_collection.add_range(targets)\n\n # for performance we check count value, OrderByMarginImpact and ClearFulfilled are expensive to call\n if not self.targets_collection.is_empty:\n for target in self.targets_collection.order_by_margin_impact(algorithm):\n symbol = target.symbol\n\n # calculate remaining quantity to be ordered\n unordered_quantity = OrderSizing.get_unordered_quantity(algorithm, target)\n\n # fetch our symbol data containing our VWAP indicator\n data = self.symbol_data.get(symbol, None)\n if data is None: return\n\n # check order entry conditions\n if self.price_is_favorable(data, unordered_quantity):\n # adjust order size to respect maximum order size based on a percentage of current volume\n order_size = OrderSizing.get_order_size_for_percent_volume(data.security, self.maximum_order_quantity_percent_volume, unordered_quantity)\n\n if order_size != 0:\n algorithm.market_order(symbol, order_size, self.asynchronous, target.tag)\n\n self.targets_collection.clear_fulfilled(algorithm)\n\n\n def on_securities_changed(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n for removed in changes.removed_securities:\n # clean up removed security data\n if removed.symbol in self.symbol_data:\n if self.is_safe_to_remove(algorithm, removed.symbol):\n data = self.symbol_data.pop(removed.symbol)\n algorithm.subscription_manager.remove_consolidator(removed.symbol, data.consolidator)\n\n for added in changes.added_securities:\n if added.symbol not in self.symbol_data:\n self.symbol_data[added.symbol] = SymbolData(algorithm, added)\n\n\n def price_is_favorable(self, data, unordered_quantity):\n '''Determines if the current price is more than the configured\n number of standard deviations away from the mean in the favorable direction.'''\n if unordered_quantity > 0:\n if data.security.bid_price < data.vwap:\n return True\n else:\n if data.security.ask_price > data.vwap:\n return True\n\n return False\n\n def is_safe_to_remove(self, algorithm, symbol):\n '''Determines if it's safe to remove the associated symbol data'''\n # confirm the security isn't currently a member of any universe\n return not any([kvp.value.contains_member(symbol) for kvp in algorithm.universe_manager])\n\nclass SymbolData:\n def __init__(self, algorithm, security):\n self.security = security\n self.consolidator = algorithm.resolve_consolidator(security.symbol, security.resolution)\n name = algorithm.create_indicator_name(security.symbol, \"VWAP\", security.resolution)\n self._vwap = IntradayVwap(name)\n algorithm.register_indicator(security.symbol, self._vwap, self.consolidator)\n\n @property\n def vwap(self):\n return self._vwap.value\n\nclass IntradayVwap:\n '''Defines the canonical intraday VWAP indicator'''\n def __init__(self, name):\n self.name = name\n self.value = 0.0\n self.last_date = datetime.min\n self.sum_of_volume = 0.0\n self.sum_of_price_times_volume = 0.0\n\n @property\n def is_ready(self):\n return self.sum_of_volume > 0.0\n\n def update(self, input):\n '''Computes the new VWAP'''\n success, volume, average_price = self.get_volume_and_average_price(input)\n if not success:\n return self.is_ready\n\n # reset vwap on daily boundaries\n if self.last_date != input.end_time.date():\n self.sum_of_volume = 0.0\n self.sum_of_price_times_volume = 0.0\n self.last_date = input.end_time.date()\n\n # running totals for \u03a3 PiVi / \u03a3 Vi\n self.sum_of_volume += volume\n self.sum_of_price_times_volume += average_price * volume\n\n if self.sum_of_volume == 0.0:\n # if we have no trade volume then use the current price as VWAP\n self.value = input.value\n return self.is_ready\n\n self.value = self.sum_of_price_times_volume / self.sum_of_volume\n return self.is_ready\n\n def get_volume_and_average_price(self, input):\n '''Determines the volume and price to be used for the current input in the VWAP computation'''\n\n if type(input) is Tick:\n if input.tick_type == TickType.TRADE:\n return True, float(input.quantity), float(input.last_price)\n\n if type(input) is TradeBar:\n if not input.is_fill_forward:\n average_price = float(input.high + input.low + input.close) / 3\n return True, float(input.volume), average_price\n\n return False, 0.0, 0.0\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN ExecutionModel that can be described like this\n: Execution model that submits orders while the current spread is tight.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass SpreadExecutionModel(ExecutionModel):\n '''Execution model that submits orders while the current spread is tight.\n Note this execution model will not work using Resolution.DAILY since Exchange.exchange_open will be false, suggested resolution is Minute\n '''\n\n def __init__(self, accepting_spread_percent=0.005, asynchronous=True):\n '''Initializes a new instance of the SpreadExecutionModel class'''\n super().__init__(asynchronous)\n self.targets_collection = PortfolioTargetCollection()\n\n # Gets or sets the maximum spread compare to current price in percentage.\n self.accepting_spread_percent = Math.abs(accepting_spread_percent)\n\n def execute(self, algorithm, targets):\n '''Executes market orders if the spread percentage to price is in desirable range.\n Args:\n algorithm: The algorithm instance\n targets: The portfolio targets'''\n # update the complete set of portfolio targets with the new targets\n self.targets_collection.add_range(targets)\n\n # for performance we check count value, OrderByMarginImpact and ClearFulfilled are expensive to call\n if not self.targets_collection.is_empty:\n for target in self.targets_collection.order_by_margin_impact(algorithm):\n symbol = target.symbol\n\n # calculate remaining quantity to be ordered\n unordered_quantity = OrderSizing.get_unordered_quantity(algorithm, target)\n\n # check order entry conditions\n if unordered_quantity != 0:\n # get security information\n security = algorithm.securities[symbol]\n if self.spread_is_favorable(security):\n algorithm.market_order(symbol, unordered_quantity, self.asynchronous, target.tag)\n\n self.targets_collection.clear_fulfilled(algorithm)\n\n def spread_is_favorable(self, security):\n '''Determines if the spread is in desirable range.'''\n # Price has to be larger than zero to avoid zero division error, or negative price causing the spread percentage < 0 by error\n # Has to be in opening hours of exchange to avoid extreme spread in OTC period\n return security.exchange.exchange_open \\\n and security.price > 0 and security.ask_price > 0 and security.bid_price > 0 \\\n and (security.ask_price - security.bid_price) / security.price <= self.accepting_spread_percent\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: This alpha model is designed to accept every possible pair combination", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom enum import Enum\n\nclass BasePairsTradingAlphaModel(AlphaModel):\n '''This alpha model is designed to accept every possible pair combination\n from securities selected by the universe selection model\n This model generates alternating long ratio/short ratio insights emitted as a group'''\n\n def __init__(self, lookback = 1,\n resolution = Resolution.DAILY,\n threshold = 1):\n ''' Initializes a new instance of the PairsTradingAlphaModel class\n Args:\n lookback: Lookback period of the analysis\n resolution: Analysis resolution\n threshold: The percent [0, 100] deviation of the ratio from the mean before emitting an insight'''\n self.lookback = lookback\n self.resolution = resolution\n self.threshold = threshold\n self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), self.lookback)\n\n self.pairs = dict()\n self.securities = set()\n\n self.name = f'{self.__class__.__name__}({self.lookback},{resolution},{Extensions.normalize_to_str(threshold)})'\n\n\n def update(self, algorithm, data):\n ''' Updates this alpha model with the latest data from the algorithm.\n This is called each time the algorithm receives data for subscribed securities\n Args:\n algorithm: The algorithm instance\n data: The new data available\n Returns:\n The new insights generated'''\n insights = []\n\n for key, pair in self.pairs.items():\n insights.extend(pair.get_insight_group())\n\n return insights\n\n def on_securities_changed(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed.\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n\n for security in changes.added_securities:\n self.securities.add(security)\n\n for security in changes.removed_securities:\n if security in self.securities:\n self.securities.remove(security)\n\n self.update_pairs(algorithm)\n\n for security in changes.removed_securities:\n keys = [k for k in self.pairs.keys() if security.symbol in k]\n for key in keys:\n self.pairs.pop(key).dispose()\n\n def update_pairs(self, algorithm):\n\n symbols = sorted([x.symbol for x in self.securities])\n\n for i in range(0, len(symbols)):\n asset_i = symbols[i]\n\n for j in range(1 + i, len(symbols)):\n asset_j = symbols[j]\n\n pair_symbol = (asset_i, asset_j)\n invert = (asset_j, asset_i)\n\n if pair_symbol in self.pairs or invert in self.pairs:\n continue\n\n if not self.has_passed_test(algorithm, asset_i, asset_j):\n continue\n\n pair = self.Pair(algorithm, asset_i, asset_j, self.prediction_interval, self.threshold)\n self.pairs[pair_symbol] = pair\n\n def has_passed_test(self, algorithm, asset1, asset2):\n '''Check whether the assets pass a pairs trading test\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n asset1: The first asset's symbol in the pair\n asset2: The second asset's symbol in the pair\n Returns:\n True if the statistical test for the pair is successful'''\n return True\n\n class Pair:\n\n class State(Enum):\n SHORT_RATIO = -1\n FLAT_RATIO = 0\n LONG_RATIO = 1\n\n def __init__(self, algorithm, asset1, asset2, prediction_interval, threshold):\n '''Create a new pair\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n asset1: The first asset's symbol in the pair\n asset2: The second asset's symbol in the pair\n prediction_interval: Period over which this insight is expected to come to fruition\n threshold: The percent [0, 100] deviation of the ratio from the mean before emitting an insight'''\n self.state = self.State.FLAT_RATIO\n\n self.algorithm = algorithm\n self.asset1 = asset1\n self.asset2 = asset2\n\n # Created the Identity indicator for a given Symbol and\n # the consolidator it is registered to. The consolidator reference\n # will be used to remove it from SubscriptionManager\n def create_identity_indicator(symbol: Symbol):\n resolution = min([x.resolution for x in algorithm.subscription_manager.subscription_data_config_service.get_subscription_data_configs(symbol)])\n\n name = algorithm.create_indicator_name(symbol, \"close\", resolution)\n identity = Identity(name)\n\n consolidator = algorithm.resolve_consolidator(symbol, resolution)\n algorithm.register_indicator(symbol, identity, consolidator)\n\n return identity, consolidator\n\n self.asset1_price, self.identity_consolidator1 = create_identity_indicator(asset1);\n self.asset2_price, self.identity_consolidator2 = create_identity_indicator(asset2);\n\n self.ratio = IndicatorExtensions.over(self.asset1_price, self.asset2_price)\n self.mean = IndicatorExtensions.of(ExponentialMovingAverage(500), self.ratio)\n\n upper = ConstantIndicator[IndicatorDataPoint](\"ct\", 1 + threshold / 100)\n self.upper_threshold = IndicatorExtensions.times(self.mean, upper)\n\n lower = ConstantIndicator[IndicatorDataPoint](\"ct\", 1 - threshold / 100)\n self.lower_threshold = IndicatorExtensions.times(self.mean, lower)\n\n self.prediction_interval = prediction_interval\n\n def dispose(self):\n '''\n On disposal, remove the consolidators from the subscription manager\n '''\n self.algorithm.subscription_manager.remove_consolidator(self.asset1, self.identity_consolidator1)\n self.algorithm.subscription_manager.remove_consolidator(self.asset2, self.identity_consolidator2)\n\n def get_insight_group(self):\n '''Gets the insights group for the pair\n Returns:\n Insights grouped by an unique group id'''\n\n if not self.mean.is_ready:\n return []\n\n # don't re-emit the same direction\n if self.state is not self.State.LONG_RATIO and self.ratio > self.upper_threshold:\n self.state = self.State.LONG_RATIO\n\n # asset1/asset2 is more than 2 std away from mean, short asset1, long asset2\n short_asset_1 = Insight.price(self.asset1, self.prediction_interval, InsightDirection.DOWN)\n long_asset_2 = Insight.price(self.asset2, self.prediction_interval, InsightDirection.UP)\n\n # creates a group id and set the GroupId property on each insight object\n return Insight.group(short_asset_1, long_asset_2)\n\n # don't re-emit the same direction\n if self.state is not self.State.SHORT_RATIO and self.ratio < self.lower_threshold:\n self.state = self.State.SHORT_RATIO\n\n # asset1/asset2 is less than 2 std away from mean, long asset1, short asset2\n long_asset_1 = Insight.price(self.asset1, self.prediction_interval, InsightDirection.UP)\n short_asset_2 = Insight.price(self.asset2, self.prediction_interval, InsightDirection.DOWN)\n\n # creates a group id and set the GroupId property on each insight object\n return Insight.group(long_asset_1, short_asset_2)\n\n return []\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: Defines a custom alpha model that uses MACD crossovers. The MACD signal line", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MacdAlphaModel(AlphaModel):\n '''Defines a custom alpha model that uses MACD crossovers. The MACD signal line\n is used to generate up/down insights if it's stronger than the bounce threshold.\n If the MACD signal is within the bounce threshold then a flat price insight is returned.'''\n\n def __init__(self,\n fastPeriod = 12,\n slowPeriod = 26,\n signalPeriod = 9,\n movingAverageType = MovingAverageType.Exponential,\n resolution = Resolution.Daily):\n ''' Initializes a new instance of the MacdAlphaModel class\n Args:\n fastPeriod: The MACD fast period\n slowPeriod: The MACD slow period\n signalPeriod: The smoothing period for the MACD signal\n movingAverageType: The type of moving average to use in the MACD'''\n self.fastPeriod = fastPeriod\n self.slowPeriod = slowPeriod\n self.signalPeriod = signalPeriod\n self.movingAverageType = movingAverageType\n self.resolution = resolution\n self.insightPeriod = Time.Multiply(Extensions.ToTimeSpan(resolution), fastPeriod)\n self.bounceThresholdPercent = 0.01\n self.insightCollection = InsightCollection()\n self.symbolData = {}\n\n self.Name = '{}({},{},{},{},{})'.format(self.__class__.__name__, fastPeriod, slowPeriod, signalPeriod, movingAverageType, resolution)\n\n\n def Update(self, algorithm, data):\n ''' Determines an insight for each security based on it's current MACD signal\n Args:\n algorithm: The algorithm instance\n data: The new data available\n Returns:\n The new insights generated'''\n insights = []\n\n for key, sd in self.symbolData.items():\n if sd.Security.Price == 0:\n continue\n\n direction = InsightDirection.Flat\n normalized_signal = sd.MACD.Signal.Current.Value / sd.Security.Price\n\n if normalized_signal > self.bounceThresholdPercent:\n direction = InsightDirection.Up\n elif normalized_signal < -self.bounceThresholdPercent:\n direction = InsightDirection.Down\n\n # ignore signal for same direction as previous signal\n if direction == sd.PreviousDirection:\n continue\n\n sd.PreviousDirection = direction\n\n if direction == InsightDirection.Flat:\n self.CancelInsights(algorithm, sd.Security.Symbol)\n continue\n\n insight = Insight.Price(sd.Security.Symbol, self.insightPeriod, direction)\n insights.append(insight)\n self.insightCollection.Add(insight)\n\n return insights\n\n\n def OnSecuritiesChanged(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed.\n This initializes the MACD for each added security and cleans up the indicator for each removed security.\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n for added in changes.AddedSecurities:\n self.symbolData[added.Symbol] = SymbolData(algorithm, added, self.fastPeriod, self.slowPeriod, self.signalPeriod, self.movingAverageType, self.resolution)\n\n for removed in changes.RemovedSecurities:\n symbol = removed.Symbol\n\n data = self.symbolData.pop(symbol, None)\n if data is not None:\n # clean up our consolidator\n algorithm.SubscriptionManager.RemoveConsolidator(symbol, data.Consolidator)\n\n # remove from insight collection manager\n self.CancelInsights(algorithm, symbol)\n\n def CancelInsights(self, algorithm, symbol):\n if not self.insightCollection.ContainsKey(symbol):\n return\n insights = self.insightCollection[symbol]\n algorithm.Insights.Cancel(insights)\n self.insightCollection.Clear([ symbol ]);\n\n\nclass SymbolData:\n def __init__(self, algorithm, security, fastPeriod, slowPeriod, signalPeriod, movingAverageType, resolution):\n self.Security = security\n self.MACD = MovingAverageConvergenceDivergence(fastPeriod, slowPeriod, signalPeriod, movingAverageType)\n\n self.Consolidator = algorithm.ResolveConsolidator(security.Symbol, resolution)\n algorithm.RegisterIndicator(security.Symbol, self.MACD, self.Consolidator)\n algorithm.WarmUpIndicator(security.Symbol, self.MACD, resolution)\n\n self.PreviousDirection = None\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: Uses Wilder's RSI to create insights.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom QuantConnect.Logging import *\nfrom enum import Enum\n\nclass RsiAlphaModel(AlphaModel):\n '''Uses Wilder's RSI to create insights.\n Using default settings, a cross over below 30 or above 70 will trigger a new insight.'''\n\n def __init__(self,\n period = 14,\n resolution = Resolution.DAILY):\n '''Initializes a new instance of the RsiAlphaModel class\n Args:\n period: The RSI indicator period'''\n self.period = period\n self.resolution = resolution\n self.insight_period = Time.multiply(Extensions.to_time_span(resolution), period)\n self.symbol_data_by_symbol ={}\n\n self.name = '{}({},{})'.format(self.__class__.__name__, period, resolution)\n\n def update(self, algorithm, data):\n '''Updates this alpha model with the latest data from the algorithm.\n This is called each time the algorithm receives data for subscribed securities\n Args:\n algorithm: The algorithm instance\n data: The new data available\n Returns:\n The new insights generated'''\n insights = []\n for symbol, symbol_data in self.symbol_data_by_symbol.items():\n rsi = symbol_data.rsi\n previous_state = symbol_data.state\n state = self.get_state(rsi, previous_state)\n\n if state != previous_state and rsi.is_ready:\n if state == State.TRIPPED_LOW:\n insights.append(Insight.price(symbol, self.insight_period, InsightDirection.UP))\n if state == State.TRIPPED_HIGH:\n insights.append(Insight.price(symbol, self.insight_period, InsightDirection.DOWN))\n\n symbol_data.state = state\n\n return insights\n\n\n def on_securities_changed(self, algorithm, changes):\n '''Cleans out old security data and initializes the RSI for any newly added securities.\n Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n # clean up data for removed securities\n for security in changes.removed_securities:\n symbol_data = self.symbol_data_by_symbol.pop(security.symbol, None)\n if symbol_data:\n symbol_data.dispose()\n\n # initialize data for added securities\n added_symbols = []\n for security in changes.added_securities:\n symbol = security.symbol\n if symbol not in self.symbol_data_by_symbol:\n symbol_data = SymbolData(algorithm, symbol, self.period, self.resolution)\n self.symbol_data_by_symbol[symbol] = symbol_data\n added_symbols.append(symbol)\n\n if added_symbols:\n history = algorithm.history[TradeBar](added_symbols, self.period, self.resolution)\n for trade_bars in history:\n for bar in trade_bars.values():\n self.symbol_data_by_symbol[bar.symbol].update(bar)\n\n\n def get_state(self, rsi, previous):\n ''' Determines the new state. This is basically cross-over detection logic that\n includes considerations for bouncing using the configured bounce tolerance.'''\n if rsi.current.value > 70:\n return State.TRIPPED_HIGH\n if rsi.current.value < 30:\n return State.TRIPPED_LOW\n if previous == State.TRIPPED_LOW:\n if rsi.current.value > 35:\n return State.MIDDLE\n if previous == State.TRIPPED_HIGH:\n if rsi.current.value < 65:\n return State.MIDDLE\n\n return previous\n\n\nclass SymbolData:\n '''Contains data specific to a symbol required by this model'''\n def __init__(self, algorithm, symbol, period, resolution):\n self.algorithm = algorithm\n self.symbol = symbol\n self.state = State.MIDDLE\n\n self.rsi = RelativeStrengthIndex(period, MovingAverageType.WILDERS)\n self.consolidator = algorithm.resolve_consolidator(symbol, resolution)\n algorithm.register_indicator(symbol, self.rsi, self.consolidator)\n\n def update(self, bar):\n self.consolidator.update(bar)\n\n def dispose(self):\n self.algorithm.subscription_manager.remove_consolidator(self.symbol, self.consolidator)\n\n\nclass State(Enum):\n '''Defines the state. This is used to prevent signal spamming and aid in bounce detection.'''\n TRIPPED_LOW = 0\n MIDDLE = 1\n TRIPPED_HIGH = 2\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: This alpha model is designed to rank every pair combination by its pearson correlation", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Alphas.BasePairsTradingAlphaModel import BasePairsTradingAlphaModel\nfrom scipy.stats import pearsonr\n\nclass PearsonCorrelationPairsTradingAlphaModel(BasePairsTradingAlphaModel):\n ''' This alpha model is designed to rank every pair combination by its pearson correlation\n and trade the pair with the hightest correlation\n This model generates alternating long ratio/short ratio insights emitted as a group'''\n\n def __init__(self, lookback = 15,\n resolution = Resolution.MINUTE,\n threshold = 1,\n minimum_correlation = .5):\n '''Initializes a new instance of the PearsonCorrelationPairsTradingAlphaModel class\n Args:\n lookback: lookback period of the analysis\n resolution: analysis resolution\n threshold: The percent [0, 100] deviation of the ratio from the mean before emitting an insight\n minimum_correlation: The minimum correlation to consider a tradable pair'''\n super().__init__(lookback, resolution, threshold)\n self.lookback = lookback\n self.resolution = resolution\n self.minimum_correlation = minimum_correlation\n self.best_pair = ()\n\n def on_securities_changed(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed.\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n\n for security in changes.added_securities:\n self.securities.add(security)\n\n for security in changes.removed_securities:\n if security in self.securities:\n self.securities.remove(security)\n\n symbols = sorted([ x.symbol for x in self.securities ])\n\n history = algorithm.history(symbols, self.lookback, self.resolution)\n\n if not history.empty:\n history = history.close.unstack(level=0)\n\n df = self.get_price_dataframe(history)\n stop = len(df.columns)\n\n corr = dict()\n\n for i in range(0, stop):\n for j in range(i+1, stop):\n if (j, i) not in corr:\n corr[(i, j)] = pearsonr(df.iloc[:,i], df.iloc[:,j])[0]\n\n corr = sorted(corr.items(), key = lambda kv: kv[1])\n if corr[-1][1] >= self.minimum_correlation:\n self.best_pair = (symbols[corr[-1][0][0]], symbols[corr[-1][0][1]])\n\n super().on_securities_changed(algorithm, changes)\n\n def has_passed_test(self, algorithm, asset1, asset2):\n '''Check whether the assets pass a pairs trading test\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n asset1: The first asset's symbol in the pair\n asset2: The second asset's symbol in the pair\n Returns:\n True if the statistical test for the pair is successful'''\n return self.best_pair is not None and self.best_pair[0] == asset1 and self.best_pair[1] == asset2\n\n def get_price_dataframe(self, df):\n timezones = { x.symbol.value: x.exchange.time_zone for x in self.securities }\n\n # Use log prices\n df = np.log(df)\n\n is_single_timeZone = len(set(timezones.values())) == 1\n\n if not is_single_timeZone:\n series_dict = dict()\n\n for column in df:\n # Change the dataframe index from data time to UTC time\n to_utc = lambda x: Extensions.convert_to_utc(x, timezones[column])\n if self.resolution == Resolution.DAILY:\n to_utc = lambda x: Extensions.convert_to_utc(x, timezones[column]).date()\n\n data = df[[column]]\n data.index = data.index.map(to_utc)\n series_dict[column] = data[column]\n\n df = pd.DataFrame(series_dict).dropna()\n\n return (df - df.shift(1)).dropna()\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: Uses Historical returns to create insights.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass HistoricalReturnsAlphaModel(AlphaModel):\n '''Uses Historical returns to create insights.'''\n\n def __init__(self, *args, **kwargs):\n '''Initializes a new default instance of the HistoricalReturnsAlphaModel class.\n Args:\n lookback(int): Historical return lookback period\n resolution: The resolution of historical data'''\n self.lookback = kwargs['lookback'] if 'lookback' in kwargs else 1\n self.resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.DAILY\n self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), self.lookback)\n self._symbol_data_by_symbol = {}\n self.insight_collection = InsightCollection()\n\n def update(self, algorithm, data):\n '''Updates this alpha model with the latest data from the algorithm.\n This is called each time the algorithm receives data for subscribed securities\n Args:\n algorithm: The algorithm instance\n data: The new data available\n Returns:\n The new insights generated'''\n insights = []\n\n for symbol, symbol_data in self._symbol_data_by_symbol.items():\n if symbol_data.can_emit:\n\n direction = InsightDirection.FLAT\n magnitude = symbol_data.return_\n if magnitude > 0: direction = InsightDirection.UP\n if magnitude < 0: direction = InsightDirection.DOWN\n\n if direction == InsightDirection.FLAT:\n self.cancel_insights(algorithm, symbol)\n continue\n\n insights.append(Insight.price(symbol, self.prediction_interval, direction, magnitude, None))\n\n self.insight_collection.add_range(insights)\n return insights\n\n def on_securities_changed(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n\n # clean up data for removed securities\n for removed in changes.removed_securities:\n symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)\n if symbol_data is not None:\n symbol_data.remove_consolidators(algorithm)\n self.cancel_insights(algorithm, removed.symbol)\n\n # initialize data for added securities\n symbols = [ x.symbol for x in changes.added_securities ]\n history = algorithm.history(symbols, self.lookback, self.resolution)\n if history.empty: return\n\n tickers = history.index.levels[0]\n for ticker in tickers:\n symbol = SymbolCache.get_symbol(ticker)\n\n if symbol not in self._symbol_data_by_symbol:\n symbol_data = SymbolData(symbol, self.lookback)\n self._symbol_data_by_symbol[symbol] = symbol_data\n symbol_data.register_indicators(algorithm, self.resolution)\n symbol_data.warm_up_indicators(history.loc[ticker])\n\n def cancel_insights(self, algorithm, symbol):\n if not self.insight_collection.contains_key(symbol):\n return\n insights = self.insight_collection[symbol]\n algorithm.insights.cancel(insights)\n self.insight_collection.clear([ symbol ]);\n\n\nclass SymbolData:\n '''Contains data specific to a symbol required by this model'''\n def __init__(self, symbol, lookback):\n self.symbol = symbol\n self.roc = RateOfChange('{}.roc({})'.format(symbol, lookback), lookback)\n self.consolidator = None\n self.previous = 0\n\n def register_indicators(self, algorithm, resolution):\n self.consolidator = algorithm.resolve_consolidator(self.symbol, resolution)\n algorithm.register_indicator(self.symbol, self.roc, self.consolidator)\n\n def remove_consolidators(self, algorithm):\n if self.consolidator is not None:\n algorithm.subscription_manager.remove_consolidator(self.symbol, self.consolidator)\n\n def warm_up_indicators(self, history):\n for tuple in history.itertuples():\n self.roc.update(tuple.Index, tuple.close)\n\n @property\n def return_(self):\n return float(self.roc.current.value)\n\n @property\n def can_emit(self):\n if self.previous == self.roc.samples:\n return False\n\n self.previous = self.roc.samples\n return self.roc.is_ready\n\n def __str__(self, **kwargs):\n return '{}: {:.2%}'.format(self.roc.name, (1 + self.return_)**252 - 1)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: Alpha model that uses an EMA cross to create insights", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass EmaCrossAlphaModel(AlphaModel):\n '''Alpha model that uses an EMA cross to create insights'''\n\n def __init__(self,\n fast_period = 12,\n slow_period = 26,\n resolution = Resolution.DAILY):\n '''Initializes a new instance of the EmaCrossAlphaModel class\n Args:\n fast_period: The fast EMA period\n slow_period: The slow EMA period'''\n self.fast_period = fast_period\n self.slow_period = slow_period\n self.resolution = resolution\n self.prediction_interval = Time.multiply(Extensions.to_time_span(resolution), fast_period)\n self.symbol_data_by_symbol = {}\n\n self.name = '{}({},{},{})'.format(self.__class__.__name__, fast_period, slow_period, resolution)\n\n\n def update(self, algorithm, data):\n '''Updates this alpha model with the latest data from the algorithm.\n This is called each time the algorithm receives data for subscribed securities\n Args:\n algorithm: The algorithm instance\n data: The new data available\n Returns:\n The new insights generated'''\n insights = []\n for symbol, symbol_data in self.symbol_data_by_symbol.items():\n if symbol_data.fast.is_ready and symbol_data.slow.is_ready:\n\n if symbol_data.fast_is_over_slow:\n if symbol_data.slow > symbol_data.fast:\n insights.append(Insight.price(symbol_data.symbol, self.prediction_interval, InsightDirection.DOWN))\n\n elif symbol_data.slow_is_over_fast:\n if symbol_data.fast > symbol_data.slow:\n insights.append(Insight.price(symbol_data.symbol, self.prediction_interval, InsightDirection.UP))\n\n symbol_data.fast_is_over_slow = symbol_data.fast > symbol_data.slow\n\n return insights\n\n def on_securities_changed(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n for added in changes.added_securities:\n symbol_data = self.symbol_data_by_symbol.get(added.symbol)\n if symbol_data is None:\n symbol_data = SymbolData(added, self.fast_period, self.slow_period, algorithm, self.resolution)\n self.symbol_data_by_symbol[added.symbol] = symbol_data\n else:\n # a security that was already initialized was re-added, reset the indicators\n symbol_data.fast.reset()\n symbol_data.slow.reset()\n\n for removed in changes.removed_securities:\n data = self.symbol_data_by_symbol.pop(removed.symbol, None)\n if data is not None:\n # clean up our consolidators\n data.remove_consolidators()\n\n\nclass SymbolData:\n '''Contains data specific to a symbol required by this model'''\n def __init__(self, security, fast_period, slow_period, algorithm, resolution):\n self.security = security\n self.symbol = security.symbol\n self.algorithm = algorithm\n\n self.fast_consolidator = algorithm.resolve_consolidator(security.symbol, resolution)\n self.slow_consolidator = algorithm.resolve_consolidator(security.symbol, resolution)\n\n algorithm.subscription_manager.add_consolidator(security.symbol, self.fast_consolidator)\n algorithm.subscription_manager.add_consolidator(security.symbol, self.slow_consolidator)\n\n # create fast/slow EMAs\n self.fast = ExponentialMovingAverage(security.symbol, fast_period, ExponentialMovingAverage.smoothing_factor_default(fast_period))\n self.slow = ExponentialMovingAverage(security.symbol, slow_period, ExponentialMovingAverage.smoothing_factor_default(slow_period))\n\n algorithm.register_indicator(security.symbol, self.fast, self.fast_consolidator);\n algorithm.register_indicator(security.symbol, self.slow, self.slow_consolidator);\n\n algorithm.warm_up_indicator(security.symbol, self.fast, resolution);\n algorithm.warm_up_indicator(security.symbol, self.slow, resolution);\n\n # True if the fast is above the slow, otherwise false.\n # This is used to prevent emitting the same signal repeatedly\n self.fast_is_over_slow = False\n\n def remove_consolidators(self):\n self.algorithm.subscription_manager.remove_consolidator(self.security.symbol, self.fast_consolidator)\n self.algorithm.subscription_manager.remove_consolidator(self.security.symbol, self.slow_consolidator)\n\n @property\n def slow_is_over_fast(self):\n return not self.fast_is_over_slow\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN AlphaModel that can be described like this\n: Provides an implementation of IAlphaModel that always returns the same insight for each security", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass ConstantAlphaModel(AlphaModel):\n ''' Provides an implementation of IAlphaModel that always returns the same insight for each security'''\n\n def __init__(self, type, direction, period, magnitude = None, confidence = None, weight = None):\n '''Initializes a new instance of the ConstantAlphaModel class\n Args:\n type: The type of insight\n direction: The direction of the insight\n period: The period over which the insight with come to fruition\n magnitude: The predicted change in magnitude as a +- percentage\n confidence: The confidence in the insight\n weight: The portfolio weight of the insights'''\n self.type = type\n self.direction = direction\n self.period = period\n self.magnitude = magnitude\n self.confidence = confidence\n self.weight = weight\n self.securities = []\n self.insights_time_by_symbol = {}\n\n self.Name = '{}({},{},{}'.format(self.__class__.__name__, type, direction, strfdelta(period))\n if magnitude is not None:\n self.Name += ',{}'.format(magnitude)\n if confidence is not None:\n self.Name += ',{}'.format(confidence)\n\n self.Name += ')'\n\n\n def update(self, algorithm, data):\n ''' Creates a constant insight for each security as specified via the constructor\n Args:\n algorithm: The algorithm instance\n data: The new data available\n Returns:\n The new insights generated'''\n insights = []\n\n for security in self.securities:\n # security price could be zero until we get the first data point. e.g. this could happen\n # when adding both forex and equities, we will first get a forex data point\n if security.price != 0 and self.should_emit_insight(algorithm.utc_time, security.symbol):\n insights.append(Insight(security.symbol, self.period, self.type, self.direction, self.magnitude, self.confidence, weight = self.weight))\n\n return insights\n\n\n def on_securities_changed(self, algorithm, changes):\n ''' Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n for added in changes.added_securities:\n self.securities.append(added)\n\n # this will allow the insight to be re-sent when the security re-joins the universe\n for removed in changes.removed_securities:\n if removed in self.securities:\n self.securities.remove(removed)\n if removed.symbol in self.insights_time_by_symbol:\n self.insights_time_by_symbol.pop(removed.symbol)\n\n\n def should_emit_insight(self, utc_time, symbol):\n if symbol.is_canonical():\n # canonical futures & options are none tradable\n return False\n\n generated_time_utc = self.insights_time_by_symbol.get(symbol)\n\n if generated_time_utc is not None:\n # we previously emitted a insight for this symbol, check it's period to see\n # if we should emit another insight\n if utc_time - generated_time_utc < self.period:\n return False\n\n # we either haven't emitted a insight for this symbol or the previous\n # insight's period has expired, so emit a new insight now for this symbol\n self.insights_time_by_symbol[symbol] = utc_time\n return True\n\ndef strfdelta(tdelta):\n d = tdelta.days\n h, rem = divmod(tdelta.seconds, 3600)\n m, s = divmod(rem, 60)\n return \"{}.{:02d}:{:02d}:{:02d}\".format(d,h,m,s)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN RiskManagementModel that can be described like this\n: Provides an implementation of IRiskManagementModel that limits the unrealized profit per holding to the specified percentage", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MaximumUnrealizedProfitPercentPerSecurity(RiskManagementModel):\n '''Provides an implementation of IRiskManagementModel that limits the unrealized profit per holding to the specified percentage'''\n\n def __init__(self, maximum_unrealized_profit_percent = 0.05):\n '''Initializes a new instance of the MaximumUnrealizedProfitPercentPerSecurity class\n Args:\n maximum_unrealized_profit_percent: The maximum percentage unrealized profit allowed for any single security holding, defaults to 5% drawdown per security'''\n self.maximum_unrealized_profit_percent = abs(maximum_unrealized_profit_percent)\n\n def manage_risk(self, algorithm, targets):\n '''Manages the algorithm's risk at each time step\n Args:\n algorithm: The algorithm instance\n targets: The current portfolio targets to be assessed for risk'''\n targets = []\n for kvp in algorithm.securities:\n security = kvp.value\n\n if not security.invested:\n continue\n\n pnl = security.holdings.unrealized_profit_percent\n if pnl > self.maximum_unrealized_profit_percent:\n symbol = security.symbol\n\n # Cancel insights\n algorithm.insights.cancel([ symbol ]);\n\n # liquidate\n targets.append(PortfolioTarget(symbol, 0))\n\n return targets\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN RiskManagementModel that can be described like this\n: Provides an implementation of IRiskManagementModel that limits the drawdown per holding to the specified percentage", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MaximumDrawdownPercentPerSecurity(RiskManagementModel):\n '''Provides an implementation of IRiskManagementModel that limits the drawdown per holding to the specified percentage'''\n\n def __init__(self, maximum_drawdown_percent = 0.05):\n '''Initializes a new instance of the MaximumDrawdownPercentPerSecurity class\n Args:\n maximum_drawdown_percent: The maximum percentage drawdown allowed for any single security holding'''\n self.maximum_drawdown_percent = -abs(maximum_drawdown_percent)\n\n def manage_risk(self, algorithm, targets):\n '''Manages the algorithm's risk at each time step\n Args:\n algorithm: The algorithm instance\n targets: The current portfolio targets to be assessed for risk'''\n targets = []\n for kvp in algorithm.securities:\n security = kvp.value\n\n if not security.invested:\n continue\n\n pnl = security.holdings.unrealized_profit_percent\n if pnl < self.maximum_drawdown_percent:\n symbol = security.symbol\n\n # Cancel insights\n algorithm.insights.cancel([symbol])\n\n # liquidate\n targets.append(PortfolioTarget(symbol, 0))\n\n return targets\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN RiskManagementModel that can be described like this\n: Provides an implementation of IRiskManagementModel that that limits the sector exposure to the specified percentage", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom itertools import groupby\n\nclass MaximumSectorExposureRiskManagementModel(RiskManagementModel):\n '''Provides an implementation of IRiskManagementModel that that limits the sector exposure to the specified percentage'''\n\n def __init__(self, maximum_sector_exposure = 0.20):\n '''Initializes a new instance of the MaximumSectorExposureRiskManagementModel class\n Args:\n maximum_drawdown_percent: The maximum exposure for any sector, defaults to 20% sector exposure.'''\n if maximum_sector_exposure <= 0:\n raise ValueError('MaximumSectorExposureRiskManagementModel: the maximum sector exposure cannot be a non-positive value.')\n\n self.maximum_sector_exposure = maximum_sector_exposure\n self.targets_collection = PortfolioTargetCollection()\n\n def manage_risk(self, algorithm, targets):\n '''Manages the algorithm's risk at each time step\n Args:\n algorithm: The algorithm instance'''\n maximum_sector_exposure_value = float(algorithm.portfolio.total_portfolio_value) * self.maximum_sector_exposure\n\n self.targets_collection.add_range(targets)\n\n risk_targets = list()\n\n # Group the securities by their sector\n filtered = list(filter(lambda x: x.value.fundamentals is not None and x.value.fundamentals.has_fundamental_data, algorithm.universe_manager.active_securities))\n filtered.sort(key = lambda x: x.value.fundamentals.company_reference.industry_template_code)\n group_by_sector = groupby(filtered, lambda x: x.value.fundamentals.company_reference.industry_template_code)\n\n for code, securities in group_by_sector:\n # Compute the sector absolute holdings value\n # If the construction model has created a target, we consider that\n # value to calculate the security absolute holding value\n quantities = {}\n sector_absolute_holdings_value = 0\n\n for security in securities:\n symbol = security.value.symbol\n quantities[symbol] = security.value.holdings.quantity\n absolute_holdings_value = security.value.holdings.absolute_holdings_value\n\n if self.targets_collection.contains_key(symbol):\n quantities[symbol] = self.targets_collection[symbol].quantity\n\n absolute_holdings_value = (security.value.price * abs(quantities[symbol]) *\n security.value.symbol_properties.contract_multiplier *\n security.value.quote_currency.conversion_rate)\n\n sector_absolute_holdings_value += absolute_holdings_value\n\n # If the ratio between the sector absolute holdings value and the maximum sector exposure value\n # exceeds the unity, it means we need to reduce each security of that sector by that ratio\n # Otherwise, it means that the sector exposure is below the maximum and there is nothing to do.\n ratio = float(sector_absolute_holdings_value) / maximum_sector_exposure_value\n\n if ratio > 1:\n for symbol, quantity in quantities.items():\n if quantity != 0:\n risk_targets.append(PortfolioTarget(symbol, float(quantity) / ratio))\n\n return risk_targets\n\n def on_securities_changed(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n any_fundamental_data = any([\n kvp.value.fundamentals is not None and\n kvp.value.fundamentals.has_fundamental_data for kvp in algorithm.active_securities\n ])\n\n if not any_fundamental_data:\n raise Exception(\"MaximumSectorExposureRiskManagementModel.on_securities_changed: Please select a portfolio selection model that selects securities with fundamental data.\")\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN RiskManagementModel that can be described like this\n: Provides an implementation of IRiskManagementModel that limits the maximum possible loss", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass TrailingStopRiskManagementModel(RiskManagementModel):\n '''Provides an implementation of IRiskManagementModel that limits the maximum possible loss\n measured from the highest unrealized profit'''\n def __init__(self, maximum_drawdown_percent = 0.05):\n '''Initializes a new instance of the TrailingStopRiskManagementModel class\n Args:\n maximum_drawdown_percent: The maximum percentage drawdown allowed for algorithm portfolio compared with the highest unrealized profit, defaults to 5% drawdown'''\n self.maximum_drawdown_percent = abs(maximum_drawdown_percent)\n self.trailing_absolute_holdings_state = dict()\n\n def manage_risk(self, algorithm, targets):\n '''Manages the algorithm's risk at each time step\n Args:\n algorithm: The algorithm instance\n targets: The current portfolio targets to be assessed for risk'''\n risk_adjusted_targets = list()\n\n for kvp in algorithm.securities:\n symbol = kvp.key\n security = kvp.value\n\n # Remove if not invested\n if not security.invested:\n self.trailing_absolute_holdings_state.pop(symbol, None)\n continue\n\n position = PositionSide.LONG if security.holdings.is_long else PositionSide.SHORT\n absolute_holdings_value = security.holdings.absolute_holdings_value\n trailing_absolute_holdings_state = self.trailing_absolute_holdings_state.get(symbol)\n\n # Add newly invested security (if doesn't exist) or reset holdings state (if position changed)\n if trailing_absolute_holdings_state == None or position != trailing_absolute_holdings_state.position:\n self.trailing_absolute_holdings_state[symbol] = trailing_absolute_holdings_state = self.HoldingsState(position, security.holdings.absolute_holdings_cost)\n\n trailing_absolute_holdings_value = trailing_absolute_holdings_state.absolute_holdings_value\n\n # Check for new max (for long position) or min (for short position) absolute holdings value\n if ((position == PositionSide.LONG and trailing_absolute_holdings_value < absolute_holdings_value) or\n (position == PositionSide.SHORT and trailing_absolute_holdings_value > absolute_holdings_value)):\n self.trailing_absolute_holdings_state[symbol].absolute_holdings_value = absolute_holdings_value\n continue\n\n drawdown = abs((trailing_absolute_holdings_value - absolute_holdings_value) / trailing_absolute_holdings_value)\n\n if self.maximum_drawdown_percent < drawdown:\n # Cancel insights\n algorithm.insights.cancel([ symbol ]);\n\n self.trailing_absolute_holdings_state.pop(symbol, None)\n # liquidate\n risk_adjusted_targets.append(PortfolioTarget(symbol, 0))\n\n return risk_adjusted_targets\n\n class HoldingsState:\n def __init__(self, position, absolute_holdings_value):\n self.position = position\n self.absolute_holdings_value = absolute_holdings_value\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN RiskManagementModel that can be described like this\n: Provides an implementation of IRiskManagementModel that limits the drawdown of the portfolio to the specified percentage.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MaximumDrawdownPercentPortfolio(RiskManagementModel):\n '''Provides an implementation of IRiskManagementModel that limits the drawdown of the portfolio to the specified percentage.'''\n\n def __init__(self, maximum_drawdown_percent = 0.05, is_trailing = False):\n '''Initializes a new instance of the MaximumDrawdownPercentPortfolio class\n Args:\n maximum_drawdown_percent: The maximum percentage drawdown allowed for algorithm portfolio compared with starting value, defaults to 5% drawdown\n is_trailing: If \"false\", the drawdown will be relative to the starting value of the portfolio.\n If \"true\", the drawdown will be relative the last maximum portfolio value'''\n self.maximum_drawdown_percent = -abs(maximum_drawdown_percent)\n self.is_trailing = is_trailing\n self.initialised = False\n self.portfolio_high = 0\n\n def manage_risk(self, algorithm, targets):\n '''Manages the algorithm's risk at each time step\n Args:\n algorithm: The algorithm instance\n targets: The current portfolio targets to be assessed for risk'''\n current_value = algorithm.portfolio.total_portfolio_value\n\n if not self.initialised:\n self.portfolio_high = current_value # Set initial portfolio value\n self.initialised = True\n\n # Update trailing high value if in trailing mode\n if self.is_trailing and self.portfolio_high < current_value:\n self.portfolio_high = current_value\n return [] # return if new high reached\n\n pnl = self.get_total_drawdown_percent(current_value)\n if pnl < self.maximum_drawdown_percent and len(targets) != 0:\n self.initialised = False # reset the trailing high value for restart investing on next rebalcing period\n\n risk_adjusted_targets = []\n for target in targets:\n symbol = target.symbol\n\n # Cancel insights\n algorithm.insights.cancel([symbol])\n\n # liquidate\n risk_adjusted_targets.append(PortfolioTarget(symbol, 0))\n return risk_adjusted_targets\n\n return []\n\n def get_total_drawdown_percent(self, current_value):\n return (float(current_value) / float(self.portfolio_high)) - 1.0\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN UniverseSelectionModel that can be described like this\n: Provides a base class for defining equity coarse/fine fundamental selection models", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass FundamentalUniverseSelectionModel:\n '''Provides a base class for defining equity coarse/fine fundamental selection models'''\n \n def __init__(self,\n filterFineData = None,\n universeSettings = None):\n '''Initializes a new instance of the FundamentalUniverseSelectionModel class\n Args:\n filterFineData: [Obsolete] Fine and Coarse selection are merged\n universeSettings: The settings used when adding symbols to the algorithm, specify null to use algorithm.UniverseSettings'''\n self.filter_fine_data = filterFineData\n if self.filter_fine_data == None:\n self.fundamental_data = True\n else:\n self.fundamental_data = False\n self.market = Market.USA\n self.universe_settings = universeSettings\n\n\n def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:\n '''Creates a new fundamental universe using this class's selection functions\n Args:\n algorithm: The algorithm instance to create universes for\n Returns:\n The universe defined by this model'''\n if self.fundamental_data:\n universe_settings = algorithm.universe_settings if self.universe_settings is None else self.universe_settings\n # handle both 'Select' and 'select' for backwards compatibility\n selection = lambda fundamental: self.select(algorithm, fundamental)\n if hasattr(self, \"Select\") and callable(self.Select):\n selection = lambda fundamental: self.Select(algorithm, fundamental)\n universe = FundamentalUniverseFactory(self.market, universe_settings, selection)\n return [universe]\n else:\n universe = self.create_coarse_fundamental_universe(algorithm)\n if self.filter_fine_data:\n if universe.universe_settings.asynchronous:\n raise ValueError(\"Asynchronous universe setting is not supported for coarse & fine selections, please use the new Fundamental single pass selection\")\n selection = lambda fine: self.select_fine(algorithm, fine)\n if hasattr(self, \"SelectFine\") and callable(self.SelectFine):\n selection = lambda fine: self.SelectFine(algorithm, fine)\n universe = FineFundamentalFilteredUniverse(universe, selection)\n return [universe]\n\n\n def create_coarse_fundamental_universe(self, algorithm: QCAlgorithm) -> Universe:\n '''Creates the coarse fundamental universe object.\n This is provided to allow more flexibility when creating coarse universe.\n Args:\n algorithm: The algorithm instance\n Returns:\n The coarse fundamental universe'''\n universe_settings = algorithm.universe_settings if self.universe_settings is None else self.universe_settings\n return CoarseFundamentalUniverse(universe_settings, lambda coarse: self.filtered_select_coarse(algorithm, coarse))\n\n\n def filtered_select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:\n '''Defines the coarse fundamental selection function.\n If we're using fine fundamental selection than exclude symbols without fine data\n Args:\n algorithm: The algorithm instance\n coarse: The coarse fundamental data used to perform filtering\n Returns:\n An enumerable of symbols passing the filter'''\n if self.filter_fine_data:\n fundamental = filter(lambda c: c.has_fundamental_data, fundamental)\n if hasattr(self, \"SelectCoarse\") and callable(self.SelectCoarse):\n # handle both 'select_coarse' and 'SelectCoarse' for backwards compatibility\n return self.SelectCoarse(algorithm, fundamental)\n return self.select_coarse(algorithm, fundamental)\n\n\n def select(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:\n '''Defines the fundamental selection function.\n Args:\n algorithm: The algorithm instance\n fundamental: The fundamental data used to perform filtering\n Returns:\n An enumerable of symbols passing the filter'''\n raise NotImplementedError(\"Please overrride the 'select' fundamental function\")\n\n\n def select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:\n '''Defines the coarse fundamental selection function.\n Args:\n algorithm: The algorithm instance\n coarse: The coarse fundamental data used to perform filtering\n Returns:\n An enumerable of symbols passing the filter'''\n raise NotImplementedError(\"Please overrride the 'select' fundamental function\")\n\n\n def select_fine(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:\n '''Defines the fine fundamental selection function.\n Args:\n algorithm: The algorithm instance\n fine: The fine fundamental data used to perform filtering\n Returns:\n An enumerable of symbols passing the filter'''\n return [f.symbol for f in fundamental]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN UniverseSelectionModel that can be described like this\n: Provides an implementation of IUniverseSelectionMode that subscribes to option chains", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Selection.UniverseSelectionModel import UniverseSelectionModel\n\nclass OptionUniverseSelectionModel(UniverseSelectionModel):\n '''Provides an implementation of IUniverseSelectionMode that subscribes to option chains'''\n def __init__(self,\n refreshInterval,\n optionChainSymbolSelector,\n universeSettings = None):\n '''Creates a new instance of OptionUniverseSelectionModel\n Args:\n refreshInterval: Time interval between universe refreshes\n optionChainSymbolSelector: Selects symbols from the provided option chain\n universeSettings: Universe settings define attributes of created subscriptions, such as their resolution and the minimum time in universe before they can be removed'''\n self.next_refresh_time_utc = datetime.min\n\n self.refresh_interval = refreshInterval\n self.option_chain_symbol_selector = optionChainSymbolSelector\n self.universe_settings = universeSettings\n\n def get_next_refresh_time_utc(self):\n '''Gets the next time the framework should invoke the `CreateUniverses` method to refresh the set of universes.'''\n return self.next_refresh_time_utc\n\n def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:\n '''Creates a new fundamental universe using this class's selection functions\n Args:\n algorithm: The algorithm instance to create universes for\n Returns:\n The universe defined by this model'''\n self.next_refresh_time_utc = (algorithm.utc_time + self.refresh_interval).date()\n\n uniqueUnderlyingSymbols = set()\n for option_symbol in self.option_chain_symbol_selector(algorithm.utc_time):\n if not Extensions.is_option(option_symbol.security_type):\n raise ValueError(\"optionChainSymbolSelector must return option, index options, or futures options symbols.\")\n\n # prevent creating duplicate option chains -- one per underlying\n if option_symbol.underlying not in uniqueUnderlyingSymbols:\n uniqueUnderlyingSymbols.add(option_symbol.underlying)\n selection = self.filter\n if hasattr(self, \"Filter\") and callable(self.Filter):\n selection = self.Filter\n yield Extensions.create_option_chain(algorithm, option_symbol, selection, self.universe_settings)\n\n def filter(self, filter):\n '''Defines the option chain universe filter'''\n # NOP\n return filter\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN UniverseSelectionModel that can be described like this\n: Universe selection model that selects the constituents of an ETF.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Selection.UniverseSelectionModel import UniverseSelectionModel\n\nclass ETFConstituentsUniverseSelectionModel(UniverseSelectionModel):\n '''Universe selection model that selects the constituents of an ETF.'''\n\n def __init__(self,\n etf_symbol,\n universe_settings = None,\n universe_filter_func = None):\n '''Initializes a new instance of the ETFConstituentsUniverseSelectionModel class\n Args:\n etfSymbol: Symbol of the ETF to get constituents for\n universeSettings: Universe settings\n universeFilterFunc: Function to filter universe results'''\n if type(etf_symbol) is str:\n symbol = SymbolCache.try_get_symbol(etf_symbol, None)\n if symbol[0] and symbol[1].security_type == SecurityType.EQUITY:\n self.etf_symbol = symbol[1]\n else:\n self.etf_symbol = Symbol.create(etf_symbol, SecurityType.EQUITY, Market.USA)\n else:\n self.etf_symbol = etf_symbol\n self.universe_settings = universe_settings\n self.universe_filter_function = universe_filter_func\n\n self.universe = None\n\n def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:\n '''Creates a new ETF constituents universe using this class's selection function\n Args:\n algorithm: The algorithm instance to create universes for\n Returns:\n The universe defined by this model'''\n if self.universe is None:\n self.universe = algorithm.universe.etf(self.etf_symbol, self.universe_settings, self.universe_filter_function)\n return [self.universe]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN UniverseSelectionModel that can be described like this\n: Defines the QC500 universe as a universe selection model for framework algorithm", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel\nfrom itertools import groupby\nfrom math import ceil\n\nclass QC500UniverseSelectionModel(FundamentalUniverseSelectionModel):\n '''Defines the QC500 universe as a universe selection model for framework algorithm\n For details: https://github.com/QuantConnect/Lean/pull/1663'''\n\n def __init__(self, filterFineData = True, universeSettings = None):\n '''Initializes a new default instance of the QC500UniverseSelectionModel'''\n super().__init__(filterFineData, universeSettings)\n self.number_of_symbols_coarse = 1000\n self.number_of_symbols_fine = 500\n self.dollar_volume_by_symbol = {}\n self.last_month = -1\n\n def select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]):\n '''Performs coarse selection for the QC500 constituents.\n The stocks must have fundamental data\n The stock must have positive previous-day close price\n The stock must have positive volume on the previous trading day'''\n if algorithm.time.month == self.last_month:\n return Universe.UNCHANGED\n\n sorted_by_dollar_volume = sorted([x for x in fundamental if x.has_fundamental_data and x.volume > 0 and x.price > 0],\n key = lambda x: x.dollar_volume, reverse=True)[:self.number_of_symbols_coarse]\n\n self.dollar_volume_by_symbol = {x.Symbol:x.dollar_volume for x in sorted_by_dollar_volume}\n\n # If no security has met the QC500 criteria, the universe is unchanged.\n # A new selection will be attempted on the next trading day as self.lastMonth is not updated\n if len(self.dollar_volume_by_symbol) == 0:\n return Universe.UNCHANGED\n\n # return the symbol objects our sorted collection\n return list(self.dollar_volume_by_symbol.keys())\n\n def select_fine(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]):\n '''Performs fine selection for the QC500 constituents\n The company's headquarter must in the U.S.\n The stock must be traded on either the NYSE or NASDAQ\n At least half a year since its initial public offering\n The stock's market cap must be greater than 500 million'''\n\n sorted_by_sector = sorted([x for x in fundamental if x.company_reference.country_id == \"USA\"\n and x.company_reference.primary_exchange_id in [\"NYS\",\"NAS\"]\n and (algorithm.time - x.security_reference.ipo_date).days > 180\n and x.market_cap > 5e8],\n key = lambda x: x.company_reference.industry_template_code)\n\n count = len(sorted_by_sector)\n\n # If no security has met the QC500 criteria, the universe is unchanged.\n # A new selection will be attempted on the next trading day as self.lastMonth is not updated\n if count == 0:\n return Universe.UNCHANGED\n\n # Update self.lastMonth after all QC500 criteria checks passed\n self.last_month = algorithm.time.month\n\n percent = self.number_of_symbols_fine / count\n sorted_by_dollar_volume = []\n\n # select stocks with top dollar volume in every single sector\n for code, g in groupby(sorted_by_sector, lambda x: x.company_reference.industry_template_code):\n y = sorted(g, key = lambda x: self.dollar_volume_by_symbol[x.Symbol], reverse = True)\n c = ceil(len(y) * percent)\n sorted_by_dollar_volume.extend(y[:c])\n\n sorted_by_dollar_volume = sorted(sorted_by_dollar_volume, key = lambda x: self.dollar_volume_by_symbol[x.Symbol], reverse=True)\n return [x.Symbol for x in sorted_by_dollar_volume[:self.number_of_symbols_fine]]\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN UniverseSelectionModel that can be described like this\n: Provides an implementation of IUniverseSelectionMode that subscribes to future chains", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nfrom Selection.UniverseSelectionModel import UniverseSelectionModel\n\nclass FutureUniverseSelectionModel(UniverseSelectionModel):\n '''Provides an implementation of IUniverseSelectionMode that subscribes to future chains'''\n def __init__(self,\n refreshInterval,\n futureChainSymbolSelector,\n universeSettings = None):\n '''Creates a new instance of FutureUniverseSelectionModel\n Args:\n refreshInterval: Time interval between universe refreshes\n futureChainSymbolSelector: Selects symbols from the provided future chain\n universeSettings: Universe settings define attributes of created subscriptions, such as their resolution and the minimum time in universe before they can be removed'''\n self.next_refresh_time_utc = datetime.min\n\n self.refresh_interval = refreshInterval\n self.future_chain_symbol_selector = futureChainSymbolSelector\n self.universe_settings = universeSettings\n\n def get_next_refresh_time_utc(self):\n '''Gets the next time the framework should invoke the `CreateUniverses` method to refresh the set of universes.'''\n return self.next_refresh_time_utc\n\n def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:\n '''Creates a new fundamental universe using this class's selection functions\n Args:\n algorithm: The algorithm instance to create universes for\n Returns:\n The universe defined by this model'''\n self.next_refresh_time_utc = algorithm.utc_time + self.refresh_interval\n\n unique_symbols = set()\n for future_symbol in self.future_chain_symbol_selector(algorithm.utc_time):\n if future_symbol.SecurityType != SecurityType.FUTURE:\n raise ValueError(\"futureChainSymbolSelector must return future symbols.\")\n\n # prevent creating duplicate future chains -- one per symbol\n if future_symbol not in unique_symbols:\n unique_symbols.add(future_symbol)\n selection = self.filter\n if hasattr(self, \"Filter\") and callable(self.Filter):\n selection = self.Filter\n for universe in Extensions.create_future_chain(algorithm, future_symbol, selection, self.universe_settings):\n yield universe\n\n def filter(self, filter):\n '''Defines the future chain universe filter'''\n # NOP\n return filter\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN UniverseSelectionModel that can be described like this\n: Provides an implementation of FundamentalUniverseSelectionModel that subscribes to", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel\n\nclass EmaCrossUniverseSelectionModel(FundamentalUniverseSelectionModel):\n '''Provides an implementation of FundamentalUniverseSelectionModel that subscribes to\n symbols with the larger delta by percentage between the two exponential moving average'''\n\n def __init__(self,\n fastPeriod = 100,\n slowPeriod = 300,\n universeCount = 500,\n universeSettings = None):\n '''Initializes a new instance of the EmaCrossUniverseSelectionModel class\n Args:\n fastPeriod: Fast EMA period\n slowPeriod: Slow EMA period\n universeCount: Maximum number of members of this universe selection\n universeSettings: The settings used when adding symbols to the algorithm, specify null to use algorithm.UniverseSettings'''\n super().__init__(False, universeSettings)\n self.fast_period = fastPeriod\n self.slow_period = slowPeriod\n self.universe_count = universeCount\n self.tolerance = 0.01\n # holds our coarse fundamental indicators by symbol\n self.averages = {}\n\n def select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:\n '''Defines the coarse fundamental selection function.\n Args:\n algorithm: The algorithm instance\n fundamental: The coarse fundamental data used to perform filtering\n Returns:\n An enumerable of symbols passing the filter'''\n filtered = []\n\n for cf in fundamental:\n if cf.symbol not in self.averages:\n self.averages[cf.symbol] = self.SelectionData(cf.symbol, self.fast_period, self.slow_period)\n\n # grab th SelectionData instance for this symbol\n avg = self.averages.get(cf.symbol)\n\n # Update returns true when the indicators are ready, so don't accept until they are\n # and only pick symbols who have their fastPeriod-day ema over their slowPeriod-day ema\n if avg.update(cf.end_time, cf.adjusted_price) and avg.fast > avg.slow * (1 + self.tolerance):\n filtered.append(avg)\n\n # prefer symbols with a larger delta by percentage between the two averages\n filtered = sorted(filtered, key=lambda avg: avg.scaled_delta, reverse = True)\n\n # we only need to return the symbol and return 'universeCount' symbols\n return [x.symbol for x in filtered[:self.universe_count]]\n\n # class used to improve readability of the coarse selection function\n class SelectionData:\n def __init__(self, symbol, fast_period, slow_period):\n self.symbol = symbol\n self.fast_ema = ExponentialMovingAverage(fast_period)\n self.slow_ema = ExponentialMovingAverage(slow_period)\n\n @property\n def fast(self):\n return float(self.fast_ema.current.value)\n\n @property\n def slow(self):\n return float(self.slow_ema.current.value)\n\n # computes an object score of how much large the fast is than the slow\n @property\n def scaled_delta(self):\n return (self.fast - self.slow) / ((self.fast + self.slow) / 2)\n\n # updates the EMAFast and EMASlow indicators, returning true when they're both ready\n def update(self, time, value):\n return self.slow_ema.update(time, value) & self.fast_ema.update(time, value)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN PortfolioConstructionModel that can be described like this\n: Provides an implementation of Mean-Variance portfolio optimization based on modern portfolio theory.\nThe default model uses the MinimumVariancePortfolioOptimizer that accepts a 63-row matrix of 1-day returns.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Portfolio.MinimumVariancePortfolioOptimizer import MinimumVariancePortfolioOptimizer\n\nclass MeanVarianceOptimizationPortfolioConstructionModel(PortfolioConstructionModel):\n def __init__(self,\n rebalance = Resolution.DAILY,\n portfolio_bias = PortfolioBias.LONG_SHORT,\n lookback = 1,\n period = 63,\n resolution = Resolution.DAILY,\n target_return = 0.02,\n optimizer = None):\n \"\"\"Initialize the model\n Args:\n rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.\n If None will be ignored.\n The function returns the next expected rebalance time for a given algorithm UTC DateTime.\n The function returns null if unknown, in which case the function will be called again in the\n next loop. Returning current time will trigger rebalance.\n portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)\n lookback(int): Historical return lookback period\n period(int): The time interval of history price to calculate the weight\n resolution: The resolution of the history price\n optimizer(class): Method used to compute the portfolio weights\"\"\"\n super().__init__()\n self.lookback = lookback\n self.period = period\n self.resolution = resolution\n self.portfolio_bias = portfolio_bias\n self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)\n\n lower = 0 if portfolio_bias == PortfolioBias.LONG else -1\n upper = 0 if portfolio_bias == PortfolioBias.SHORT else 1\n self.optimizer = MinimumVariancePortfolioOptimizer(lower, upper, target_return) if optimizer is None else optimizer\n\n self.symbol_data_by_symbol = {}\n\n # If the argument is an instance of Resolution or Timedelta\n # Redefine rebalancing_func\n rebalancing_func = rebalance\n if isinstance(rebalance, Resolution):\n rebalance = Extensions.to_time_span(rebalance)\n if isinstance(rebalance, timedelta):\n rebalancing_func = lambda dt: dt + rebalance\n if rebalancing_func:\n self.set_rebalancing_func(rebalancing_func)\n\n def should_create_target_for_insight(self, insight):\n if len(PortfolioConstructionModel.filter_invalid_insight_magnitude(self.algorithm, [insight])) == 0:\n return False\n\n symbol_data = self.symbol_data_by_symbol.get(insight.symbol)\n if insight.magnitude is None:\n self.algorithm.set_run_time_error(ArgumentNullException('MeanVarianceOptimizationPortfolioConstructionModel does not accept \\'None\\' as Insight.magnitude. Please checkout the selected Alpha Model specifications.'))\n return False\n symbol_data.add(self.algorithm.time, insight.magnitude)\n\n return True\n\n def determine_target_percent(self, active_insights):\n \"\"\"\n Will determine the target percent for each insight\n Args:\n Returns:\n \"\"\"\n targets = {}\n\n # If we have no insights just return an empty target list\n if len(active_insights) == 0:\n return targets\n\n symbols = [insight.symbol for insight in active_insights]\n\n # Create a dictionary keyed by the symbols in the insights with an pandas.series as value to create a data frame\n returns = { str(symbol.id) : data.return_ for symbol, data in self.symbol_data_by_symbol.items() if symbol in symbols }\n returns = pd.DataFrame(returns)\n\n # The portfolio optimizer finds the optional weights for the given data\n weights = self.optimizer.optimize(returns)\n weights = pd.Series(weights, index = returns.columns)\n\n # Create portfolio targets from the specified insights\n for insight in active_insights:\n weight = weights[str(insight.symbol.id)]\n\n # don't trust the optimizer\n if self.portfolio_bias != PortfolioBias.LONG_SHORT and self.sign(weight) != self.portfolio_bias:\n weight = 0\n targets[insight] = weight\n\n return targets\n\n def on_securities_changed(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n\n # clean up data for removed securities\n super().on_securities_changed(algorithm, changes)\n for removed in changes.removed_securities:\n symbol_data = self.symbol_data_by_symbol.pop(removed.symbol, None)\n symbol_data.reset()\n\n # initialize data for added securities\n symbols = [x.symbol for x in changes.added_securities]\n for symbol in [x for x in symbols if x not in self.symbol_data_by_symbol]:\n self.symbol_data_by_symbol[symbol] = self.MeanVarianceSymbolData(symbol, self.lookback, self.period)\n\n history = algorithm.history[TradeBar](symbols, self.lookback * self.period, self.resolution)\n for bars in history:\n for symbol, bar in bars.items():\n symbol_data = self.symbol_data_by_symbol.get(symbol).update(bar.end_time, bar.value)\n\n class MeanVarianceSymbolData:\n '''Contains data specific to a symbol required by this model'''\n def __init__(self, symbol, lookback, period):\n self._symbol = symbol\n self.roc = RateOfChange(f'{symbol}.roc({lookback})', lookback)\n self.roc.updated += self.on_rate_of_change_updated\n self.window = RollingWindow(period)\n\n def reset(self):\n self.roc.updated -= self.on_rate_of_change_updated\n self.roc.reset()\n self.window.reset()\n\n def update(self, time, value):\n return self.roc.update(time, value)\n\n def on_rate_of_change_updated(self, roc, value):\n if roc.is_ready:\n self.window.add(value)\n\n def add(self, time, value):\n item = IndicatorDataPoint(self._symbol, time, value)\n self.window.add(item)\n\n # Get symbols' returns, we use simple return according to\n # Meucci, Attilio, Quant Nugget 2: Linear vs. Compounded Returns \u2013 Common Pitfalls in Portfolio Management (May 1, 2010).\n # GARP Risk Professional, pp. 49-51, April 2010 , Available at SSRN: https://ssrn.com/abstract=1586656\n @property\n def return_(self):\n return pd.Series(\n data = [x.value for x in self.window],\n index = [x.end_time for x in self.window])\n\n @property\n def is_ready(self):\n return self.window.is_ready\n\n def __str__(self, **kwargs):\n return '{}: {:.2%}'.format(self.roc.name, self.window[0])\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN PortfolioConstructionModel that can be described like this\n: Provides an implementation of Black-Litterman portfolio optimization. The model adjusts equilibrium market\nreturns by incorporating views from multiple alpha models and therefore to get the optimal risky portfolio\nreflecting those views. If insights of all alpha models have None magnitude or there are linearly dependent\nvectors in link matrix of views, the expected return would be the implied excess equilibrium return.\nThe interval of weights in optimization method can be changed based on the long-short algorithm.\nThe default model uses the 0.0025 as weight-on-views scalar parameter tau and\nMaximumSharpeRatioPortfolioOptimizer that accepts a 63-row matrix of 1-day returns.", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Portfolio.MaximumSharpeRatioPortfolioOptimizer import MaximumSharpeRatioPortfolioOptimizer\nfrom itertools import groupby\nfrom numpy import dot, transpose\nfrom numpy.linalg import inv\n\nclass BlackLittermanOptimizationPortfolioConstructionModel(PortfolioConstructionModel):\n def __init__(self,\n rebalance = Resolution.DAILY,\n portfolio_bias = PortfolioBias.LONG_SHORT,\n lookback = 1,\n period = 63,\n resolution = Resolution.DAILY,\n risk_free_rate = 0,\n delta = 2.5,\n tau = 0.05,\n optimizer = None):\n \"\"\"Initialize the model\n Args:\n rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.\n If None will be ignored.\n The function returns the next expected rebalance time for a given algorithm UTC DateTime.\n The function returns null if unknown, in which case the function will be called again in the\n next loop. Returning current time will trigger rebalance.\n portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)\n lookback(int): Historical return lookback period\n period(int): The time interval of history price to calculate the weight\n resolution: The resolution of the history price\n risk_free_rate(float): The risk free rate\n delta(float): The risk aversion coeffficient of the market portfolio\n tau(float): The model parameter indicating the uncertainty of the CAPM prior\"\"\"\n super().__init__()\n self.lookback = lookback\n self.period = period\n self.resolution = resolution\n self.risk_free_rate = risk_free_rate\n self.delta = delta\n self.tau = tau\n self.portfolio_bias = portfolio_bias\n\n lower = 0 if portfolio_bias == PortfolioBias.LONG else -1\n upper = 0 if portfolio_bias == PortfolioBias.SHORT else 1\n self.optimizer = MaximumSharpeRatioPortfolioOptimizer(lower, upper, risk_free_rate) if optimizer is None else optimizer\n\n self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)\n self.symbol_data_by_symbol = {}\n\n # If the argument is an instance of Resolution or Timedelta\n # Redefine rebalancing_func\n rebalancing_func = rebalance\n if isinstance(rebalance, Resolution):\n rebalance = Extensions.to_time_span(rebalance)\n if isinstance(rebalance, timedelta):\n rebalancing_func = lambda dt: dt + rebalance\n if rebalancing_func:\n self.set_rebalancing_func(rebalancing_func)\n\n def should_create_target_for_insight(self, insight):\n return PortfolioConstructionModel.filter_invalid_insight_magnitude(self.algorithm, [ insight ])\n\n def determine_target_percent(self, last_active_insights):\n targets = {}\n\n # Get view vectors\n p, q = self.get_views(last_active_insights)\n if p is not None:\n returns = dict()\n # Updates the BlackLittermanSymbolData with insights\n # Create a dictionary keyed by the symbols in the insights with an pandas.Series as value to create a data frame\n for insight in last_active_insights:\n symbol = insight.symbol\n symbol_data = self.symbol_data_by_symbol.get(symbol, self.BlackLittermanSymbolData(symbol, self.lookback, self.period))\n if insight.magnitude is None:\n self.algorithm.set_run_time_error(ArgumentNullException('BlackLittermanOptimizationPortfolioConstructionModel does not accept \\'None\\' as Insight.magnitude. Please make sure your Alpha Model is generating Insights with the Magnitude property set.'))\n return targets\n symbol_data.add(insight.generated_time_utc, insight.magnitude)\n returns[symbol] = symbol_data.return_\n\n returns = pd.DataFrame(returns)\n\n # Calculate prior estimate of the mean and covariance\n pi, sigma = self.get_equilibrium_return(returns)\n\n # Calculate posterior estimate of the mean and covariance\n pi, sigma = self.apply_blacklitterman_master_formula(pi, sigma, p, q)\n\n # Create portfolio targets from the specified insights\n weights = self.optimizer.optimize(returns, pi, sigma)\n weights = pd.Series(weights, index = sigma.columns)\n\n for symbol, weight in weights.items():\n for insight in last_active_insights:\n if str(insight.symbol) == str(symbol):\n # don't trust the optimizer\n if self.portfolio_bias != PortfolioBias.LONG_SHORT and self.sign(weight) != self.portfolio_bias:\n weight = 0\n targets[insight] = weight\n break\n\n return targets\n\n def get_target_insights(self):\n # Get insight that haven't expired of each symbol that is still in the universe\n active_insights = filter(self.should_create_target_for_insight,\n self.algorithm.insights.get_active_insights(self.algorithm.utc_time))\n\n # Get the last generated active insight for each symbol\n last_active_insights = []\n for source_model, f in groupby(sorted(active_insights, key = lambda ff: ff.source_model), lambda fff: fff.source_model):\n for symbol, g in groupby(sorted(list(f), key = lambda gg: gg.symbol), lambda ggg: ggg.symbol):\n last_active_insights.append(sorted(g, key = lambda x: x.generated_time_utc)[-1])\n return last_active_insights\n\n def on_securities_changed(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n\n # Get removed symbol and invalidate them in the insight collection\n super().on_securities_changed(algorithm, changes)\n\n for security in changes.removed_securities:\n symbol = security.symbol\n symbol_data = self.symbol_data_by_symbol.pop(symbol, None)\n if symbol_data is not None:\n symbol_data.reset()\n\n # initialize data for added securities\n added_symbols = { x.symbol: x.exchange.time_zone for x in changes.added_securities }\n history = algorithm.history(list(added_symbols.keys()), self.lookback * self.period, self.resolution)\n\n if history.empty:\n return\n\n history = history.close.unstack(0)\n symbols = history.columns\n\n for symbol, timezone in added_symbols.items():\n if str(symbol) not in symbols:\n continue\n\n symbol_data = self.symbol_data_by_symbol.get(symbol, self.BlackLittermanSymbolData(symbol, self.lookback, self.period))\n for time, close in history[symbol].items():\n utc_time = Extensions.convert_to_utc(time, timezone)\n symbol_data.update(utc_time, close)\n\n self.symbol_data_by_symbol[symbol] = symbol_data\n\n def apply_blacklitterman_master_formula(self, Pi, Sigma, P, Q):\n '''Apply Black-Litterman master formula\n http://www.blacklitterman.org/cookbook.html\n Args:\n Pi: Prior/Posterior mean array\n Sigma: Prior/Posterior covariance matrix\n P: A matrix that identifies the assets involved in the views (size: K x N)\n Q: A view vector (size: K x 1)'''\n ts = self.tau * Sigma\n\n # Create the diagonal Sigma matrix of error terms from the expressed views\n omega = np.dot(np.dot(P, ts), P.T) * np.eye(Q.shape[0])\n if np.linalg.det(omega) == 0:\n return Pi, Sigma\n\n A = np.dot(np.dot(ts, P.T), inv(np.dot(np.dot(P, ts), P.T) + omega))\n\n Pi = np.squeeze(np.asarray((\n np.expand_dims(Pi, axis=0).T +\n np.dot(A, (Q - np.expand_dims(np.dot(P, Pi.T), axis=1))))\n ))\n\n M = ts - np.dot(np.dot(A, P), ts)\n Sigma = (Sigma + M) * self.delta\n\n return Pi, Sigma\n\n def get_equilibrium_return(self, returns):\n '''Calculate equilibrium returns and covariance\n Args:\n returns: Matrix of returns where each column represents a security and each row returns for the given date/time (size: K x N)\n Returns:\n equilibrium_return: Array of double of equilibrium returns\n cov: Multi-dimensional array of double with the portfolio covariance of returns (size: K x K)'''\n\n size = len(returns.columns)\n # equal weighting scheme\n W = np.array([1/size]*size)\n # the covariance matrix of excess returns (N x N matrix)\n cov = returns.cov()*252\n # annualized return\n annual_return = np.sum(((1 + returns.mean())**252 -1) * W)\n # annualized variance of return\n annual_variance = dot(W.T, dot(cov, W))\n # the risk aversion coefficient\n risk_aversion = (annual_return - self.risk_free_rate ) / annual_variance\n # the implied excess equilibrium return Vector (N x 1 column vector)\n equilibrium_return = dot(dot(risk_aversion, cov), W)\n\n return equilibrium_return, cov\n\n def get_views(self, insights):\n '''Generate views from multiple alpha models\n Args\n insights: Array of insight that represent the investors' views\n Returns\n P: A matrix that identifies the assets involved in the views (size: K x N)\n Q: A view vector (size: K x 1)'''\n try:\n P = {}\n Q = {}\n symbols = set(insight.symbol for insight in insights)\n\n for model, group in groupby(insights, lambda x: x.source_model):\n group = list(group)\n\n up_insights_sum = 0.0\n dn_insights_sum = 0.0\n for insight in group:\n if insight.direction == InsightDirection.UP:\n up_insights_sum = up_insights_sum + np.abs(insight.magnitude)\n if insight.direction == InsightDirection.DOWN:\n dn_insights_sum = dn_insights_sum + np.abs(insight.magnitude)\n\n q = up_insights_sum if up_insights_sum > dn_insights_sum else dn_insights_sum\n if q == 0:\n continue\n\n Q[model] = q\n\n # generate the link matrix of views: P\n P[model] = dict()\n for insight in group:\n value = insight.direction * np.abs(insight.magnitude)\n P[model][insight.symbol] = value / q\n # Add zero for other symbols that are listed but active insight\n for symbol in symbols:\n if symbol not in P[model]:\n P[model][symbol] = 0\n\n Q = np.array([[x] for x in Q.values()])\n if len(Q) > 0:\n P = np.array([list(x.values()) for x in P.values()])\n return P, Q\n except:\n pass\n\n return None, None\n\n\n class BlackLittermanSymbolData:\n '''Contains data specific to a symbol required by this model'''\n def __init__(self, symbol, lookback, period):\n self._symbol = symbol\n self.roc = RateOfChange(f'{symbol}.roc({lookback})', lookback)\n self.roc.updated += self.on_rate_of_change_updated\n self.window = RollingWindow(period)\n\n def reset(self):\n self.roc.updated -= self.on_rate_of_change_updated\n self.roc.reset()\n self.window.reset()\n\n def update(self, utc_time, close):\n self.roc.update(utc_time, close)\n\n def on_rate_of_change_updated(self, roc, value):\n if roc.is_ready:\n self.window.add(value)\n\n def add(self, time, value):\n if self.window.samples > 0 and self.window[0].end_time == time:\n return\n\n item = IndicatorDataPoint(self._symbol, time, value)\n self.window.add(item)\n\n @property\n def return_(self):\n return pd.Series(\n data = [x.value for x in self.window],\n index = [x.end_time for x in self.window])\n\n @property\n def is_ready(self):\n return self.window.is_ready\n\n def __str__(self, **kwargs):\n return f'{self.roc.name}: {(1 + self.window[0])**252 - 1:.2%}'\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN PortfolioConstructionModel that can be described like this\n: Provides an implementation of IPortfolioConstructionModel that gives equal weighting to all securities.", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass EqualWeightingPortfolioConstructionModel(PortfolioConstructionModel):\n '''Provides an implementation of IPortfolioConstructionModel that gives equal weighting to all securities.\n The target percent holdings of each security is 1/N where N is the number of securities.\n For insights of direction InsightDirection.UP, long targets are returned and\n for insights of direction InsightDirection.DOWN, short targets are returned.'''\n\n def __init__(self, rebalance = Resolution.DAILY, portfolio_bias = PortfolioBias.LONG_SHORT):\n '''Initialize a new instance of EqualWeightingPortfolioConstructionModel\n Args:\n rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.\n If None will be ignored.\n The function returns the next expected rebalance time for a given algorithm UTC DateTime.\n The function returns null if unknown, in which case the function will be called again in the\n next loop. Returning current time will trigger rebalance.\n portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)'''\n super().__init__()\n self.portfolio_bias = portfolio_bias\n\n # If the argument is an instance of Resolution or Timedelta\n # Redefine rebalancing_func\n rebalancing_func = rebalance\n if isinstance(rebalance, Resolution):\n rebalance = Extensions.to_time_span(rebalance)\n if isinstance(rebalance, timedelta):\n rebalancing_func = lambda dt: dt + rebalance\n if rebalancing_func:\n self.set_rebalancing_func(rebalancing_func)\n\n def determine_target_percent(self, active_insights):\n '''Will determine the target percent for each insight\n Args:\n active_insights: The active insights to generate a target for'''\n result = {}\n\n # give equal weighting to each security\n count = sum(x.direction != InsightDirection.FLAT and self.respect_portfolio_bias(x) for x in active_insights)\n percent = 0 if count == 0 else 1.0 / count\n for insight in active_insights:\n result[insight] = (insight.direction if self.respect_portfolio_bias(insight) else InsightDirection.FLAT) * percent\n return result\n\n def respect_portfolio_bias(self, insight):\n '''Method that will determine if a given insight respects the portfolio bias\n Args:\n insight: The insight to create a target for\n '''\n return self.portfolio_bias == PortfolioBias.LONG_SHORT or insight.direction == self.portfolio_bias\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN PortfolioConstructionModel that can be described like this\n: Provides an implementation of IPortfolioConstructionModel that allocates percent of account", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\n\nclass AccumulativeInsightPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):\n '''Provides an implementation of IPortfolioConstructionModel that allocates percent of account\n to each insight, defaulting to 3%.\n For insights of direction InsightDirection.UP, long targets are returned and\n for insights of direction InsightDirection.DOWN, short targets are returned.\n By default, no rebalancing shall be done.\n Rules:\n 1. On active Up insight, increase position size by percent\n 2. On active Down insight, decrease position size by percent\n 3. On active Flat insight, move by percent towards 0\n 4. On expired insight, and no other active insight, emits a 0 target'''\n\n def __init__(self, rebalance = None, portfolio_bias = PortfolioBias.LONG_SHORT, percent = 0.03):\n '''Initialize a new instance of AccumulativeInsightPortfolioConstructionModel\n Args:\n rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.\n If None will be ignored.\n The function returns the next expected rebalance time for a given algorithm UTC DateTime.\n The function returns null if unknown, in which case the function will be called again in the\n next loop. Returning current time will trigger rebalance.\n portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)\n percent: percent of portfolio to allocate to each position'''\n super().__init__(rebalance)\n self.portfolio_bias = portfolio_bias\n self.percent = abs(percent)\n self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)\n\n def determine_target_percent(self, active_insights):\n '''Will determine the target percent for each insight\n Args:\n active_insights: The active insights to generate a target for'''\n percent_per_symbol = {}\n\n insights = sorted(self.algorithm.insights.get_active_insights(self.current_utc_time), key=lambda insight: insight.generated_time_utc)\n\n for insight in insights:\n target_percent = 0\n if insight.symbol in percent_per_symbol:\n target_percent = percent_per_symbol[insight.symbol]\n if insight.direction == InsightDirection.FLAT:\n # We received a Flat\n # if adding or subtracting will push past 0, then make it 0\n if abs(target_percent) < self.percent:\n target_percent = 0\n else:\n # otherwise, we flatten by percent\n target_percent += (-self.percent if target_percent > 0 else self.percent)\n target_percent += self.percent * insight.direction\n\n # adjust to respect portfolio bias\n if self.portfolio_bias != PortfolioBias.LONG_SHORT and self.sign(target_percent) != self.portfolio_bias:\n target_percent = 0\n\n percent_per_symbol[insight.symbol] = target_percent\n\n return dict((insight, percent_per_symbol[insight.symbol]) for insight in active_insights)\n\n def create_targets(self, algorithm, insights):\n '''Create portfolio targets from the specified insights\n Args:\n algorithm: The algorithm instance\n insights: The insights to create portfolio targets from\n Returns:\n An enumerable of portfolio targets to be sent to the execution model'''\n self.current_utc_time = algorithm.utc_time\n return super().create_targets(algorithm, insights)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN PortfolioConstructionModel that can be described like this\n: Provides an implementation of IPortfolioConstructionModel that generates percent targets based on the", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\n\nclass InsightWeightingPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):\n '''Provides an implementation of IPortfolioConstructionModel that generates percent targets based on the\n Insight.WEIGHT. The target percent holdings of each Symbol is given by the Insight.WEIGHT from the last\n active Insight for that symbol.\n For insights of direction InsightDirection.UP, long targets are returned and for insights of direction\n InsightDirection.DOWN, short targets are returned.\n If the sum of all the last active Insight per symbol is bigger than 1, it will factor down each target\n percent holdings proportionally so the sum is 1.\n It will ignore Insight that have no Insight.WEIGHT value.'''\n\n def __init__(self, rebalance = Resolution.DAILY, portfolio_bias = PortfolioBias.LONG_SHORT):\n '''Initialize a new instance of InsightWeightingPortfolioConstructionModel\n Args:\n rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.\n If None will be ignored.\n The function returns the next expected rebalance time for a given algorithm UTC DateTime.\n The function returns null if unknown, in which case the function will be called again in the\n next loop. Returning current time will trigger rebalance.\n portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)'''\n super().__init__(rebalance, portfolio_bias)\n\n def should_create_target_for_insight(self, insight):\n '''Method that will determine if the portfolio construction model should create a\n target for this insight\n Args:\n insight: The insight to create a target for'''\n # Ignore insights that don't have Weight value\n return insight.weight is not None\n\n def determine_target_percent(self, active_insights):\n '''Will determine the target percent for each insight\n Args:\n active_insights: The active insights to generate a target for'''\n result = {}\n\n # We will adjust weights proportionally in case the sum is > 1 so it sums to 1.\n weight_sums = sum(self.get_value(insight) for insight in active_insights if self.respect_portfolio_bias(insight))\n weight_factor = 1.0\n if weight_sums > 1:\n weight_factor = 1 / weight_sums\n for insight in active_insights:\n result[insight] = (insight.direction if self.respect_portfolio_bias(insight) else InsightDirection.FLAT) * self.get_value(insight) * weight_factor\n return result\n\n def get_value(self, insight):\n '''Method that will determine which member will be used to compute the weights and gets its value\n Args:\n insight: The insight to create a target for\n Returns:\n The value of the selected insight member'''\n return abs(insight.weight)\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN PortfolioConstructionModel that can be described like this\n: Provides an implementation of IPortfolioConstructionModel that", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel\n\nclass SectorWeightingPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):\n '''Provides an implementation of IPortfolioConstructionModel that\n generates percent targets based on the CompanyReference.industry_template_code.\n The target percent holdings of each sector is 1/S where S is the number of sectors and\n the target percent holdings of each security is 1/N where N is the number of securities of each sector.\n For insights of direction InsightDirection.UP, long targets are returned and for insights of direction\n InsightDirection.DOWN, short targets are returned.\n It will ignore Insight for symbols that have no CompanyReference.industry_template_code'''\n\n def __init__(self, rebalance = Resolution.DAILY):\n '''Initialize a new instance of InsightWeightingPortfolioConstructionModel\n Args:\n rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.\n If None will be ignored.\n The function returns the next expected rebalance time for a given algorithm UTC DateTime.\n The function returns null if unknown, in which case the function will be called again in the\n next loop. Returning current time will trigger rebalance.'''\n super().__init__(rebalance)\n self.sector_code_by_symbol = dict()\n\n def should_create_target_for_insight(self, insight):\n '''Method that will determine if the portfolio construction model should create a\n target for this insight\n Args:\n insight: The insight to create a target for'''\n return insight.symbol in self.sector_code_by_symbol\n\n def determine_target_percent(self, active_insights):\n '''Will determine the target percent for each insight\n Args:\n active_insights: The active insights to generate a target for'''\n result = dict()\n\n insight_by_sector_code = dict()\n\n for insight in active_insights:\n if insight.direction == InsightDirection.FLAT:\n result[insight] = 0\n continue\n\n sector_code = self.sector_code_by_symbol.get(insight.symbol)\n insights = insight_by_sector_code.pop(sector_code, list())\n\n insights.append(insight)\n insight_by_sector_code[sector_code] = insights\n\n # give equal weighting to each sector\n sector_percent = 0 if len(insight_by_sector_code) == 0 else 1.0 / len(insight_by_sector_code)\n\n for _, insights in insight_by_sector_code.items():\n # give equal weighting to each security\n count = len(insights)\n percent = 0 if count == 0 else sector_percent / count\n for insight in insights:\n result[insight] = insight.direction * percent\n\n return result\n\n def on_securities_changed(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n for security in changes.removed_securities:\n # Removes the symbol from the self.sector_code_by_symbol dictionary\n # since we cannot emit PortfolioTarget for removed securities\n self.sector_code_by_symbol.pop(security.symbol, None)\n\n for security in changes.added_securities:\n sector_code = self.get_sector_code(security)\n if sector_code:\n self.sector_code_by_symbol[security.symbol] = sector_code\n\n super().on_securities_changed(algorithm, changes)\n\n def get_sector_code(self, security):\n '''Gets the sector code\n Args:\n security: The security to create a sector code for\n Returns:\n The value of the sector code for the security\n Remarks:\n Other sectors can be defined using AssetClassification'''\n fundamentals = security.fundamentals\n company_reference = security.fundamentals.company_reference if fundamentals else None\n return company_reference.industry_template_code if company_reference else None\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN PortfolioConstructionModel that can be described like this\n: Implementation of On-Line Moving Average Reversion (OLMAR)", "output": "```python\n\n\nfrom AlgorithmImports import *\n\nclass MeanReversionPortfolioConstructionModel(PortfolioConstructionModel):\n \n def __init__(self,\n rebalance = Resolution.Daily,\n portfolioBias = PortfolioBias.LongShort,\n reversion_threshold = 1,\n window_size = 20,\n resolution = Resolution.Daily):\n \"\"\"Initialize the model\n Args:\n rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.\n If None will be ignored.\n The function returns the next expected rebalance time for a given algorithm UTC DateTime.\n The function returns null if unknown, in which case the function will be called again in the\n next loop. Returning current time will trigger rebalance.\n portfolioBias: Specifies the bias of the portfolio (Short, Long/Short, Long)\n reversion_threshold: Reversion threshold\n window_size: Window size of mean price calculation\n resolution: The resolution of the history price and rebalancing\n \"\"\"\n super().__init__()\n if portfolioBias == PortfolioBias.Short:\n raise ArgumentException(\"Long position must be allowed in MeanReversionPortfolioConstructionModel.\")\n \n self.reversion_threshold = reversion_threshold\n self.window_size = window_size\n self.resolution = resolution\n\n self.num_of_assets = 0\n # Initialize a dictionary to store stock data\n self.symbol_data = {}\n\n # If the argument is an instance of Resolution or Timedelta\n # Redefine rebalancingFunc\n rebalancingFunc = rebalance\n if isinstance(rebalance, int):\n rebalance = Extensions.ToTimeSpan(rebalance)\n if isinstance(rebalance, timedelta):\n rebalancingFunc = lambda dt: dt + rebalance\n if rebalancingFunc:\n self.SetRebalancingFunc(rebalancingFunc)\n\n def DetermineTargetPercent(self, activeInsights):\n \"\"\"Will determine the target percent for each insight\n Args:\n activeInsights: list of active insights\n Returns:\n dictionary of insight and respective target weight\n \"\"\"\n targets = {}\n\n # If we have no insights or non-ready just return an empty target list\n if len(activeInsights) == 0 or not all([self.symbol_data[x.Symbol].IsReady for x in activeInsights]):\n return targets\n\n num_of_assets = len(activeInsights)\n if self.num_of_assets != num_of_assets:\n self.num_of_assets = num_of_assets\n # Initialize portfolio weightings vector\n self.weight_vector = np.ones(num_of_assets) * (1/num_of_assets)\n \n ### Get price relatives vs expected price (SMA)\n price_relatives = self.GetPriceRelatives(activeInsights) # \\tilde{x}_{t+1}\n\n ### Get step size of next portfolio\n # \\bar{x}_{t+1} = 1^T * \\tilde{x}_{t+1} / m\n # \\lambda_{t+1} = max( 0, ( b_t * \\tilde{x}_{t+1} - \\epsilon ) / ||\\tilde{x}_{t+1} - \\bar{x}_{t+1} * 1|| ^ 2 )\n next_prediction = price_relatives.mean() # \\bar{x}_{t+1}\n assets_mean_dev = price_relatives - next_prediction\n second_norm = (np.linalg.norm(assets_mean_dev)) ** 2\n \n if second_norm == 0.0:\n step_size = 0\n else:\n step_size = (np.dot(self.weight_vector, price_relatives) - self.reversion_threshold) / second_norm\n step_size = max(0, step_size) # \\lambda_{t+1}\n\n ### Get next portfolio weightings\n # b_{t+1} = b_t - step_size * ( \\tilde{x}_{t+1} - \\bar{x}_{t+1} * 1 )\n next_portfolio = self.weight_vector - step_size * assets_mean_dev\n # Normalize\n normalized_portfolio_weight_vector = self.SimplexProjection(next_portfolio)\n # Save normalized result for the next portfolio step\n self.weight_vector = normalized_portfolio_weight_vector\n\n # Update portfolio state\n for i, insight in enumerate(activeInsights):\n targets[insight] = normalized_portfolio_weight_vector[i]\n\n return targets\n \n def GetPriceRelatives(self, activeInsights):\n \"\"\"Get price relatives with reference level of SMA\n Args:\n activeInsights: list of active insights\n Returns:\n array of price relatives vector\n \"\"\" \n # Initialize a price vector of the next prices relatives' projection\n next_price_relatives = np.zeros(len(activeInsights))\n\n ### Get next price relative predictions\n # Using the previous price to simulate assumption of instant reversion\n for i, insight in enumerate(activeInsights):\n symbol_data = self.symbol_data[insight.Symbol]\n next_price_relatives[i] = 1 + insight.Magnitude * insight.Direction \\\n if insight.Magnitude is not None \\\n else symbol_data.Identity.Current.Value / symbol_data.Sma.Current.Value\n \n return next_price_relatives\n\n def OnSecuritiesChanged(self, algorithm, changes):\n \"\"\"Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm\n \"\"\"\n # clean up data for removed securities\n super().OnSecuritiesChanged(algorithm, changes)\n for removed in changes.RemovedSecurities:\n symbol_data = self.symbol_data.pop(removed.Symbol, None)\n symbol_data.Reset()\n\n # initialize data for added securities\n symbols = [ x.Symbol for x in changes.AddedSecurities ]\n\n for symbol in symbols:\n if symbol not in self.symbol_data:\n self.symbol_data[symbol] = self.MeanReversionSymbolData(algorithm, symbol, self.window_size, self.resolution)\n\n def SimplexProjection(self, vector, total=1):\n \"\"\"Normalize the updated portfolio into weight vector:\n v_{t+1} = arg min || v - v_{t+1} || ^ 2\n Implementation from:\n Duchi, J., Shalev-Shwartz, S., Singer, Y., & Chandra, T. (2008, July). \n Efficient projections onto the l 1-ball for learning in high dimensions.\n In Proceedings of the 25th international conference on Machine learning \n (pp. 272-279).\n Args:\n vector: unnormalized weight vector\n total: total weight of output, default to be 1, making it a probabilistic simplex\n \"\"\"\n if total <= 0:\n raise ArgumentException(\"Total must be > 0 for Euclidean Projection onto the Simplex.\")\n \n vector = np.asarray(vector)\n\n # Sort v into u in descending order\n mu = np.sort(vector)[::-1]\n sv = np.cumsum(mu)\n\n rho = np.where(mu > (sv - total) / np.arange(1, len(vector) + 1))[0][-1]\n theta = (sv[rho] - total) / (rho + 1)\n w = (vector - theta)\n w[w < 0] = 0\n return w\n\n class MeanReversionSymbolData:\n def __init__(self, algo, symbol, window_size, resolution):\n # Indicator of price\n self.Identity = algo.Identity(symbol, resolution)\n # Moving average indicator for mean reversion level\n self.Sma = algo.SMA(symbol, window_size, resolution)\n \n # Warmup indicator\n algo.WarmUpIndicator(symbol, self.Identity, resolution)\n algo.WarmUpIndicator(symbol, self.Sma, resolution)\n\n def Reset(self):\n self.Identity.Reset()\n self.Sma.Reset()\n \n @property\n def IsReady(self):\n return self.Identity.IsReady and self.Sma.IsReady\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN PortfolioConstructionModel that can be described like this\n: Risk Parity Portfolio Construction Model", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom Portfolio.RiskParityPortfolioOptimizer import RiskParityPortfolioOptimizer\n\nclass RiskParityPortfolioConstructionModel(PortfolioConstructionModel):\n def __init__(self,\n rebalance = Resolution.DAILY,\n portfolio_bias = PortfolioBias.LONG_SHORT,\n lookback = 1,\n period = 252,\n resolution = Resolution.DAILY,\n optimizer = None):\n \"\"\"Initialize the model\n Args:\n rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.\n If None will be ignored.\n The function returns the next expected rebalance time for a given algorithm UTC DateTime.\n The function returns null if unknown, in which case the function will be called again in the\n next loop. Returning current time will trigger rebalance.\n portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)\n lookback(int): Historical return lookback period\n period(int): The time interval of history price to calculate the weight\n resolution: The resolution of the history price\n optimizer(class): Method used to compute the portfolio weights\"\"\"\n super().__init__()\n if portfolio_bias == PortfolioBias.SHORT:\n raise ArgumentException(\"Long position must be allowed in RiskParityPortfolioConstructionModel.\")\n\n self.lookback = lookback\n self.period = period\n self.resolution = resolution\n self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)\n\n self.optimizer = RiskParityPortfolioOptimizer() if optimizer is None else optimizer\n\n self._symbol_data_by_symbol = {}\n\n # If the argument is an instance of Resolution or Timedelta\n # Redefine rebalancing_func\n rebalancing_func = rebalance\n if isinstance(rebalance, int):\n rebalance = Extensions.to_time_span(rebalance)\n if isinstance(rebalance, timedelta):\n rebalancing_func = lambda dt: dt + rebalance\n if rebalancing_func:\n self.set_rebalancing_func(rebalancing_func)\n\n def determine_target_percent(self, active_insights):\n \"\"\"Will determine the target percent for each insight\n Args:\n active_insights: list of active insights\n Returns:\n dictionary of insight and respective target weight\n \"\"\"\n targets = {}\n\n # If we have no insights just return an empty target list\n if len(active_insights) == 0:\n return targets\n\n symbols = [insight.symbol for insight in active_insights]\n\n # Create a dictionary keyed by the symbols in the insights with an pandas.series as value to create a data frame\n returns = { str(symbol) : data.return_ for symbol, data in self._symbol_data_by_symbol.items() if symbol in symbols }\n returns = pd.DataFrame(returns)\n\n # The portfolio optimizer finds the optional weights for the given data\n weights = self.optimizer.optimize(returns)\n weights = pd.Series(weights, index = returns.columns)\n\n # Create portfolio targets from the specified insights\n for insight in active_insights:\n targets[insight] = weights[str(insight.symbol)]\n\n return targets\n\n def on_securities_changed(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n\n # clean up data for removed securities\n super().on_securities_changed(algorithm, changes)\n for removed in changes.removed_securities:\n symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)\n symbol_data.reset()\n algorithm.unregister_indicator(symbol_data.roc)\n\n # initialize data for added securities\n symbols = [ x.symbol for x in changes.added_securities ]\n history = algorithm.history(symbols, self.lookback * self.period, self.resolution)\n if history.empty: return\n\n tickers = history.index.levels[0]\n for ticker in tickers:\n symbol = SymbolCache.get_symbol(ticker)\n\n if symbol not in self._symbol_data_by_symbol:\n symbol_data = self.RiskParitySymbolData(symbol, self.lookback, self.period)\n symbol_data.warm_up_indicators(history.loc[ticker])\n self._symbol_data_by_symbol[symbol] = symbol_data\n algorithm.register_indicator(symbol, symbol_data.roc, self.resolution)\n\n class RiskParitySymbolData:\n '''Contains data specific to a symbol required by this model'''\n def __init__(self, symbol, lookback, period):\n self._symbol = symbol\n self.roc = RateOfChange(f'{symbol}.roc({lookback})', lookback)\n self.roc.updated += self.on_rate_of_change_updated\n self.window = RollingWindow(period)\n\n def reset(self):\n self.roc.updated -= self.on_rate_of_change_updated\n self.roc.reset()\n self.window.reset()\n\n def warm_up_indicators(self, history):\n for tuple in history.itertuples():\n self.roc.update(tuple.Index, tuple.close)\n\n def on_rate_of_change_updated(self, roc, value):\n if roc.is_ready:\n self.window.add(value)\n\n def add(self, time, value):\n item = IndicatorDataPoint(self._symbol, time, value)\n self.window.add(item)\n\n @property\n def return_(self):\n return pd.Series(\n data = [x.value for x in self.window],\n index = [x.end_time for x in self.window])\n\n @property\n def is_ready(self):\n return self.window.is_ready\n\n def __str__(self, **kwargs):\n return '{}: {:.2%}'.format(self.roc.name, self.window[0])\n```"} +{"instruction": "You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.", "input": "Generate a LEAN PortfolioConstructionModel that can be described like this\n: Provides an implementation of IPortfolioConstructionModel that generates percent targets based on the", "output": "```python\n\n\nfrom AlgorithmImports import *\nfrom InsightWeightingPortfolioConstructionModel import InsightWeightingPortfolioConstructionModel\n\nclass ConfidenceWeightedPortfolioConstructionModel(InsightWeightingPortfolioConstructionModel):\n '''Provides an implementation of IPortfolioConstructionModel that generates percent targets based on the\n Insight.CONFIDENCE. The target percent holdings of each Symbol is given by the Insight.CONFIDENCE from the last\n active Insight for that symbol.\n For insights of direction InsightDirection.UP, long targets are returned and for insights of direction\n InsightDirection.DOWN, short targets are returned.\n If the sum of all the last active Insight per symbol is bigger than 1, it will factor down each target\n percent holdings proportionally so the sum is 1.\n It will ignore Insight that have no Insight.CONFIDENCE value.'''\n\n def __init__(self, rebalance = Resolution.DAILY, portfolio_bias = PortfolioBias.LONG_SHORT):\n '''Initialize a new instance of ConfidenceWeightedPortfolioConstructionModel\n Args:\n rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.\n If None will be ignored.\n The function returns the next expected rebalance time for a given algorithm UTC DateTime.\n The function returns null if unknown, in which case the function will be called again in the\n next loop. Returning current time will trigger rebalance.\n portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)'''\n super().__init__(rebalance, portfolio_bias)\n\n def should_create_target_for_insight(self, insight):\n '''Method that will determine if the portfolio construction model should create a\n target for this insight\n Args:\n insight: The insight to create a target for'''\n # Ignore insights that don't have Confidence value\n return insight.confidence is not None\n\n def get_value(self, insight):\n '''Method that will determine which member will be used to compute the weights and gets its value\n Args:\n insight: The insight to create a target for\n Returns:\n The value of the selected insight member'''\n return insight.confidence\n```"}