Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Algorithm illustrating how to manually set market hours and symbol properties database entries to be picked up by the algorithm's securities.
This specific case illustrates how to do it for CFDs to match InteractiveBrokers brokerage, which has different market hours
depending on the CFD underlying asset.

Output:
```python

from AlgorithmImports import *

import Newtonsoft.Json as json

class ManuallySetMarketHoursAndSymbolPropertiesDatabaseEntriesAlgorithm(QCAlgorithm):
    '''
    Algorithm illustrating how to manually set market hours and symbol properties database entries to be picked up by the algorithm's securities.
    This specific case illustrates how to do it for CFDs to match InteractiveBrokers brokerage, which has different market hours
    depending on the CFD underlying asset.
    '''

    def initialize(self):
        self.set_start_date(2013,10, 7)
        self.set_end_date(2013,10,11)
        self.set_cash(100000)

        self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE)

        # Some brokerages like InteractiveBrokers make a difference on CFDs depending on the underlying (equity, index, metal, forex).
        # Depending on this, the market hours can be different. In order to be more specific with the market hours,
        # we can set the MarketHoursDatabase entry for the CFDs.

        # Equity CFDs are usually traded the same hours as the equity market.
        equity_market_hours_entry = self.market_hours_database.get_entry(Market.USA, Symbol.EMPTY, SecurityType.EQUITY)
        self.market_hours_database.set_entry(Market.INTERACTIVE_BROKERS, "", SecurityType.CFD, equity_market_hours_entry.exchange_hours, equity_market_hours_entry.data_time_zone)

        # The same can be done for the symbol properties, in case they are different depending on the underlying
        equity_symbol_properties = self.symbol_properties_database.get_symbol_properties(Market.USA, Symbol.EMPTY, SecurityType.EQUITY, Currencies.USD)
        self.symbol_properties_database.set_entry(Market.INTERACTIVE_BROKERS, "", SecurityType.CFD, equity_symbol_properties)

        spy_cfd = self.add_cfd("SPY", market=Market.INTERACTIVE_BROKERS)

        if json.JsonConvert.serialize_object(spy_cfd.exchange.hours) != json.JsonConvert.serialize_object(equity_market_hours_entry.exchange_hours):
            raise AssertionError("Expected the SPY CFD market hours to be the same as the underlying equity market hours.")

        if json.JsonConvert.serialize_object(spy_cfd.symbol_properties) != json.JsonConvert.serialize_object(equity_symbol_properties):
            raise AssertionError("Expected the SPY CFD symbol properties to be the same as the underlying equity symbol properties.")

        # We can also do it for a specific ticker
        aud_usd_forex_market_hours_entry = self.market_hours_database.get_entry(Market.OANDA, Symbol.EMPTY, SecurityType.FOREX)
        self.market_hours_database.set_entry(Market.INTERACTIVE_BROKERS, "AUDUSD", SecurityType.CFD, aud_usd_forex_market_hours_entry.exchange_hours, aud_usd_forex_market_hours_entry.data_time_zone)

        aud_usd_forex_symbol_properties = self.symbol_properties_database.get_symbol_properties(Market.OANDA, "AUDUSD", SecurityType.FOREX, Currencies.USD)
        self.symbol_properties_database.set_entry(Market.INTERACTIVE_BROKERS, "AUDUSD", SecurityType.CFD, aud_usd_forex_symbol_properties)

        aud_usd_cfd = self.add_cfd("AUDUSD", market=Market.INTERACTIVE_BROKERS)

        if json.JsonConvert.serialize_object(aud_usd_cfd.exchange.hours) != json.JsonConvert.serialize_object(aud_usd_forex_market_hours_entry.exchange_hours):
            raise AssertionError("Expected the AUDUSD CFD market hours to be the same as the underlying forex market hours.")

        if json.JsonConvert.serialize_object(aud_usd_cfd.symbol_properties) != json.JsonConvert.serialize_object(aud_usd_forex_symbol_properties):
            raise AssertionError("Expected the AUDUSD CFD symbol properties to be the same as the underlying forex symbol properties.")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This algorithm is a regression test for issue #2018 and PR #2038.

Output:
```python

from AlgorithmImports import *

class OptionDataNullReferenceRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2016, 12, 1)
        self.set_end_date(2017, 1, 1)
        self.set_cash(500000)

        self.add_equity("DUST")

        option = self.add_option("DUST")

        option.set_filter(self.universe_func)

    def universe_func(self, universe):
        return universe.include_weeklys().strikes(-1, +1).expiration(timedelta(25), timedelta(100))
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This algorithm demonstrates using the history provider to retrieve data
to warm up indicators before data is received.

Output:
```python

from AlgorithmImports import *

class WarmupHistoryAlgorithm(QCAlgorithm):

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2014,5,2)   #Set Start Date
        self.set_end_date(2014,5,2)     #Set End Date
        self.set_cash(100000)          #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        forex = self.add_forex("EURUSD", Resolution.SECOND)
        forex = self.add_forex("NZDUSD", Resolution.SECOND)

        fast_period = 60
        slow_period = 3600
        self.fast = self.ema("EURUSD", fast_period)
        self.slow = self.ema("EURUSD", slow_period)

        # "slow_period + 1" because rolling window waits for one to fall off the back to be considered ready
        # History method returns a dict with a pandas.data_frame
        history = self.history(["EURUSD", "NZDUSD"], slow_period + 1)

        # prints out the tail of the dataframe
        self.log(str(history.loc["EURUSD"].tail()))
        self.log(str(history.loc["NZDUSD"].tail()))

        for index, row in history.loc["EURUSD"].iterrows():
            self.fast.update(index, row["close"])
            self.slow.update(index, row["close"])

        self.log("FAST {0} READY. Samples: {1}".format("IS" if self.fast.is_ready else "IS NOT", self.fast.samples))
        self.log("SLOW {0} READY. Samples: {1}".format("IS" if self.slow.is_ready else "IS NOT", self.slow.samples))

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''

        if self.fast.current.value > self.slow.current.value:
            self.set_holdings("EURUSD", 1)
        else:
            self.set_holdings("EURUSD", -1)
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: The demonstration algorithm shows some of the most common order methods when working with FutureOption assets.

Output:
```python

from AlgorithmImports import *

class BasicTemplateFutureOptionAlgorithm(QCAlgorithm):

    def initialize(self):
        '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
        self.set_start_date(2022, 1, 1)
        self.set_end_date(2022, 2, 1)
        self.set_cash(100000)

        gold_futures = self.add_future(Futures.Metals.GOLD, Resolution.MINUTE)
        gold_futures.set_filter(0, 180)
        self._symbol = gold_futures.symbol
        self.add_future_option(self._symbol, lambda universe: universe.strikes(-5, +5)
                                                                    .calls_only()
                                                                    .back_month()
                                                                    .only_apply_filter_at_market_open())

        # Historical Data
        history = self.history(self._symbol, 60, Resolution.DAILY)
        self.log(f"Received {len(history)} bars from {self._symbol} FutureOption historical data call.")

    def on_data(self, data):
        '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        Arguments:
            slice: Slice object keyed by symbol containing the stock data
        '''
        # Access Data
        for kvp in data.option_chains:
            underlying_future_contract = kvp.key.underlying
            chain = kvp.value

            if not chain: continue

            for contract in chain:
                self.log(f"""Canonical Symbol: {kvp.key};
                    Contract: {contract};
                    Right: {contract.right};
                    Expiry: {contract.expiry};
                    Bid price: {contract.bid_price};
                    Ask price: {contract.ask_price};
                    Implied Volatility: {contract.implied_volatility}""")

            if not self.portfolio.invested:
                atm_strike = sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike))[0].strike
                selected_contract = sorted([contract for contract in chain if contract.strike == atm_strike], \
                           key = lambda x: x.expiry, reverse=True)[0]
                self.market_order(selected_contract.symbol, 1)

    def on_order_event(self, order_event):
        self.debug("{} {}".format(self.time, order_event.to_string()))
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This example demonstrates how to execute a Call Butterfly option equity strategy
It adds options for a given underlying equity security, and shows how you can prefilter contracts easily based on strikes and expirations

Output:
```python

from AlgorithmImports import *

class BasicTemplateOptionEquityStrategyAlgorithm(QCAlgorithm):
    underlying_ticker = "GOOG"

    def initialize(self) -> None:
        self.set_start_date(2015, 12, 24)
        self.set_end_date(2015, 12, 24)

        equity = self.add_equity(self.underlying_ticker)
        option = self.add_option(self.underlying_ticker)
        self._option_symbol = option.symbol

        # set our strike/expiry filter for this option chain
        option.set_filter(lambda u: (u.strikes(-2, +2)
                                     # Expiration method accepts TimeSpan objects or integer for days.
                                     # The following statements yield the same filtering criteria
                                     .expiration(0, 180)))

    def on_data(self, slice: Slice) -> None:
        if self.portfolio.invested or not self.is_market_open(self._option_symbol):
            return

        chain = slice.option_chains.get(self._option_symbol)
        if not chain:
            return

        grouped_by_expiry = dict()
        for contract in [contract for contract in chain if contract.right == OptionRight.CALL]:
            grouped_by_expiry.setdefault(int(contract.expiry.timestamp()), []).append(contract)

        first_expiry = list(sorted(grouped_by_expiry))[0]
        call_contracts = sorted(grouped_by_expiry[first_expiry], key = lambda x: x.strike)

        expiry = call_contracts[0].expiry
        lower_strike = call_contracts[0].strike
        middle_strike = call_contracts[1].strike
        higher_strike = call_contracts[2].strike

        option_strategy = OptionStrategies.call_butterfly(self._option_symbol, higher_strike, middle_strike, lower_strike, expiry)

        self.order(option_strategy, 10)

    def on_order_event(self, order_event: OrderEvent) -> None:
        self.log(str(order_event))
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Example of custom fill model for security to only fill bars of data obtained after the order was placed. This is to encourage more
pessimistic fill models and eliminate the possibility to fill on old market data that may not be relevant.

Output:
```python

from AlgorithmImports import *

class ForwardDataOnlyFillModelAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013,10,1)
        self.set_end_date(2013,10,31)

        self.security = self.add_equity("SPY", Resolution.HOUR)
        self.security.set_fill_model(ForwardDataOnlyFillModel())

        self.schedule.on(self.date_rules.week_start(), self.time_rules.after_market_open(self.security.symbol), self.trade)

    def trade(self):
        if not self.portfolio.invested:
            if self.time.hour != 9 or self.time.minute != 30:
                raise AssertionError(f"Unexpected event time {self.time}")

            ticket = self.buy("SPY", 1)
            if ticket.status != OrderStatus.SUBMITTED:
                raise AssertionError(f"Unexpected order status {ticket.status}")

    def on_order_event(self, order_event: OrderEvent):
        self.debug(f"OnOrderEvent:: {order_event}")
        if order_event.status == OrderStatus.FILLED and (self.time.hour != 10 or self.time.minute != 0):
            raise AssertionError(f"Unexpected fill time {self.time}")

class ForwardDataOnlyFillModel(EquityFillModel):
    def fill(self, parameters: FillModelParameters):
        order_local_time = Extensions.convert_from_utc(parameters.order.time, parameters.security.exchange.time_zone)
        for data_type in [ QuoteBar, TradeBar, Tick ]:
            data = parameters.security.cache.get_data(data_type)
            if not data is None and order_local_time <= data.end_time:
                return super().fill(parameters)
        return Fill([])
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration on how to access order tickets right after placing an order.

Output:
```python

from datetime import timedelta
from AlgorithmImports import *

class OrderTicketAssignmentDemoAlgorithm(QCAlgorithm):
    '''Demonstration on how to access order tickets right after placing an order.'''
    def initialize(self):
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)
        self.set_cash(100000)

        self._symbol = self.add_equity("SPY").symbol

        self.trade_count = 0
        self.consolidate(self._symbol, timedelta(hours=1), self.hour_consolidator)

    def hour_consolidator(self, bar: TradeBar):
        # Reset self.ticket to None on each new bar
        self.ticket = None
        self.ticket = self.market_order(self._symbol, 1, asynchronous=True)
        self.debug(f"{self.time}: Buy: Price {bar.price}, order_id: {self.ticket.order_id}")
        self.trade_count += 1

    def on_order_event(self, order_event: OrderEvent):
        # We cannot access self.ticket directly because it is assigned asynchronously:
        # this order event could be triggered before self.ticket is assigned.
        ticket = order_event.ticket
        if ticket is None:
            raise AssertionError("Expected order ticket in order event to not be null")
        if order_event.status == OrderStatus.SUBMITTED and self.ticket is not None:
            raise AssertionError("Field self.ticket not expected no be assigned on the first order event")

        self.debug(ticket.to_string())

    def on_end_of_algorithm(self):
        # Just checking that orders were placed
        if not self.portfolio.invested or self.trade_count != self.transactions.orders_count:
            raise AssertionError(f"Expected the portfolio to have holdings and to have {self.trade_count} trades, but had {self.transactions.orders_count}")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration of using custom fee, slippage, fill, and buying power models for modeling transactions in backtesting.
QuantConnect allows you to model all orders as deeply and accurately as you need.
This example illustrates how Lean exports its API to Python conforming to PEP8 style guide.

Output:
```python

from AlgorithmImports import *
import random

class CustomModelsPEP8Algorithm(QCAlgorithm):
    '''Demonstration of using custom fee, slippage, fill, and buying power models for modeling transactions in backtesting.
    QuantConnect allows you to model all orders as deeply and accurately as you need.'''

    def initialize(self):
        self.set_start_date(2013,10,1)   # Set Start Date
        self.set_end_date(2013,10,31)    # Set End Date
        self.security = self.add_equity("SPY", Resolution.HOUR)
        self.spy = self.security.symbol

        # set our models
        self.security.set_fee_model(CustomFeeModelPEP8(self))
        self.security.set_fill_model(CustomFillModelPEP8(self))
        self.security.set_slippage_model(CustomSlippageModelPEP8(self))
        self.security.set_buying_power_model(CustomBuyingPowerModelPEP8(self))

    def on_data(self, data):
        open_orders = self.transactions.get_open_orders(self.spy)
        if len(open_orders) != 0: return
        if self.time.day > 10 and self.security.holdings.quantity <= 0:
            quantity = self.calculate_order_quantity(self.spy, .5)
            self.log(f"MarketOrder: {quantity}")
            self.market_order(self.spy, quantity, True)   # async needed for partial fill market orders
        elif self.time.day > 20 and self.security.holdings.quantity >= 0:
            quantity = self.calculate_order_quantity(self.spy, -.5)
            self.log(f"MarketOrder: {quantity}")
            self.market_order(self.spy, quantity, True)   # async needed for partial fill market orders

class CustomFillModelPEP8(ImmediateFillModel):
    def __init__(self, algorithm):
        super().__init__()
        self.algorithm = algorithm
        self.absolute_remaining_by_order_id = {}
        self.random = Random(387510346)

    def market_fill(self, asset, order):
        absolute_remaining = order.absolute_quantity

        if order.id in self.absolute_remaining_by_order_id.keys():
            absolute_remaining = self.absolute_remaining_by_order_id[order.id]

        fill = super().market_fill(asset, order)
        absolute_fill_quantity = int(min(absolute_remaining, self.random.next(0, 2*int(order.absolute_quantity))))
        fill.fill_quantity = np.sign(order.quantity) * absolute_fill_quantity

        if absolute_remaining == absolute_fill_quantity:
            fill.status = OrderStatus.FILLED
            if self.absolute_remaining_by_order_id.get(order.id):
                self.absolute_remaining_by_order_id.pop(order.id)
        else:
            absolute_remaining = absolute_remaining - absolute_fill_quantity
            self.absolute_remaining_by_order_id[order.id] = absolute_remaining
            fill.status = OrderStatus.PARTIALLY_FILLED
        self.algorithm.log(f"CustomFillModel: {fill}")
        return fill

class CustomFeeModelPEP8(FeeModel):
    def __init__(self, algorithm):
        super().__init__()
        self.algorithm = algorithm

    def get_order_fee(self, parameters):
        # custom fee math
        fee = max(1, parameters.security.price
                  * parameters.order.absolute_quantity
                  * 0.00001)
        self.algorithm.log(f"CustomFeeModel: {fee}")
        return OrderFee(CashAmount(fee, "USD"))

class CustomSlippageModelPEP8:
    def __init__(self, algorithm):
        self.algorithm = algorithm

    def get_slippage_approximation(self, asset, order):
        # custom slippage math
        slippage = asset.price * 0.0001 * np.log10(2*float(order.absolute_quantity))
        self.algorithm.log(f"CustomSlippageModel: {slippage}")
        return slippage

class CustomBuyingPowerModelPEP8(BuyingPowerModel):
    def __init__(self, algorithm):
        super().__init__()
        self.algorithm = algorithm

    def has_sufficient_buying_power_for_order(self, parameters):
        # custom behavior: this model will assume that there is always enough buying power
        has_sufficient_buying_power_for_order_result = HasSufficientBuyingPowerForOrderResult(True)
        self.algorithm.log(f"CustomBuyingPowerModel: {has_sufficient_buying_power_for_order_result.is_sufficient}")
        return has_sufficient_buying_power_for_order_result

class SimpleCustomFillModelPEP8(FillModel):
    def __init__(self):
        super().__init__()

    def _create_order_event(self, asset, order):
        utc_time = Extensions.convert_to_utc(asset.local_time, asset.exchange.time_zone)
        return OrderEvent(order, utc_time, OrderFee.ZERO)

    def _set_order_event_to_filled(self, fill, fill_price, fill_quantity):
        fill.status = OrderStatus.FILLED
        fill.fill_quantity = fill_quantity
        fill.fill_price = fill_price
        return fill

    def _get_trade_bar(self, asset, order_direction):
        trade_bar = asset.cache.get_data(TradeBar)
        if trade_bar:
            return trade_bar

        price = asset.price
        return TradeBar(asset.local_time, asset.symbol, price, price, price, price, 0)

    def market_fill(self, asset, order):
        fill = self._create_order_event(asset, order)
        if order.status == OrderStatus.CANCELED:
            return fill

        fill_price = asset.cache.ask_price if order.direction == OrderDirection.BUY else asset.cache.bid_price
        return self._set_order_event_to_filled(fill, fill_price, order.quantity)

    def stop_market_fill(self, asset, order):
        fill = self._create_order_event(asset, order)
        if order.status == OrderStatus.CANCELED:
            return fill

        stop_price = order.stop_price
        trade_bar = self._get_trade_bar(asset, order.direction)

        if order.direction == OrderDirection.SELL and trade_bar.low < stop_price:
            return self._set_order_event_to_filled(fill, stop_price, order.quantity)

        if order.direction == OrderDirection.BUY and trade_bar.high > stop_price:
            return self._set_order_event_to_filled(fill, stop_price, order.quantity)

        return fill

    def limit_fill(self, asset, order):
        fill = self._create_order_event(asset, order)
        if order.status == OrderStatus.CANCELED:
            return fill

        limit_price = order.limit_price
        trade_bar = self._get_trade_bar(asset, order.direction)

        if order.direction == OrderDirection.SELL and trade_bar.high > limit_price:
            return self._set_order_event_to_filled(fill, limit_price, order.quantity)

        if order.direction == OrderDirection.BUY and trade_bar.low < limit_price:
            return self._set_order_event_to_filled(fill, limit_price, order.quantity)

        return fill
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration of how to define a universe as a combination of use the coarse fundamental data and fine fundamental data

Output:
```python

from AlgorithmImports import *

class CoarseFineFundamentalRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2014,3,24)   #Set Start Date
        self.set_end_date(2014,4,7)      #Set End Date
        self.set_cash(50000)            #Set Strategy Cash

        self.universe_settings.resolution = Resolution.DAILY

        # this add universe method accepts two parameters:
        # - coarse selection function: accepts an List[CoarseFundamental] and returns an List[Symbol]
        # - fine selection function: accepts an List[FineFundamental] and returns an List[Symbol]
        self.add_universe(self.coarse_selection_function, self.fine_selection_function)

        self.changes = None
        self.number_of_symbols_fine = 2

    # return a list of three fixed symbol objects
    def coarse_selection_function(self, coarse):
        tickers = [ "GOOG", "BAC", "SPY" ]

        if self.time.date() < date(2014, 4, 1):
            tickers = [ "AAPL", "AIG", "IBM" ]

        return [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers ]

    # sort the data by market capitalization and take the top 'number_of_symbols_fine'
    def fine_selection_function(self, fine):
        # sort descending by market capitalization
        sorted_by_market_cap = sorted(fine, key=lambda x: x.market_cap, reverse=True)

        # take the top entries from our sorted collection
        return [ x.symbol for x in sorted_by_market_cap[:self.number_of_symbols_fine] ]

    def on_data(self, data):
        # if we have no changes, do nothing
        if self.changes is None: return

        # liquidate removed securities
        for security in self.changes.removed_securities:
            if security.invested:
                self.liquidate(security.symbol)
                self.debug("Liquidated Stock: " + str(security.symbol.value))

        # we want 50% allocation in each security in our universe
        for security in self.changes.added_securities:
            if (security.fundamentals.earning_ratios.equity_per_share_growth.one_year > 0.25):
                self.set_holdings(security.symbol, 0.5)
                self.debug("Purchased Stock: " + str(security.symbol.value))

        self.changes = None

    # this event fires whenever we have changes to our universe
    def on_securities_changed(self, changes):
        self.changes = changes
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This algorithm tests the functionality of the CompositeIndicator
using either a lambda expression or a method reference.

Output:
```python

from AlgorithmImports import *

class CompositeIndicatorWorksAsExpectedRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013, 10, 4)
        self.set_end_date(2013, 10, 5)
        self.add_equity("SPY", Resolution.MINUTE)
        close  = self.identity("SPY", Resolution.MINUTE, Field.CLOSE)
        low = self.min("SPY", 420, Resolution.MINUTE, Field.LOW)
        self.composite_min_direct = CompositeIndicator("CompositeMinDirect", close, low, lambda l, r: IndicatorResult(min(l.current.value, r.current.value)))
        self.composite_min_method = CompositeIndicator("CompositeMinMethod", close, low, self.composer)

        self.data_received = False

    def composer(self, l, r):
        return IndicatorResult(min(l.current.value, r.current.value))

    def on_data(self, data):
        self.data_received = True
        if self.composite_min_direct.current.value != self.composite_min_method.current.value:
            raise AssertionError(f"Values of indicators differ: {self.composite_min_direct.current.value} | {self.composite_min_method.current.value}")

    def on_end_of_algorithm(self):
        if not self.data_received:
            raise AssertionError("No data was processed during the algorithm execution.")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Example algorithm giving an introduction into using IDataConsolidators.
This is an advanced QC concept and requires a certain level of comfort using C# and its event system.

What is an IDataConsolidator?
IDataConsolidator is a plugin point that can be used to transform your data more easily.
In this example we show one of the simplest consolidators, the TradeBarConsolidator.
This type is capable of taking a timespan to indicate how long each bar should be, or an
integer to indicate how many bars should be aggregated into one.

When a new 'consolidated' piece of data is produced by the IDataConsolidator, an event is fired
with the argument of the new data.

Output:
```python

from AlgorithmImports import *

class DataConsolidationAlgorithm(QCAlgorithm):

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2013, 10, 7)  #Set Start Date
        self.set_end_date(2013, 12, 7)  #Set End Date
        # Find more symbols here: http://quantconnect.com/data
        self.add_equity("SPY")
        self.add_forex("EURUSD", Resolution.HOUR)

        # define our 30 minute trade bar consolidator. we can
        # access the 30 minute bar from the DataConsolidated events
        thirty_minute_consolidator = TradeBarConsolidator(timedelta(minutes=30))

        # attach our event handler. the event handler is a function that will
        # be called each time we produce a new consolidated piece of data.
        thirty_minute_consolidator.data_consolidated += self.thirty_minute_bar_handler

        # this call adds our 30 minute consolidator to
        # the manager to receive updates from the engine
        self.subscription_manager.add_consolidator("SPY", thirty_minute_consolidator)

        # here we'll define a slightly more complex consolidator. what we're trying to produce is
        # a 3 day bar. Now we could just use a single TradeBarConsolidator like above and pass in
        # TimeSpan.from_days(3), but in reality that's not what we want. For time spans of longer than
        # a day we'll get incorrect results around weekends and such. What we really want are tradeable
        # days. So we'll create a daily consolidator, and then wrap it with a 3 count consolidator.

        # first define a one day trade bar -- this produces a consolidated piece of data after a day has passed
        one_day_consolidator = TradeBarConsolidator(timedelta(1))

        # next define our 3 count trade bar -- this produces a consolidated piece of data after it sees 3 pieces of data
        three_count_consolidator = TradeBarConsolidator(3)

        # here we combine them to make a new, 3 day trade bar. The SequentialConsolidator allows composition of
        # consolidators. It takes the consolidated output of one consolidator (in this case, the one_day_consolidator)
        # and pipes it through to the three_count_consolidator.  His output will be a 3 day bar.
        three_one_day_bar = SequentialConsolidator(one_day_consolidator, three_count_consolidator)

        # attach our handler
        three_one_day_bar.data_consolidated += self.three_day_bar_consolidated_handler

        # this call adds our 3 day to the manager to receive updates from the engine
        self.subscription_manager.add_consolidator("SPY", three_one_day_bar)

        # Custom monthly consolidator
        custom_monthly_consolidator = TradeBarConsolidator(self.custom_monthly)
        custom_monthly_consolidator.data_consolidated += self.custom_monthly_handler
        self.subscription_manager.add_consolidator("SPY", custom_monthly_consolidator)

        # API convenience method for easily receiving consolidated data
        self.consolidate("SPY", timedelta(minutes=45), self.forty_five_minute_bar_handler)
        self.consolidate("SPY", Resolution.HOUR, self.hour_bar_handler)
        self.consolidate("EURUSD", Resolution.DAILY, self.daily_eur_usd_bar_handler)

        # API convenience method for easily receiving weekly-consolidated data
        self.consolidate("SPY", Calendar.WEEKLY, self.calendar_trade_bar_handler)
        self.consolidate("EURUSD", Calendar.WEEKLY, self.calendar_quote_bar_handler)

        # API convenience method for easily receiving monthly-consolidated data
        self.consolidate("SPY", Calendar.MONTHLY, self.calendar_trade_bar_handler)
        self.consolidate("EURUSD", Calendar.MONTHLY, self.calendar_quote_bar_handler)

        # API convenience method for easily receiving quarterly-consolidated data
        self.consolidate("SPY", Calendar.QUARTERLY, self.calendar_trade_bar_handler)
        self.consolidate("EURUSD", Calendar.QUARTERLY, self.calendar_quote_bar_handler)

        # API convenience method for easily receiving yearly-consolidated data
        self.consolidate("SPY", Calendar.YEARLY, self.calendar_trade_bar_handler)
        self.consolidate("EURUSD", Calendar.YEARLY, self.calendar_quote_bar_handler)

        # some securities may have trade and quote data available, so we can choose it based on TickType:
        #self.consolidate("BTCUSD", Resolution.HOUR, TickType.TRADE, self.hour_bar_handler)   # to get TradeBar
        #self.consolidate("BTCUSD", Resolution.HOUR, TickType.QUOTE, self.hour_bar_handler)   # to get QuoteBar (default)

        self.consolidated_hour = False
        self.consolidated45_minute = False
        self.__last = None

    def on_data(self, data):
        '''We need to declare this method'''
        pass

    def on_end_of_day(self, symbol):
        # close up shop each day and reset our 'last' value so we start tomorrow fresh
        self.liquidate("SPY")
        self.__last = None

    def thirty_minute_bar_handler(self, sender, consolidated):
        '''This is our event handler for our 30 minute trade bar defined above in Initialize(). So each time the
        consolidator produces a new 30 minute bar, this function will be called automatically. The 'sender' parameter
         will be the instance of the IDataConsolidator that invoked the event, but you'll almost never need that!'''

        if self.__last is not None and consolidated.close > self.__last.close:
            self.log(f"{consolidated.time} >> SPY >> LONG  >> 100 >> {self.portfolio['SPY'].quantity}")
            self.order("SPY", 100)

        elif self.__last is not None and consolidated.close < self.__last.close:
            self.log(f"{consolidated.time} >> SPY >> SHORT  >> 100 >> {self.portfolio['SPY'].quantity}")
            self.order("SPY", -100)

        self.__last = consolidated

    def three_day_bar_consolidated_handler(self, sender, consolidated):
        ''' This is our event handler for our 3 day trade bar defined above in Initialize(). So each time the
        consolidator produces a new 3 day bar, this function will be called automatically. The 'sender' parameter
        will be the instance of the IDataConsolidator that invoked the event, but you'll almost never need that!'''
        self.log(f"{consolidated.time} >> Plotting!")
        self.plot(consolidated.symbol.value, "3HourBar", consolidated.close)

    def forty_five_minute_bar_handler(self, consolidated):
        ''' This is our event handler for our 45 minute consolidated defined using the Consolidate method'''
        self.consolidated45_minute = True
        self.log(f"{consolidated.end_time} >> FortyFiveMinuteBarHandler >> {consolidated.close}")

    def hour_bar_handler(self, consolidated):
        '''This is our event handler for our one hour consolidated defined using the Consolidate method'''
        self.consolidated_hour = True
        self.log(f"{consolidated.end_time} >> FortyFiveMinuteBarHandler >> {consolidated.close}")

    def daily_eur_usd_bar_handler(self, consolidated):
        '''This is our event handler for our daily consolidated defined using the Consolidate method'''
        self.log(f"{consolidated.end_time} EURUSD Daily consolidated.")

    def calendar_trade_bar_handler(self, trade_bar):
        self.log(f'{self.time} :: {trade_bar.time} {trade_bar.close}')

    def calendar_quote_bar_handler(self, quote_bar):
        self.log(f'{self.time} :: {quote_bar.time} {quote_bar.close}')

    def custom_monthly(self, dt):
        '''Custom Monthly Func'''
        start = dt.replace(day=1).date()
        end = dt.replace(day=28) + timedelta(4)
        end = (end - timedelta(end.day-1)).date()
        return CalendarInfo(start, end - start)

    def custom_monthly_handler(self, sender, consolidated):
        '''This is our event handler Custom Monthly function'''
        self.log(f"{consolidated.time} >> CustomMonthlyHandler >> {consolidated.close}")

    def on_end_of_algorithm(self):
        if not self.consolidated_hour:
            raise AssertionError("Expected hourly consolidator to be fired.")

        if not self.consolidated45_minute:
            raise AssertionError("Expected 45-minute consolidator to be fired.")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm illustrating the usage of the <see cref="QCAlgorithm.OptionChain(Symbol)"/> method
to get a future option chain.

Output:
```python

from AlgorithmImports import *

class FutureOptionChainFullDataRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2020, 1, 6)
        self.set_end_date(2020, 1, 6)

        future_contract = self.add_future_contract(
            Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 3, 20)),
            Resolution.MINUTE).symbol

        option_chain = self.option_chain(future_contract, flatten=True)

        # Demonstration using data frame:
        df = option_chain.data_frame
        # Get contracts expiring within 4 months, with the latest expiration date, highest strike and lowest price
        contracts = df.loc[(df.expiry <= self.time + timedelta(days=120))]
        contracts = contracts.sort_values(['expiry', 'strike', 'lastprice'], ascending=[False, False, True])
        self._option_contract = contracts.index[0]

        self.add_future_option_contract(self._option_contract)

    def on_data(self, data):
        # Do some trading with the selected contract for sample purposes
        if not self.portfolio.invested:
            self.set_holdings(self._option_contract, 0.5)
        else:
            self.liquidate()
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: The regression algorithm showcases the utilization of a custom data source with the Sort flag set to true.
This means that the source initially provides data in descending order, which is then organized into ascending order and returned in the 'on_data' function.

Output:
```python

from AlgorithmImports import *

class DescendingCustomDataObjectStoreRegressionAlgorithm(QCAlgorithm):
    descending_custom_data = [
        "2024-10-03 19:00:00,173.5,176.0,172.0,175.2,120195681,4882.29",
        "2024-10-02 18:00:00,174.0,177.0,173.0,175.8,116275729,4641.97",
        "2024-10-01 17:00:00,175.0,178.0,172.5,174.5,127707078,6591.27",
        "2024-09-30 11:00:00,174.8,176.5,172.8,175.0,127707078,6591.27",
        "2024-09-27 10:00:00,172.5,175.0,171.5,173.5,120195681,4882.29",
        "2024-09-26 09:00:00,171.0,172.5,170.0,171.8,117516350,4820.53",
        "2024-09-25 08:00:00,169.5,172.0,169.0,171.0,110427867,4661.55",
        "2024-09-24 07:00:00,170.0,171.0,168.0,169.5,127624733,4823.52",
        "2024-09-23 06:00:00,172.0,173.5,169.5,171.5,123586417,4303.93",
        "2024-09-20 05:00:00,168.0,171.0,167.5,170.5,151929179,5429.87",
        "2024-09-19 04:00:00,170.5,171.5,166.0,167.0,160523863,5219.24",
        "2024-09-18 03:00:00,173.0,174.0,169.0,172.0,145721790,5163.09",
        "2024-09-17 02:00:00,171.0,173.5,170.0,172.5,144794030,5405.72",
        "2024-09-16 01:00:00,168.0,171.0,167.0,170.0,214402430,8753.33",
        "2024-09-13 16:00:00,173.5,176.0,172.0,175.2,120195681,4882.29",
        "2024-09-12 15:00:00,174.5,177.5,173.5,176.5,171728134,7774.83",
        "2024-09-11 14:00:00,175.0,178.0,174.0,175.5,191516153,8349.59",
        "2024-09-10 13:00:00,174.5,176.0,173.0,174.0,151162819,5915.8",
        "2024-09-09 12:00:00,176.0,178.0,175.0,177.0,116275729,4641.97"
    ]

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 9)
        self.set_end_date(2024, 10, 3)
        self.set_cash(100000)

        self.set_benchmark(lambda x: 0)

        SortCustomData.custom_data_key = self.get_custom_data_key()

        self._custom_symbol = self.add_data(SortCustomData, "SortCustomData", Resolution.DAILY).symbol

        # Saving data here for demonstration and regression testing purposes.
        # In real scenarios, data has to be saved to the object store before the algorithm starts.
        self.object_store.save(self.get_custom_data_key(), "\n".join(self.descending_custom_data))

        self.received_data = []

    def on_data(self, slice: Slice) -> None:
        if slice.contains_key(self._custom_symbol):
            custom_data = slice.get(SortCustomData, self._custom_symbol)
            if custom_data.open == 0 or custom_data.high == 0 or custom_data.low == 0 or custom_data.close == 0 or custom_data.price == 0:
                raise AssertionError("One or more custom data fields (open, high, low, close, price) are zero.")

            self.received_data.append(custom_data)

    def on_end_of_algorithm(self) -> None:
        if not self.received_data:
            raise AssertionError("Custom data was not fetched")

        # Make sure history requests work as expected
        history = self.history(SortCustomData, self._custom_symbol, self.start_date, self.end_date, Resolution.DAILY)

        if history.shape[0] != len(self.received_data):
            raise AssertionError("History request returned more or less data than expected")

        # Iterate through the history collection, checking if the time is in ascending order.
        for i in range(len(history) - 1):
            # [1] - time
            if history.index[i][1] > history.index[i + 1][1]:
                raise AssertionError(
                    f"Order failure: {history.index[i][1]} > {history.index[i + 1][1]} at index {i}.")

    def get_custom_data_key(self) -> str:
        return "CustomData/SortCustomData"

class SortCustomData(PythonData):
    custom_data_key = ""

    def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:
        subscription = SubscriptionDataSource(self.custom_data_key, SubscriptionTransportMedium.OBJECT_STORE,
                                              FileFormat.CSV)
        # Indicate that the data from the subscription will be returned in descending order.
        subscription.sort = True
        return subscription

    def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData:
        data = line.split(',')
        obj_data = SortCustomData()
        obj_data.symbol = config.symbol
        obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S')
        obj_data.value = float(data[4])
        obj_data["Open"] = float(data[1])
        obj_data["High"] = float(data[2])
        obj_data["Low"] = float(data[3])
        obj_data["Close"] = float(data[4])
        return obj_data
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Basic Continuous Futures Template Algorithm

Output:
```python

from AlgorithmImports import *

class BasicTemplateContinuousFutureAlgorithm(QCAlgorithm):
    '''Basic template algorithm simply initializes the date range and cash'''

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2013, 7, 1)
        self.set_end_date(2014, 1, 1)

        self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI,
                                                  data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,
                                                  data_mapping_mode = DataMappingMode.LAST_TRADING_DAY,
                                                  contract_depth_offset = 0)

        self._fast = self.sma(self._continuous_contract.symbol, 4, Resolution.DAILY)
        self._slow = self.sma(self._continuous_contract.symbol, 10, Resolution.DAILY)
        self._current_contract = None

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        for changed_event in data.symbol_changed_events.values():
            if changed_event.symbol == self._continuous_contract.symbol:
                self.log(f"SymbolChanged event: {changed_event}")

        if not self.portfolio.invested:
            if self._fast.current.value > self._slow.current.value:
                self._current_contract = self.securities[self._continuous_contract.mapped]
                self.buy(self._current_contract.symbol, 1)
        elif self._fast.current.value < self._slow.current.value:
            self.liquidate()

        # We check exchange hours because the contract mapping can call OnData outside of regular hours.
        if self._current_contract is not None and self._current_contract.symbol != self._continuous_contract.mapped and self._continuous_contract.exchange.exchange_open:
            self.log(f"{self.time} - rolling position from {self._current_contract.symbol} to {self._continuous_contract.mapped}")

            current_position_size = self._current_contract.holdings.quantity
            self.liquidate(self._current_contract.symbol)
            self.buy(self._continuous_contract.mapped, current_position_size)
            self._current_contract = self.securities[self._continuous_contract.mapped]

    def on_order_event(self, order_event):
        self.debug("Purchased Stock: {0}".format(order_event.symbol))

    def on_securities_changed(self, changes):
        self.debug(f"{self.time}-{changes}")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This algorithm sends portfolio targets to CrunchDAO API once a week.

Output:
```python

from AlgorithmImports import *

class CrunchDAOSignalExportDemonstrationAlgorithm(QCAlgorithm):

    crunch_universe = []

    def initialize(self) -> None:
        self.set_start_date(2023, 5, 22)
        self.set_end_date(2023, 5, 26)
        self.set_cash(1_000_000)

        # Disable automatic exports as we manually set them
        self.signal_export.automatic_export_time_span = None

        # Connect to CrunchDAO
        api_key = ""            # Your CrunchDAO API key
        model = ""              # The Id of your CrunchDAO model
        submission_name = ""    # A name for the submission to distinguish it from your other submissions
        comment = ""            # A comment for the submission
        self.signal_export.add_signal_export_provider(CrunchDAOSignalExport(api_key, model, submission_name, comment))

        self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))

        # Add a custom data universe to read the CrunchDAO skeleton
        self.add_universe(CrunchDaoSkeleton, "CrunchDaoSkeleton", Resolution.DAILY, self.select_symbols)

        # Create a Scheduled Event to submit signals every monday before the market opens
        self._week = -1
        self.schedule.on(
            self.date_rules.every([DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY]),
            self.time_rules.at(13, 15, TimeZones.UTC),
            self.submit_signals)

        self.settings.minimum_order_margin_portfolio_percentage = 0

        self.set_warm_up(timedelta(45))

    def select_symbols(self, data: list[CrunchDaoSkeleton]) -> list[Symbol]:
        return [x.symbol for x in data]

    def on_securities_changed(self, changes: SecurityChanges) -> None:
        for security in changes.removed_securities:
            if security in self.crunch_universe:
                self.crunch_universe.remove(security)
        self.crunch_universe.extend(changes.added_securities)

    def submit_signals(self) -> None:
        if self.is_warming_up:
            return

        # Submit signals once per week
        week_num = self.time.isocalendar()[1]
        if self._week == week_num:
            return
        self._week = week_num

        symbols = [security.symbol for security in self.crunch_universe if security.price > 0]

        # Get historical price data
        # close_prices = self.history(symbols, 22, Resolution.DAILY).close.unstack(0)

        # Create portfolio targets
        weight_by_symbol = {symbol: 1/len(symbols) for symbol in symbols} # Add your logic here
        targets = [PortfolioTarget(symbol, weight) for symbol, weight in weight_by_symbol.items()]

        # (Optional) Place trades
        self.set_holdings(targets)

        # Send signals to CrunchDAO
        success = self.signal_export.set_target_portfolio(targets)
        if not success:
            self.debug(f"Couldn't send targets at {self.time}")

class CrunchDaoSkeleton(PythonData):

    def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:
        return SubscriptionDataSource("https://tournament.crunchdao.com/data/skeleton.csv", SubscriptionTransportMedium.REMOTE_FILE)

    def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> DynamicData:
        if not line[0].isdigit():
            return None
        skeleton = CrunchDaoSkeleton()
        skeleton.symbol = config.symbol

        try:
            csv = line.split(',')
            skeleton.end_time = datetime.strptime(csv[0], "%Y-%m-%d")
            skeleton.symbol =  Symbol(SecurityIdentifier.generate_equity(csv[1], Market.USA, mapping_resolve_date=skeleton.time), csv[1])
            skeleton["Ticker"] = csv[1]

        except ValueError:
            # Do nothing
            return None

        return skeleton
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Example and regression algorithm asserting the behavior of registering and unregistering an indicator from the engine

Output:
```python

from AlgorithmImports import *

class UnregisterIndicatorRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
        self.set_start_date(2013,10, 7)
        self.set_end_date(2013,10,11)

        spy = self.add_equity("SPY")
        ibm = self.add_equity("IBM")

        self._symbols = [ spy.symbol, ibm.symbol ]
        self._trin = self.trin(self._symbols, Resolution.MINUTE)
        self._trin2 = None

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if self._trin.is_ready:
            self._trin.reset()
            self.unregister_indicator(self._trin)

            # let's create a new one with a differente resolution
            self._trin2 = self.trin(self._symbols, Resolution.HOUR)

        if not self._trin2 is None and self._trin2.is_ready:
            if self._trin.is_ready:
                raise ValueError("Indicator should of stop getting updates!")

            if not self.portfolio.invested:
                self.set_holdings(self._symbols[0], 0.5)
                self.set_holdings(self._symbols[1], 0.5)
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm testing GH feature 3790, using SetHoldings with a collection of targets
which will be ordered by margin impact before being executed, with the objective of avoiding any
margin errors

Output:
```python

from AlgorithmImports import *

class SetHoldingsMultipleTargetsRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2013,10, 7)
        self.set_end_date(2013,10,11)

        # use leverage 1 so we test the margin impact ordering
        self._spy = self.add_equity("SPY", Resolution.MINUTE, Market.USA, False, 1).symbol
        self._ibm = self.add_equity("IBM", Resolution.MINUTE, Market.USA, False, 1).symbol

        # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
        # Commented so regression algorithm is more sensitive
        #self.settings.minimum_order_margin_portfolio_percentage = 0.005

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            self.set_holdings([PortfolioTarget(self._spy, 0.8), PortfolioTarget(self._ibm, 0.2)])
        else:
            self.set_holdings([PortfolioTarget(self._ibm, 0.8), PortfolioTarget(self._spy, 0.2)])
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Algorithm demonstrating the portfolio target tags usage

Output:
```python

from AlgorithmImports import *

class PortfolioTargetTagsRegressionAlgorithm(QCAlgorithm):
    '''Algorithm demonstrating the portfolio target tags usage'''

    def initialize(self):
        self.set_start_date(2013,10,7)   #Set Start Date
        self.set_end_date(2013,10,11)    #Set End Date
        self.set_cash(100000)           #Set Strategy Cash

        self.universe_settings.resolution = Resolution.MINUTE

        symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]

        # set algorithm framework models
        self.set_universe_selection(ManualUniverseSelectionModel(symbols))
        self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))

        self.set_portfolio_construction(CustomPortfolioConstructionModel())
        self.set_risk_management(CustomRiskManagementModel())
        self.set_execution(CustomExecutionModel(self.set_target_tags_checked))

        self.target_tags_checked = False

    def set_target_tags_checked(self):
        self.target_tags_checked = True

    def on_end_of_algorithm(self):
        if not self.target_tags_checked:
            raise AssertionError("The portfolio targets tag were not checked")

class CustomPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):
    def __init__(self):
        super().__init__(Resolution.DAILY)

    def create_targets(self, algorithm: QCAlgorithm, insights: List[Insight]) -> List[IPortfolioTarget]:
        targets = super().create_targets(algorithm, insights)
        return CustomPortfolioConstructionModel.add_p_portfolio_targets_tags(targets)

    @staticmethod
    def generate_portfolio_target_tag(target: IPortfolioTarget) -> str:
        return f"Portfolio target tag: {target.symbol} - {target.quantity:g}"

    @staticmethod
    def add_p_portfolio_targets_tags(targets: Iterable[IPortfolioTarget]) -> List[IPortfolioTarget]:
        return [PortfolioTarget(target.symbol, target.quantity, CustomPortfolioConstructionModel.generate_portfolio_target_tag(target))
                for target in targets]

class CustomRiskManagementModel(MaximumDrawdownPercentPerSecurity):
    def __init__(self):
        super().__init__(0.01)

    def manage_risk(self, algorithm: QCAlgorithm, targets: List[IPortfolioTarget]) -> List[IPortfolioTarget]:
        risk_managed_targets = super().manage_risk(algorithm, targets)
        return CustomPortfolioConstructionModel.add_p_portfolio_targets_tags(risk_managed_targets)

class CustomExecutionModel(ImmediateExecutionModel):
    def __init__(self, targets_tag_checked_callback: Callable) -> None:
        super().__init__()
        self.targets_tag_checked_callback = targets_tag_checked_callback

    def execute(self, algorithm: QCAlgorithm, targets: List[IPortfolioTarget]) -> None:
        if len(targets) > 0:
            self.targets_tag_checked_callback()

        for target in targets:
            expected_tag = CustomPortfolioConstructionModel.generate_portfolio_target_tag(target)
            if target.tag != expected_tag:
                raise AssertionError(f"Unexpected portfolio target tag: {target.tag} - Expected: {expected_tag}")

        super().execute(algorithm, targets)
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration of using the Delisting event in your algorithm. Assets are delisted on their last day of trading, or when their contract expires.
This data is not included in the open source project.

Output:
```python

from AlgorithmImports import *

class DelistingEventsAlgorithm(QCAlgorithm):

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2007, 5, 15)  #Set Start Date
        self.set_end_date(2007, 5, 25)    #Set End Date
        self.set_cash(100000)             #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.add_equity("AAA.1", Resolution.DAILY)
        self.add_equity("SPY", Resolution.DAILY)

    def on_data(self, data):
        '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if self.transactions.orders_count == 0:
            self.set_holdings("AAA.1", 1)
            self.debug("Purchased stock")

        for kvp in data.bars:
            symbol = kvp.key
            value = kvp.value

            self.log("OnData(Slice): {0}: {1}: {2}".format(self.time, symbol, value.close))

        # the slice can also contain delisting data: data.delistings in a dictionary string->Delisting

        aaa = self.securities["AAA.1"]
        if aaa.is_delisted and aaa.is_tradable:
            raise AssertionError("Delisted security must NOT be tradable")

        if not aaa.is_delisted and not aaa.is_tradable:
            raise AssertionError("Securities must be marked as tradable until they're delisted or removed from the universe")

        for kvp in data.delistings:
            symbol = kvp.key
            value = kvp.value

            if value.type == DelistingType.WARNING:
                self.log("OnData(Delistings): {0}: {1} will be delisted at end of day today.".format(self.time, symbol))

                # liquidate on delisting warning
                self.set_holdings(symbol, 0)

            if value.type == DelistingType.DELISTED:
                self.log("OnData(Delistings): {0}: {1} has been delisted.".format(self.time, symbol))

                # fails because the security has already been delisted and is no longer tradable
                self.set_holdings(symbol, 1)

    def on_order_event(self, order_event):
        self.log("OnOrderEvent(OrderEvent): {0}: {1}".format(self.time, order_event))
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration algorithm showing how to easily convert an old algorithm into the framework.

 1. When making orders, also create insights for the correct direction (up/down/flat), can also set insight prediction period/magnitude/direction
 2. Emit insights before placing any trades
 3. Profit :)

Output:
```python

from AlgorithmImports import *

class ConvertToFrameworkAlgorithm(QCAlgorithm):
    '''Demonstration algorithm showing how to easily convert an old algorithm into the framework.'''

    fast_ema_period = 12
    slow_ema_period = 26

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2004, 1, 1)
        self.set_end_date(2015, 1, 1)

        self._symbol = self.add_security(SecurityType.EQUITY, 'SPY', Resolution.DAILY).symbol

        # define our daily macd(12,26) with a 9 day signal
        self._macd = self.macd(self._symbol, self.fast_ema_period, self.slow_ema_period, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY)

    def on_data(self, data):
        '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        Args:
            data: Slice object with your stock data'''
        # wait for our indicator to be ready
        if not self._macd.is_ready or not data.contains_key(self._symbol) or data[self._symbol] is None: return

        holding = self.portfolio[self._symbol]

        signal_delta_percent = float(self._macd.current.value - self._macd.signal.current.value) / float(self._macd.fast.current.value)
        tolerance = 0.0025

        # if our macd is greater than our signal, then let's go long
        if holding.quantity <= 0 and signal_delta_percent > tolerance:
            # 1. Call emit_insights with insights created in correct direction, here we're going long
            #    The emit_insights method can accept multiple insights separated by commas
            self.emit_insights(
                # Creates an insight for our symbol, predicting that it will move up within the fast ema period number of days
                Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.UP)
            )

            # longterm says buy as well
            self.set_holdings(self._symbol, 1)

        # if our macd is less than our signal, then let's go short
        elif holding.quantity >= 0 and signal_delta_percent < -tolerance:
            # 1. Call emit_insights with insights created in correct direction, here we're going short
            #    The emit_insights method can accept multiple insights separated by commas
            self.emit_insights(
                # Creates an insight for our symbol, predicting that it will move down within the fast ema period number of days
                Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.DOWN)
            )

            self.set_holdings(self._symbol, -1)

        # if we wanted to liquidate our positions
        ## 1. Call emit_insights with insights create in the correct direction -- Flat

        #self.emit_insights(
            # Creates an insight for our symbol, predicting that it will move down or up within the fast ema period number of days, depending on our current position
            # Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.FLAT)
        #)

        # self.liquidate()

        # plot both lines
        self.plot("MACD", self._macd, self._macd.signal)
        self.plot(self._symbol.value, self._macd.fast, self._macd.slow)
        self.plot(self._symbol.value, "Open", data[self._symbol].open)
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Algorithm asserting that consolidated bars are of type `QuoteBar` when `QCAlgorithm.consolidate()` is called with `tick_type=TickType.QUOTE`

Output:
```python

from AlgorithmImports import *

class CorrectConsolidatedBarTypeForTickTypesAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 7)

        symbol = self.add_equity("SPY", Resolution.TICK).symbol

        self.consolidate(symbol, timedelta(minutes=1), TickType.QUOTE, self.quote_tick_consolidation_handler)
        self.consolidate(symbol, timedelta(minutes=1), TickType.TRADE, self.trade_tick_consolidation_handler)

        self.quote_tick_consolidation_handler_called = False
        self.trade_tick_consolidation_handler_called = False

    def on_data(self, slice: Slice) -> None:
        if self.time.hour > 9:
            self.quit("Early quit to save time")

    def on_end_of_algorithm(self):
        if not self.quote_tick_consolidation_handler_called:
            raise AssertionError("quote_tick_consolidation_handler was not called")

        if not self.trade_tick_consolidation_handler_called:
            raise AssertionError("trade_tick_consolidation_handler was not called")

    def quote_tick_consolidation_handler(self, consolidated_bar: QuoteBar) -> None:
        if type(consolidated_bar) != QuoteBar:
            raise AssertionError(f"Expected the consolidated bar to be of type {QuoteBar} but was {type(consolidated_bar)}")

        self.quote_tick_consolidation_handler_called = True

    def trade_tick_consolidation_handler(self, consolidated_bar: TradeBar) -> None:
        if type(consolidated_bar) != TradeBar:
            raise AssertionError(f"Expected the consolidated bar to be of type {TradeBar} but was {type(consolidated_bar)}")

        self.trade_tick_consolidation_handler_called = True
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration of the Scheduled Events features available in QuantConnect.

Output:
```python

from AlgorithmImports import *

class ScheduledEventsAlgorithm(QCAlgorithm):

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2013,10,7)   #Set Start Date
        self.set_end_date(2013,10,11)    #Set End Date
        self.set_cash(100000)           #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.add_equity("SPY")

        # events are scheduled using date and time rules
        # date rules specify on what dates and event will fire
        # time rules specify at what time on thos dates the event will fire

        # schedule an event to fire at a specific date/time
        self.schedule.on(self.date_rules.on(2013, 10, 7), self.time_rules.at(13, 0), self.specific_time)

        # schedule an event to fire every trading day for a security the
        # time rule here tells it to fire 10 minutes after SPY's market open
        self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.after_market_open("SPY", 10), self.every_day_after_market_open)

        # schedule an event to fire every trading day for a security the
        # time rule here tells it to fire 10 minutes before SPY's market close
        self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.before_market_close("SPY", 10), self.every_day_after_market_close)

        # schedule an event to fire on a single day of the week
        self.schedule.on(self.date_rules.every(DayOfWeek.WEDNESDAY), self.time_rules.at(12, 0), self.every_wed_at_noon)

        # schedule an event to fire on certain days of the week
        self.schedule.on(self.date_rules.every(DayOfWeek.MONDAY, DayOfWeek.FRIDAY), self.time_rules.at(12, 0), self.every_mon_fri_at_noon)

        # the scheduling methods return the ScheduledEvent object which can be used for other things here I set
        # the event up to check the portfolio value every 10 minutes, and liquidate if we have too many losses
        self.schedule.on(self.date_rules.every_day(), self.time_rules.every(timedelta(minutes=10)), self.liquidate_unrealized_losses)

        # schedule an event to fire at the beginning of the month, the symbol is optional
        # if specified, it will fire the first trading day for that symbol of the month,
        # if not specified it will fire on the first day of the month
        self.schedule.on(self.date_rules.month_start("SPY"), self.time_rules.after_market_open("SPY"), self.rebalancing_code)

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        if not self.portfolio.invested:
            self.set_holdings("SPY", 1)

    def specific_time(self):
        self.log(f"SpecificTime: Fired at : {self.time}")

    def every_day_after_market_open(self):
        self.log(f"EveryDay.SPY 10 min after open: Fired at: {self.time}")

    def every_day_after_market_close(self):
        self.log(f"EveryDay.SPY 10 min before close: Fired at: {self.time}")

    def every_wed_at_noon(self):
        self.log(f"Wed at 12pm: Fired at: {self.time}")

    def every_mon_fri_at_noon(self):
        self.log(f"Mon/Fri at 12pm: Fired at: {self.time}")

    def liquidate_unrealized_losses(self):
        ''' if we have over 1000 dollars in unrealized losses, liquidate'''
        if self.portfolio.total_unrealized_profit < -1000:
            self.log(f"Liquidated due to unrealized losses at: {self.time}")
            self.liquidate()

    def rebalancing_code(self):
        ''' Good spot for rebalancing code?'''
        pass
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Show example of how to use the TrailingStopRiskManagementModel

Output:
```python

from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Risk.TrailingStopRiskManagementModel import TrailingStopRiskManagementModel

class TrailingStopRiskFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
    '''Show example of how to use the TrailingStopRiskManagementModel'''

    def initialize(self):
        super().initialize()
        self.set_universe_selection(ManualUniverseSelectionModel([Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)]))

        self.set_risk_management(TrailingStopRiskManagementModel(0.01))
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Example algorithm showing how to use QCAlgorithm.train method

Output:
```python

from AlgorithmImports import *
from time import sleep

class TrainingExampleAlgorithm(QCAlgorithm):
    '''Example algorithm showing how to use QCAlgorithm.train method'''

    def initialize(self):

        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 14)

        self.add_equity("SPY", Resolution.DAILY)

        # Set TrainingMethod to be executed immediately
        self.train(self.training_method)

        # Set TrainingMethod to be executed at 8:00 am every Sunday
        self.train(self.date_rules.every(DayOfWeek.SUNDAY), self.time_rules.at(8 , 0), self.training_method)

    def training_method(self):

        self.log(f'Start training at {self.time}')
        # Use the historical data to train the machine learning model
        history = self.history(["SPY"], 200, Resolution.DAILY)

        # ML code:
        pass
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting that the option chain APIs return consistent values for index options.
See QCAlgorithm.OptionChain(Symbol) and QCAlgorithm.OptionChainProvider

Output:
```python

from datetime import datetime
from AlgorithmImports import *

from OptionChainApisConsistencyRegressionAlgorithm import OptionChainApisConsistencyRegressionAlgorithm

class IndexOptionChainApisConsistencyRegressionAlgorithm(OptionChainApisConsistencyRegressionAlgorithm):

    def get_test_date(self) -> datetime:
        return datetime(2021, 1, 4)

    def get_option(self) -> Option:
        return self.add_index_option("SPX")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm illustrating the usage of the <see cref="QCAlgorithm.OptionChains(IEnumerable{Symbol})"/> method
to get multiple option chains, which contains additional data besides the symbols, including prices, implied volatility and greeks.
It also shows how this data can be used to filter the contracts based on certain criteria.

Output:
```python

from AlgorithmImports import *
from datetime import timedelta

class OptionChainsMultipleFullDataRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2015, 12, 24)
        self.set_end_date(2015, 12, 24)
        self.set_cash(100000)

        goog = self.add_equity("GOOG").symbol
        spx = self.add_index("SPX").symbol

        chains = self.option_chains([goog, spx], flatten=True)

        self._goog_option_contract = self.get_contract(chains, goog, timedelta(days=10))
        self._spx_option_contract = self.get_contract(chains, spx, timedelta(days=60))

        self.add_option_contract(self._goog_option_contract)
        self.add_index_option_contract(self._spx_option_contract)

    def get_contract(self, chains: OptionChains, underlying: Symbol, expiry_span: timedelta) -> Symbol:
        df = chains.data_frame

        # Index by the requested underlying, by getting all data with canonicals which underlying is the requested underlying symbol:
        canonicals = df.index.get_level_values('canonical')
        condition = [canonical for canonical in canonicals if canonical.underlying == underlying]
        df = df.loc[condition]

        # Get contracts expiring in the next 10 days with an implied volatility greater than 0.5 and a delta less than 0.5
        contracts = df.loc[(df.expiry <= self.time + expiry_span) & (df.impliedvolatility > 0.5) & (df.delta < 0.5)]

        # Select the contract with the latest expiry date
        contracts.sort_values(by='expiry', ascending=False, inplace=True)

        # Get the symbol: the resulting series name is a tuple (canonical symbol, contract symbol)
        return contracts.iloc[0].name[1]

    def on_data(self, data):
        # Do some trading with the selected contract for sample purposes
        if not self.portfolio.invested:
            self.market_order(self._goog_option_contract, 1)
        else:
            self.liquidate()
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: In this algorithm we demonstrate how to use the UniverseSettings
to define the data normalization mode (raw)

Output:
```python

from AlgorithmImports import *

class RawPricesUniverseRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        # what resolution should the data *added* to the universe be?
        self.universe_settings.resolution = Resolution.DAILY

        # Use raw prices
        self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW

        self.set_start_date(2014,3,24)    #Set Start Date
        self.set_end_date(2014,4,7)      #Set End Date
        self.set_cash(50000)            #Set Strategy Cash

        # Set the security initializer with zero fees and price initial seed
        securitySeeder = FuncSecuritySeeder(self.get_last_known_prices)
        self.set_security_initializer(CompositeSecurityInitializer(
            FuncSecurityInitializer(lambda x: x.set_fee_model(ConstantFeeModel(0))),
            FuncSecurityInitializer(lambda security: securitySeeder.seed_security(security))))

        self.add_universe("MyUniverse", Resolution.DAILY, self.selection_function)

    def selection_function(self, date_time):
        if date_time.day % 2 == 0:
            return ["SPY", "IWM", "QQQ"]
        else:
            return ["AIG", "BAC", "IBM"]

    # this event fires whenever we have changes to our universe
    def on_securities_changed(self, changes):
        # liquidate removed securities
        for security in changes.removed_securities:
            if security.invested:
                self.liquidate(security.symbol)

        # we want 20% allocation in each security in our universe
        for security in changes.added_securities:
            self.set_holdings(security.symbol, 0.2)
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Algorithm asserting that closed orders can be updated with a new tag

Output:
```python

from AlgorithmImports import *

class CompleteOrderTagUpdateAlgorithm(QCAlgorithm):

    _tag_after_fill = "This is the tag set after order was filled."
    _tag_after_canceled = "This is the tag set after order was canceled."

    def initialize(self) -> None:
        self.set_start_date(2013,10, 7)
        self.set_end_date(2013,10,11)
        self.set_cash(100000)

        self._spy = self.add_equity("SPY", Resolution.MINUTE).symbol

        self._market_order_ticket = None
        self._limit_order_ticket = None

        self._quantity = 100

    def on_data(self, data: Slice) -> None:
        if not self.portfolio.invested:
            if self._limit_order_ticket is None:
                # a limit order to test the tag update after order was canceled.

                # low price, we don't want it to fill since we are canceling it
                self._limit_order_ticket = self.limit_order(self._spy, 100, self.securities[self._spy].price * 0.1)
                self._limit_order_ticket.cancel()
            else:
                # a market order to test the tag update after order was filled.
                self.buy(self._spy, self._quantity)

    def on_order_event(self, order_event: OrderEvent) -> None:
        if order_event.status == OrderStatus.CANCELED:
            if not self._limit_order_ticket or order_event.order_id != self._limit_order_ticket.order_id:
                raise AssertionError("The only canceled order should have been the limit order.")

            # update canceled order tag
            self.update_order_tag(self._limit_order_ticket, self._tag_after_canceled, "Error updating order tag after canceled")
        elif order_event.status == OrderStatus.FILLED:
            self._market_order_ticket = list(self.transactions.get_order_tickets(lambda x: x.order_type == OrderType.MARKET))[0]
            if not self._market_order_ticket or order_event.order_id != self._market_order_ticket.order_id:
                raise AssertionError("The only filled order should have been the market order.")

            # update filled order tag
            self.update_order_tag(self._market_order_ticket, self._tag_after_fill, "Error updating order tag after fill")

    def on_end_of_algorithm(self) -> None:
        # check the filled order
        self.assert_order_tag_update(self._market_order_ticket, self._tag_after_fill, "filled")
        if self._market_order_ticket.quantity != self._quantity or self._market_order_ticket.quantity_filled != self._quantity:
            raise AssertionError("The market order quantity should not have been updated.")

        # check the canceled order
        self.assert_order_tag_update(self._limit_order_ticket, self._tag_after_canceled, "canceled")

    def assert_order_tag_update(self, ticket: OrderTicket, expected_tag: str, order_action: str) -> None:
        if ticket is None:
            raise AssertionError(f"The order ticket was not set for the {order_action} order")

        if ticket.tag != expected_tag:
            raise AssertionError(f"Order ticket tag was not updated after order was {order_action}")

        order = self.transactions.get_order_by_id(ticket.order_id)
        if order.tag != expected_tag:
            raise AssertionError(f"Order tag was not updated after order was {order_action}")

    def update_order_tag(self, ticket: OrderTicket, tag: str, error_message_prefix: str) -> None:
        update_fields = UpdateOrderFields()
        update_fields.tag = tag
        response = ticket.update(update_fields)

        if response.is_error:
            raise AssertionError(f"{error_message_prefix}: {response.error_message}")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm for the StandardDeviationExecutionModel.
This algorithm shows how the execution model works to split up orders and submit them
only when the price is 2 standard deviations from the 60min mean (default model settings).

Output:
```python

from AlgorithmImports import *
from Alphas.RsiAlphaModel import RsiAlphaModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
from Execution.StandardDeviationExecutionModel import StandardDeviationExecutionModel

class StandardDeviationExecutionModelRegressionAlgorithm(QCAlgorithm):
    '''Regression algorithm for the StandardDeviationExecutionModel.
    This algorithm shows how the execution model works to split up orders and submit them
    only when the price is 2 standard deviations from the 60min mean (default model settings).'''

    def initialize(self):
        ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        # Set requested data resolution
        self.universe_settings.resolution = Resolution.MINUTE

        self.set_start_date(2013,10,7)
        self.set_end_date(2013,10,11)
        self.set_cash(1000000)

        self.set_universe_selection(ManualUniverseSelectionModel([
            Symbol.create('AIG', SecurityType.EQUITY, Market.USA),
            Symbol.create('BAC', SecurityType.EQUITY, Market.USA),
            Symbol.create('IBM', SecurityType.EQUITY, Market.USA),
            Symbol.create('SPY', SecurityType.EQUITY, Market.USA)
        ]))

        self.set_alpha(RsiAlphaModel(14, Resolution.HOUR))
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
        self.set_execution(StandardDeviationExecutionModel())

    def on_order_event(self, order_event):
        self.log(f"{self.time}: {order_event}")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Example algorithm of the Identity indicator with the filtering enhancement. Filtering is used to check
the output of the indicator before returning it.

Output:
```python

from AlgorithmImports import *

class FilteredIdentityAlgorithm(QCAlgorithm):
    ''' Example algorithm of the Identity indicator with the filtering enhancement '''

    def initialize(self):

        self.set_start_date(2014,5,2)       # Set Start Date
        self.set_end_date(self.start_date)   # Set End Date
        self.set_cash(100000)              # Set Stratgy Cash

        # Find more symbols here: http://quantconnect.com/data
        security = self.add_forex("EURUSD", Resolution.TICK)

        self._symbol = security.symbol
        self._identity = self.filtered_identity(self._symbol, filter=self.filter)

    def filter(self, data):
        '''Filter function: True if data is not an instance of Tick. If it is, true if TickType is Trade
        data -- Data for applying the filter'''
        if isinstance(data, Tick):
            return data.tick_type == TickType.TRADE
        return True

    def on_data(self, data):
        # Since we are only accepting TickType.TRADE,
        # this indicator will never be ready
        if not self._identity.is_ready: return
        if not self.portfolio.invested:
            self.set_holdings(self._symbol, 1)
            self.debug("Purchased Stock")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This algorithm asserts we can consolidate Tick data with different tick types

Output:
```python

from AlgorithmImports import *

class ConsolidateDifferentTickTypesRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013, 10, 6)
        self.set_end_date(2013, 10, 7)
        self.set_cash(1000000)

        equity = self.add_equity("SPY", Resolution.TICK, Market.USA)
        quote_consolidator = self.consolidate(equity.symbol, Resolution.TICK, TickType.QUOTE, lambda tick : self.on_quote_tick(tick))
        self.there_is_at_least_one_quote_tick = False

        trade_consolidator = self.consolidate(equity.symbol, Resolution.TICK, TickType.TRADE, lambda tick : self.on_trade_tick(tick))
        self.there_is_at_least_one_trade_tick = False

        # Tick consolidators with max count
        self.consolidate(TradeBar, equity.symbol, 10, TickType.TRADE, lambda trade_bar: self.on_trade_tick_max_count(trade_bar))
        self._there_is_at_least_one_trade_bar = False

        self.consolidate(QuoteBar, equity.symbol, 10, TickType.QUOTE, lambda quote_bar: self.on_quote_tick_max_count(quote_bar))
        self._there_is_at_least_one_quote_bar = False

        self._consolidation_count = 0

    def on_trade_tick_max_count(self, trade_bar):
        self._there_is_at_least_one_trade_bar = True
        if type(trade_bar) != TradeBar:
            raise AssertionError(f"The type of the bar should be Trade, but was {type(trade_bar)}")

    def on_quote_tick_max_count(self, quote_bar):
        self._there_is_at_least_one_quote_bar = True
        if type(quote_bar) != QuoteBar:
            raise AssertionError(f"The type of the bar should be Quote, but was {type(quote_bar)}")

        self._consolidation_count += 1
        # Let's shortcut to reduce regression test duration: algorithms using tick data are too long
        if self._consolidation_count >= 1000:
            self.quit()

    def on_quote_tick(self, tick):
        self.there_is_at_least_one_quote_tick = True
        if tick.tick_type != TickType.QUOTE:
            raise AssertionError(f"The type of the tick should be Quote, but was {tick.tick_type}")

    def on_trade_tick(self, tick):
        self.there_is_at_least_one_trade_tick = True
        if tick.tick_type != TickType.TRADE:
            raise AssertionError(f"The type of the tick should be Trade, but was {tick.tick_type}")

    def on_end_of_algorithm(self):
        if not self.there_is_at_least_one_quote_tick:
            raise AssertionError(f"There should have been at least one tick in OnQuoteTick() method, but there wasn't")

        if not self.there_is_at_least_one_trade_tick:
            raise AssertionError(f"There should have been at least one tick in OnTradeTick() method, but there wasn't")

        if not self._there_is_at_least_one_trade_bar:
            raise AssertionError("There should have been at least one bar in OnTradeTickMaxCount() method, but there wasn't")

        if not self._there_is_at_least_one_quote_bar:
            raise AssertionError("There should have been at least one bar in OnQuoteTickMaxCount() method, but there wasn't")

```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm demonstrating the option universe filter by greeks and other options data feature

Output:
```python

from AlgorithmImports import *

class OptionUniverseFilterGreeksRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2015, 12, 24)
        self.set_end_date(2015, 12, 24)
        self.set_cash(100000)

        underlying_ticker = "GOOG"
        self.add_equity(underlying_ticker)
        option = self.add_option(underlying_ticker)
        self.option_symbol = option.symbol

        self._min_delta = 0.5
        self._max_delta = 1.5
        self._min_gamma = 0.0001
        self._max_gamma = 0.0006
        self._min_vega = 0.01
        self._max_vega = 1.5
        self._min_theta = -2.0
        self._max_theta = -0.5
        self._min_rho = 0.5
        self._max_rho = 3.0
        self._min_iv = 1.0
        self._max_iv = 3.0
        self._min_open_interest = 100
        self._max_open_interest = 500

        option.set_filter(self.main_filter)
        self.option_chain_received = False

    def main_filter(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:
        total_contracts = len(list(universe))

        filtered_universe = self.option_filter(universe)
        filtered_contracts = len(list(filtered_universe))

        if filtered_contracts == total_contracts:
            raise AssertionError(f"Expected filtered universe to have less contracts than original universe. "
                                 f"Filtered contracts count ({filtered_contracts}) is equal to total contracts count ({total_contracts})")

        return filtered_universe

    def option_filter(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:
        # Contracts can be filtered by greeks, implied volatility, open interest:
        return universe \
            .delta(self._min_delta, self._max_delta) \
            .gamma(self._min_gamma, self._max_gamma) \
            .vega(self._min_vega, self._max_vega) \
            .theta(self._min_theta, self._max_theta) \
            .rho(self._min_rho, self._max_rho) \
            .implied_volatility(self._min_iv, self._max_iv) \
            .open_interest(self._min_open_interest, self._max_open_interest)

        # Note: there are also shortcuts for these filter methods:
        '''
        return universe \
            .d(self._min_delta, self._max_delta) \
            .g(self._min_gamma, self._max_gamma) \
            .v(self._min_vega, self._max_vega) \
            .t(self._min_theta, self._max_theta) \
            .r(self._min_rho, self._max_rho) \
            .iv(self._min_iv, self._max_iv) \
            .oi(self._min_open_interest, self._max_open_interest)
        '''

    def on_data(self, slice: Slice) -> None:
        chain = slice.option_chains.get(self.option_symbol)
        if chain and len(chain.contracts) > 0:
            self.option_chain_received = True

    def on_end_of_algorithm(self) -> None:
        if not self.option_chain_received:
            raise AssertionError("Option chain was not received.")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This regression algorithm asserts the consolidated US equity daily bars from the hour bars exactly matches
the daily bars returned from the database

Output:
```python

from AlgorithmImports import *

class ConsolidateHourBarsIntoDailyBarsRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2020, 5, 1)
        self.set_end_date(2020, 6, 5)

        self.spy = self.add_equity("SPY", Resolution.HOUR).symbol

        # We will use these two indicators to compare the daily consolidated bars equals
        # the ones returned from the database. We use this specific type of indicator as
        # it depends on its previous values. Thus, if at some point the bars received by
        # the indicators differ, so will their final values
        self._rsi = RelativeStrengthIndex("First", 15, MovingAverageType.WILDERS)
        self.register_indicator(self.spy, self._rsi, Resolution.DAILY, selector= lambda bar: (bar.close + bar.open) / 2)

        # We won't register this indicator as we will update it manually at the end of the
        # month, so that we can compare the values of the indicator that received consolidated
        # bars and the values of this one
        self._rsi_timedelta = RelativeStrengthIndex("Second", 15, MovingAverageType.WILDERS)
        self._values = {}
        self.count = 0
        self._indicators_compared = False

    def on_data(self, data: Slice):
        if self.is_warming_up:
            return

        if data.contains_key(self.spy) and data[self.spy] != None:
            if self.time.month == self.end_date.month:
                history = self.history[TradeBar](self.spy, self.count, Resolution.DAILY)
                for bar in history:
                    time = bar.end_time.strftime('%Y-%m-%d')
                    average = (bar.close + bar.open) / 2
                    self._rsi_timedelta.update(bar.end_time, average)
                    if self._rsi_timedelta.current.value != self._values[time]:
                        raise AssertionError(f"Both {self._rsi.name} and {self._rsi_timedelta.name} should have the same values, but they differ. {self._rsi.name}: {self._values[time]} | {self._rsi_timedelta.name}: {self._rsi_timedelta.current.value}")
                self._indicators_compared = True
                self.quit()
            else:
                time = self.time.strftime('%Y-%m-%d')
                self._values[time] = self._rsi.current.value

                # Since the symbol resolution is hour and the symbol is equity, we know the last bar received in a day will
                # be at the market close, this is 16h. We need to count how many daily bars were consolidated in order to know
                # how many we need to request from the history
                if self.time.hour == 16:
                    self.count += 1

    def on_end_of_algorithm(self):
        if not self._indicators_compared:
            raise AssertionError(f"Indicators {self._rsi.name} and {self._rsi_timedelta.name} should have been compared, but they were not. Please make sure the indicators are getting SPY data")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm testing the SetHolding trading API precision

Output:
```python

from AlgorithmImports import *

class SetHoldingsRegressionAlgorithm(QCAlgorithm):
    '''Basic template algorithm simply initializes the date range and cash'''

    asynchronous_orders = False

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 8)
        self.add_equity("SPY", Resolution.MINUTE)

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            self.set_holdings("SPY", 0.1, asynchronous=self.asynchronous_orders)
            self.set_holdings("SPY", float(0.20), asynchronous=self.asynchronous_orders)
            self.set_holdings("SPY", np.float64(0.30), asynchronous=self.asynchronous_orders)
            self.set_holdings("SPY", 1, asynchronous=self.asynchronous_orders)

    def on_end_of_algorithm(self):
        for ticket in self.transactions.get_order_tickets():
            if ticket.submit_request.asynchronous != self.asynchronous_orders:
                raise AssertionError("Expected all orders to have the same asynchronous flag as the algorithm.")
```