Instruction: You are a quantive developer 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 structure for structuring an algorithm with indicator and consolidator data for many tickers.

Output:
```python

from AlgorithmImports import *

class MultipleSymbolConsolidationAlgorithm(QCAlgorithm):

    # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
    def initialize(self) -> None:
        # This is the period of bars we'll be creating
        bar_period = TimeSpan.from_minutes(10)
        # This is the period of our sma indicators
        sma_period = 10
        # This is the number of consolidated bars we'll hold in symbol data for reference
        rolling_window_size = 10
        # Holds all of our data keyed by each symbol
        self._data = {}
        # Contains all of our equity symbols
        equity_symbols = ["AAPL","SPY","IBM"]
        # Contains all of our forex symbols
        forex_symbols = ["EURUSD", "USDJPY", "EURGBP", "EURCHF", "USDCAD", "USDCHF", "AUDUSD","NZDUSD"]

        self.set_start_date(2014, 12, 1)
        self.set_end_date(2015, 2, 1)

        # initialize our equity data
        for symbol in equity_symbols:
            equity = self.add_equity(symbol)
            self._data[symbol] = SymbolData(equity.symbol, bar_period, rolling_window_size)

        # initialize our forex data
        for symbol in forex_symbols:
            forex = self.add_forex(symbol)
            self._data[symbol] = SymbolData(forex.symbol, bar_period, rolling_window_size)

        # loop through all our symbols and request data subscriptions and initialize indicator
        for symbol, symbol_data in self._data.items():
            # define the indicator
            symbol_data.sma = SimpleMovingAverage(self.create_indicator_name(symbol, "sma" + str(sma_period), Resolution.MINUTE), sma_period)
            # define a consolidator to consolidate data for this symbol on the requested period

            if symbol_data._symbol.security_type == SecurityType.EQUITY:
                tb_consolidator = TradeBarConsolidator(bar_period)
                tb_consolidator.data_consolidated += self.on_trade_bar_consolidated
                # we need to add this consolidator so it gets auto updates
                self.subscription_manager.add_consolidator(symbol_data._symbol, tb_consolidator)
            else:
                qb_consolidator = QuoteBarConsolidator(bar_period)
                qb_consolidator.data_consolidated += self.on_quote_bar_consolidated
                # we need to add this consolidator so it gets auto updates
                self.subscription_manager.add_consolidator(symbol_data._symbol, qb_consolidator)

    def on_trade_bar_consolidated(self, sender: object, bar: TradeBar) -> None:
        self._on_data_consolidated(sender, bar)

    def on_quote_bar_consolidated(self, sender: object, bar: QuoteBar) -> None:
        self._on_data_consolidated(sender, bar)

    def _on_data_consolidated(self, sender: object, bar: TradeBar | QuoteBar) -> None:
        self._data[bar.symbol.value].sma.update(bar.time, bar.close)
        self._data[bar.symbol.value].bars.add(bar)

    # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
    # Argument "data": Slice object, dictionary object with your stock data
    def on_data(self, data: Slice) -> None:
        # loop through each symbol in our structure
        for symbol in self._data.keys():
            symbol_data = self._data[symbol]
            # this check proves that this symbol was JUST updated prior to this OnData function being called
            if symbol_data.is_ready() and symbol_data.was_just_updated(self.time):
                if not self.portfolio[symbol].invested:
                    self.market_order(symbol, 1)

    # End of a trading day event handler. This method is called at the end of the algorithm day (or multiple times if trading multiple assets).
    # Method is called 10 minutes before closing to allow user to close out position.
    def on_end_of_day(self, symbol: Symbol) -> None:
        i = 0
        for symbol_key in sorted(self._data.keys()):
            symbol_data = self._data[symbol_key]
            # we have too many symbols to plot them all, so plot every other
            i += 1
            if symbol_data.is_ready() and i%2 == 0:
                self.plot(symbol_key, symbol_key, symbol_data.sma.current.value)

class SymbolData(object):

    def __init__(self, symbol: Symbol, bar_period: timedelta, window_size: int) -> None:
        self._symbol = symbol
        # The period used when population the Bars rolling window
        self.bar_period = bar_period
        # A rolling window of data, data needs to be pumped into Bars by using Bars.update( trade_bar ) and can be accessed like:
        # my_symbol_data.bars[0] - most first recent piece of data
        # my_symbol_data.bars[5] - the sixth most recent piece of data (zero based indexing)
        self.bars = RollingWindow(window_size)
        # The simple moving average indicator for our symbol
        self.sma = None

    # Returns true if all the data in this instance is ready (indicators, rolling windows, ect...)
    def is_ready(self) -> bool:
        return self.bars.is_ready and self.sma.is_ready

    # Returns true if the most recent trade bar time matches the current time minus the bar's period, this
    # indicates that update was just called on this instance
    def was_just_updated(self, current: datetime) -> bool:
        return self.bars.count > 0 and self.bars[0].time == current - self.bar_period
```


Instruction: You are a quantive developer 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 to test we can specify a custom settlement model, and override some of its methods

Output:
```python

from AlgorithmImports import *
from CustomBrokerageModelRegressionAlgorithm import CustomBrokerageModel

class CustomSettlementModelRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013,10,7)
        self.set_end_date(2013,10,11)
        self.set_cash(10000)
        self.spy = self.add_equity("SPY", Resolution.DAILY)
        self.set_settlement_model(self.spy)

    def set_settlement_model(self, security):
        self.set_brokerage_model(CustomBrokerageModelWithCustomSettlementModel())

    def on_data(self, slice):
        if self.portfolio.cash_book[Currencies.USD].amount == 10000:
            parameters = ApplyFundsSettlementModelParameters(self.portfolio, self.spy, self.time, CashAmount(101, Currencies.USD), None)
            self.spy.settlement_model.apply_funds(parameters)

    def on_end_of_algorithm(self):
        if self.portfolio.cash_book[Currencies.USD].amount != 10101:
            raise AssertionError(f"It was expected to have 10101 USD in Portfolio, but was {self.portfolio.cash_book[Currencies.USD].amount}")
        parameters = ScanSettlementModelParameters(self.portfolio, self.spy, datetime(2013, 10, 6))
        self.spy.settlement_model.scan(parameters)
        if self.portfolio.cash_book[Currencies.USD].amount != 10000:
            raise AssertionError(f"It was expected to have 10000 USD in Portfolio, but was {self.portfolio.cash_book[Currencies.USD].amount}")

class CustomSettlementModel:
    def apply_funds(self, parameters):
        self.currency = parameters.cash_amount.currency
        self.amount = parameters.cash_amount.amount
        parameters.portfolio.cash_book[self.currency].add_amount(self.amount)

    def scan(self, parameters):
        if parameters.utc_time == datetime(2013, 10, 6):
            parameters.portfolio.cash_book[self.currency].add_amount(-self.amount)

    def get_unsettled_cash(self):
        return None

class CustomBrokerageModelWithCustomSettlementModel(CustomBrokerageModel):
    def get_settlement_model(self, security):
        return CustomSettlementModel()
```


Instruction: You are a quantive developer 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 and ensuring that Bybit crypto brokerage model works as expected

Output:
```python

from AlgorithmImports import *

class BybitCryptoRegressionAlgorithm(QCAlgorithm):

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

        self.set_start_date(2022, 12, 13)
        self.set_end_date(2022, 12, 13)

        # Set account currency (USDT)
        self.set_account_currency("USDT")

        # Set strategy cash (USD)
        self.set_cash(100000)

        # Add some coin as initial holdings
        # When connected to a real brokerage, the amount specified in SetCash
        # will be replaced with the amount in your actual account.
        self.set_cash("BTC", 1)

        self.set_brokerage_model(BrokerageName.BYBIT, AccountType.CASH)

        self.btc_usdt = self.add_crypto("BTCUSDT").symbol

        # create two moving averages
        self.fast = self.ema(self.btc_usdt, 30, Resolution.MINUTE)
        self.slow = self.ema(self.btc_usdt, 60, Resolution.MINUTE)

        self.liquidated = False

    def on_data(self, data):
        if self.portfolio.cash_book["USDT"].conversion_rate == 0 or self.portfolio.cash_book["BTC"].conversion_rate == 0:
            self.log(f"USDT conversion rate: {self.portfolio.cash_book['USDT'].conversion_rate}")
            self.log(f"BTC conversion rate: {self.portfolio.cash_book['BTC'].conversion_rate}")

            raise AssertionError("Conversion rate is 0")

        if not self.slow.is_ready:
            return

        btc_amount = self.portfolio.cash_book["BTC"].amount
        if self.fast > self.slow:
            if btc_amount == 1 and not self.liquidated:
                self.buy(self.btc_usdt, 1)
        else:
            if btc_amount > 1:
                self.liquidate(self.btc_usdt)
                self.liquidated = True
            elif btc_amount > 0 and self.liquidated and len(self.transactions.get_open_orders()) == 0:
                # Place a limit order to sell our initial BTC holdings at 1% above the current price
                limit_price = round(self.securities[self.btc_usdt].price * 1.01, 2)
                self.limit_order(self.btc_usdt, -btc_amount, limit_price)

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

    def on_end_of_algorithm(self):
        self.log(f"{self.time} - TotalPortfolioValue: {self.portfolio.total_portfolio_value}")
        self.log(f"{self.time} - CashBook: {self.portfolio.cash_book}")

        btc_amount = self.portfolio.cash_book["BTC"].amount
        if btc_amount > 0:
            raise AssertionError(f"BTC holdings should be zero at the end of the algorithm, but was {btc_amount}")
```


Instruction: You are a quantive developer 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 implementing VolumeShareSlippageModel.

Output:
```python

from AlgorithmImports import *
from Orders.Slippage.VolumeShareSlippageModel import VolumeShareSlippageModel

class VolumeShareSlippageModelAlgorithm(QCAlgorithm):
    _longs = []
    _shorts = []

    def initialize(self) -> None:
        self.set_start_date(2020, 11, 29)
        self.set_end_date(2020, 12, 2)
        # To set the slippage model to limit to fill only 30% volume of the historical volume, with 5% slippage impact.
        self.set_security_initializer(lambda security: security.set_slippage_model(VolumeShareSlippageModel(0.3, 0.05)))

        self.universe_settings.resolution = Resolution.DAILY
        # Add universe to trade on the most and least weighted stocks among SPY constituents.
        self.add_universe(self.universe.etf("SPY", universe_filter_func=self.selection))

    def selection(self, constituents: list[ETFConstituentUniverse]) -> list[Symbol]:
        sorted_by_weight = sorted(constituents, key=lambda c: c.weight)
        # Add the 10 most weighted stocks to the universe to long later.
        self._longs = [c.symbol for c in sorted_by_weight[-10:]]
        # Add the 10 least weighted stocks to the universe to short later.
        self._shorts = [c.symbol for c in sorted_by_weight[:10]]

        return self._longs + self._shorts

    def on_data(self, slice: Slice) -> None:
        # Equally invest into the selected stocks to evenly dissipate capital risk.
        # Dollar neutral of long and short stocks to eliminate systematic risk, only capitalize the popularity gap.
        targets = [PortfolioTarget(symbol, 0.05) for symbol in self._longs]
        targets += [PortfolioTarget(symbol, -0.05) for symbol in self._shorts]

        # Liquidate the ones not being the most and least popularity stocks to release fund for higher expected return trades.
        self.set_holdings(targets, liquidate_existing_holdings=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
: This regression algorithm tests In The Money (ITM) index option expiry for short calls.
We expect 2 orders from the algorithm, which are:

  * Initial entry, sell SPX Call Option (expiring ITM)
  * Option assignment

Additionally, we test delistings for index options and assert that our
portfolio holdings reflect the orders the algorithm has submitted.

Output:
```python

from AlgorithmImports import *

class IndexOptionShortCallITMExpiryRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2021, 1, 4)
        self.set_end_date(2021, 1, 31)
        self.set_cash(1000000)

        self.portfolio.set_margin_call_model(MarginCallModel.NULL);

        # avoid getting assigned
        self.set_security_initializer(CompositeSecurityInitializer(self.security_initializer, FuncSecurityInitializer(self.custom_security_initializer)))

        self.spx = self.add_index("SPX", Resolution.MINUTE).symbol

        # Select a index option expiring ITM, and adds it to the algorithm.
        self.spx_options = list(self.option_chain(self.spx))
        self.spx_options = [i for i in self.spx_options if i.id.strike_price <= 4200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1]
        self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price, reverse=True))[0]
        self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol

        self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.PUT, 4200, datetime(2021, 1, 15))
        if self.spx_option != self.expected_contract:
            raise AssertionError(f"Contract self.expected_contract was not found in the chain")

        self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1))

    def on_data(self, data: Slice):
        # Assert delistings, so that we can make sure that we receive the delisting warnings at
        # the expected time. These assertions detect bug #4872
        for delisting in data.delistings.values():
            if delisting.type == DelistingType.WARNING:
                if delisting.time != datetime(2021, 1, 15):
                    raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")

            if delisting.type == DelistingType.DELISTED:
                if delisting.time != datetime(2021, 1, 16):
                    raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")

    def on_order_event(self, order_event: OrderEvent):
        if order_event.status != OrderStatus.FILLED:
            # There's lots of noise with OnOrderEvent, but we're only interested in fills.
            return

        if order_event.symbol not in self.securities:
            raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")

        security = self.securities[order_event.symbol]
        if security.symbol == self.spx:
            self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_contract])
        elif security.symbol == self.expected_contract:
            self.assert_index_option_contract_order(order_event, security)
        else:
            raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")

    def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security):
        if "Assignment" in order_event.message:
            if order_event.fill_price != 4200:
                raise AssertionError("Option was not assigned at expected strike price (4200)")

            if order_event.direction != OrderDirection.SELL or index.holdings.quantity != 0:
                raise AssertionError(f"Expected Qty: 0 index holdings for assigned index option {index.symbol}, found {index.holdings.quantity}")

        elif index.holdings.quantity != 0:
            raise AssertionError(f"Expected no holdings in index: {index.symbol}")

    def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):
        if order_event.direction == OrderDirection.SELL and option.holdings.quantity != -1:
            raise AssertionError(f"No holdings were created for option contract {option.symbol}")

        if order_event.is_assignment and option.holdings.quantity != 0:
            raise AssertionError(f"Holdings were found after option contract was assigned: {option.symbol}")

    ### <summary>
    ### Ran at the end of the algorithm to ensure the algorithm has no holdings
    ### </summary>
    ### <exception cref="Exception">The algorithm has holdings</exception>
    def on_end_of_algorithm(self):
        if self.portfolio.invested:
            raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")

    def custom_security_initializer(self, security):
        if Extensions.is_option(security.symbol.security_type):
            security.set_option_assignment_model(NullOptionAssignmentModel())
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Hourly regression algorithm trading ADAUSDT binance futures long and short asserting the behavior

Output:
```python

from AlgorithmImports import *

class BasicTemplateCryptoFutureHourlyAlgorithm(QCAlgorithm):
    # <summary>
    # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
    # </summary>

    def initialize(self):
        self.set_start_date(2022, 12, 13)
        self.set_end_date(2022, 12, 13)

        self.set_time_zone(TimeZones.UTC)

        try:
            self.set_brokerage_model(BrokerageName.BINANCE_COIN_FUTURES, AccountType.CASH)
        except:
            # expected, we don't allow cash account type
            pass

        self.set_brokerage_model(BrokerageName.BINANCE_COIN_FUTURES, AccountType.MARGIN)

        self.ada_usdt = self.add_crypto_future("ADAUSDT", Resolution.HOUR)

        self.fast = self.ema(self.ada_usdt.symbol, 3, Resolution.HOUR)
        self.slow = self.ema(self.ada_usdt.symbol, 6, Resolution.HOUR)

        self.interest_per_symbol = {self.ada_usdt.symbol: 0}

        # Default USD cash, set 1M but it wont be used
        self.set_cash(1000000)

        # the amount of USDT we need to hold to trade 'ADAUSDT'
        self.ada_usdt.quote_currency.set_amount(200)

    # <summary>
    # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
    # </summary>
    # <param name="data">Slice object keyed by symbol containing the stock data</param>
    def on_data(self, slice):
        interest_rates = slice.get(MarginInterestRate);
        for interest_rate in interest_rates:
            self.interest_per_symbol[interest_rate.key] += 1
            self.cached_interest_rate = self.securities[interest_rate.key].cache.get_data(MarginInterestRate)
            if self.cached_interest_rate != interest_rate.value:
                raise AssertionError(f"Unexpected cached margin interest rate for {interest_rate.key}!")

        if self.fast > self.slow:
            if self.portfolio.invested == False and self.transactions.orders_count == 0:
                self.ticket = self.buy(self.ada_usdt.symbol, 100000)
                if self.ticket.status != OrderStatus.INVALID:
                    raise AssertionError(f"Unexpected valid order {self.ticket}, should fail due to margin not sufficient")

                self.buy(self.ada_usdt.symbol, 1000)

                self.margin_used = self.portfolio.total_margin_used

                self.ada_usdt_holdings = self.ada_usdt.holdings

                # USDT/BUSD futures value is based on it's price
                self.holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 1000

                if abs(self.ada_usdt_holdings.total_sale_volume - self.holdings_value_usdt) > 1:
                    raise AssertionError(f"Unexpected TotalSaleVolume {self.ada_usdt_holdings.total_sale_volume}")

                if abs(self.ada_usdt_holdings.absolute_holdings_cost - self.holdings_value_usdt) > 1:
                    raise AssertionError(f"Unexpected holdings cost {self.ada_usdt_holdings.holdings_cost}")

                if (abs(self.ada_usdt_holdings.absolute_holdings_cost * 0.05 - self.margin_used) > 1) or (BuyingPowerModelExtensions.get_maintenance_margin(self.ada_usdt.buying_power_model, self.ada_usdt) != self.margin_used):
                    raise AssertionError(f"Unexpected margin used {self.margin_used}")

                # position just opened should be just spread here
                self.profit = self.portfolio.total_unrealized_profit

                if (5 - abs(self.profit)) < 0:
                    raise AssertionError(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")

                if (self.portfolio.total_profit != 0):
                    raise AssertionError(f"Unexpected TotalProfit {self.portfolio.total_profit}")

        else:
            # let's revert our position and double
            if self.time.hour > 10 and self.transactions.orders_count == 2:
                self.sell(self.ada_usdt.symbol, 3000)

                self.ada_usdt_holdings = self.ada_usdt.holdings

                # USDT/BUSD futures value is based on it's price
                self.holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 2000

                if abs(self.ada_usdt_holdings.absolute_holdings_cost - self.holdings_value_usdt) > 1:
                    raise AssertionError(f"Unexpected holdings cost {self.ada_usdt_holdings.holdings_cost}")

                # position just opened should be just spread here
                self.profit = self.portfolio.total_unrealized_profit
                if (5 - abs(self.profit)) < 0:
                    raise AssertionError(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")

                # we barely did any difference on the previous trade
                if (5 - abs(self.portfolio.total_profit)) < 0:
                    raise AssertionError(f"Unexpected TotalProfit {self.portfolio.total_profit}")

            if self.time.hour >= 22 and self.transactions.orders_count == 3:
                self.liquidate()

    def on_end_of_algorithm(self):
        if self.interest_per_symbol[self.ada_usdt.symbol] != 1:
                raise AssertionError(f"Unexpected interest rate count {self.interest_per_symbol[self.ada_usdt.symbol]}")

    def on_order_event(self, order_event):
        self.debug("{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
: EMA cross with SP500 E-mini futures
In this example, we demostrate how to trade futures contracts using
a equity to generate the trading signals
It also shows how you can prefilter contracts easily based on expirations.
It also shows how you can inspect the futures chain to pick a specific contract to trade.

Output:
```python

from AlgorithmImports import *

class FuturesMomentumAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2016, 1, 1)
        self.set_end_date(2016, 8, 18)
        self.set_cash(100000)
        fast_period = 20
        slow_period = 60
        self._tolerance = 1 + 0.001
        self.is_up_trend = False
        self.is_down_trend = False
        self.set_warm_up(max(fast_period, slow_period))

        # Adds SPY to be used in our EMA indicators
        equity = self.add_equity("SPY", Resolution.DAILY)
        self._fast = self.ema(equity.symbol, fast_period, Resolution.DAILY)
        self._slow = self.ema(equity.symbol, slow_period, Resolution.DAILY)
        # Adds the future that will be traded and
        # set our expiry filter for this futures chain
        future = self.add_future(Futures.Indices.SP_500_E_MINI)
        future.set_filter(timedelta(0), timedelta(182))

    def on_data(self, slice):
        if self._slow.is_ready and self._fast.is_ready:
            self.is_up_trend = self._fast.current.value > self._slow.current.value * self._tolerance
            self.is_down_trend = self._fast.current.value < self._slow.current.value * self._tolerance
            if (not self.portfolio.invested) and self.is_up_trend:
                for chain in slice.futures_chains:
                    # find the front contract expiring no earlier than in 90 days
                    contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))
                    # if there is any contract, trade the front contract
                    if len(contracts) == 0: continue
                    contract = sorted(contracts, key = lambda x: x.expiry, reverse=True)[0]
                    self.market_order(contract.symbol , 1)

            if self.portfolio.invested and self.is_down_trend:
                self.liquidate()

    def on_end_of_day(self, symbol):
        if self.is_up_trend:
            self.plot("Indicator Signal", "EOD",1)
        elif self.is_down_trend:
            self.plot("Indicator Signal", "EOD",-1)
        elif self._slow.is_ready and self._fast.is_ready:
            self.plot("Indicator Signal", "EOD",0)

    def on_order_event(self, order_event):
        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
:  This regression algorithm is expected to stop executing after Initialization. Related to GH 6168 issue

Output:
```python

from AlgorithmImports import *

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

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

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

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

    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
        '''
        raise ValueError("Algorithm should of stopped!")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Tests filtering in coarse selection by shortable quantity

Output:
```python

from AlgorithmImports import *

class AllShortableSymbolsCoarseSelectionRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self._20140325 = datetime(2014, 3, 25)
        self._20140326 = datetime(2014, 3, 26)
        self._20140327 = datetime(2014, 3, 27)
        self._20140328 = datetime(2014, 3, 28)
        self._20140329 = datetime(2014, 3, 29)
        self.last_trade_date = date(1,1,1)

        self._aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
        self._bac = Symbol.create("BAC", SecurityType.EQUITY, Market.USA)
        self._gme = Symbol.create("GME", SecurityType.EQUITY, Market.USA)
        self._goog = Symbol.create("GOOG", SecurityType.EQUITY, Market.USA)
        self._qqq = Symbol.create("QQQ", SecurityType.EQUITY, Market.USA)
        self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)

        self.coarse_selected = { self._20140325: False, self._20140326: False, self._20140327:False, self._20140328:False }
        self.expected_symbols = { self._20140325: [ self._bac, self._qqq, self._spy ],
                                self._20140326: [ self._spy ],
                                self._20140327: [ self._aapl, self._bac, self._gme, self._qqq, self._spy ],
                                self._20140328: [ self._goog ],
                                self._20140329: []}

        self.set_start_date(2014, 3, 25)
        self.set_end_date(2014, 3, 29)
        self.set_cash(10000000)
        self.shortable_provider = RegressionTestShortableProvider()
        self.security = self.add_equity(self._spy)

        self.add_universe(self.coarse_selection)
        self.universe_settings.resolution = Resolution.DAILY

        self.set_brokerage_model(AllShortableSymbolsRegressionAlgorithmBrokerageModel(self.shortable_provider))

    def on_data(self, data):
        if self.time.date() == self.last_trade_date:
            return

        for (symbol, security) in {x.key: x.value for x in sorted(self.active_securities, key = lambda kvp:kvp.key)}.items():
            if security.invested:
                continue
            shortable_quantity = security.shortable_provider.shortable_quantity(symbol, self.time)
            if not shortable_quantity:
                raise AssertionError(f"Expected {symbol} to be shortable on {self.time.strftime('%Y%m%d')}")

            """
            Buy at least once into all Symbols. Since daily data will always use
            MOO orders, it makes the testing of liquidating buying into Symbols difficult.
            """
            self.market_order(symbol, -shortable_quantity)
            self.last_trade_date = self.time.date()

    def coarse_selection(self, coarse):
        shortable_symbols = self.shortable_provider.all_shortable_symbols(self.time)
        selected_symbols = list(sorted(filter(lambda x: (x in shortable_symbols.keys()) and (shortable_symbols[x] >= 500), map(lambda x: x.symbol, coarse)), key= lambda x: x.value))

        expected_missing = 0
        if self.time.date() == self._20140327.date():
            gme = Symbol.create("GME", SecurityType.EQUITY, Market.USA)
            if gme not in shortable_symbols.keys():
                raise AssertionError("Expected unmapped GME in shortable symbols list on 2014-03-27")
            if "GME" not in list(map(lambda x: x.symbol.value, coarse)):
                raise AssertionError("Expected mapped GME in coarse symbols on 2014-03-27")

            expected_missing = 1

        missing = list(filter(lambda x: x not in selected_symbols, self.expected_symbols[self.time]))
        if len(missing) != expected_missing:
            raise AssertionError(f"Expected Symbols selected on {self.time.strftime('%Y%m%d')} to match expected Symbols, but the following Symbols were missing: {', '.join(list(map(lambda x:x.value, missing)))}")

        self.coarse_selected[self.time] = True
        return selected_symbols

    def on_end_of_algorithm(self):
        if not all(x for x in self.coarse_selected.values()):
            raise AssertionError(f"Expected coarse selection on all dates, but didn't run on: {', '.join(list(map(lambda x: x[0].strftime('%Y%m%d'), filter(lambda x:not x[1], self.coarse_selected.items()))))}")

class AllShortableSymbolsRegressionAlgorithmBrokerageModel(DefaultBrokerageModel):
    def __init__(self, shortable_provider):
        self.shortable_provider = shortable_provider
        super().__init__()

    def get_shortable_provider(self, security):
        return self.shortable_provider

class RegressionTestShortableProvider(LocalDiskShortableProvider):
    def __init__(self):
        super().__init__("testbrokerage")

    """
    Gets a list of all shortable Symbols, including the quantity shortable as a Dictionary.
    """
    def all_shortable_symbols(self, localtime):
        shortable_data_directory = os.path.join(Globals.data_folder, "equity", Market.USA, "shortable", self.brokerage)
        all_symbols = {}

        """
        Check backwards up to one week to see if we can source a previous file.
        If not, then we return a list of all Symbols with quantity set to zero.
        """
        i = 0
        while i <= 7:
            shortable_list_file = os.path.join(shortable_data_directory, "dates", f"{(localtime - timedelta(days=i)).strftime('%Y%m%d')}.csv")

            for line in Extensions.read_lines(self.data_provider, shortable_list_file):
                csv = line.split(',')
                ticker = csv[0]

                symbol = Symbol(SecurityIdentifier.generate_equity(ticker, Market.USA, mapping_resolve_date = localtime), ticker)
                quantity = int(csv[1])
                all_symbols[symbol] = quantity

            if len(all_symbols) > 0:
                return all_symbols

            i += 1

        # Return our empty dictionary if we did not find a file to extract
        return all_symbols
```


Instruction: You are a quantive developer 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 parameter system of QuantConnect. Using parameters you can pass the values required into C# algorithms for optimization.

Output:
```python

from AlgorithmImports import *

class ParameterizedAlgorithm(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")

        # Receive parameters from the Job
        fast_period = self.get_parameter("ema-fast", 100)
        slow_period = self.get_parameter("ema-slow", 200)

        self.fast = self.ema("SPY", fast_period)
        self.slow = self.ema("SPY", slow_period)

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

        # wait for our indicators to ready
        if not self.fast.is_ready or not self.slow.is_ready:
            return

        fast = self.fast.current.value
        slow = self.slow.current.value

        if fast > slow * 1.001:
            self.set_holdings("SPY", 1)
        elif fast < slow * 0.999:
            self.liquidate("SPY")
```


Instruction: You are a quantive developer 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 the behavior of a ScheduledUniverse

Output:
```python

from AlgorithmImports import *

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

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

        self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
        self._selection_time =[ datetime(2013, 10, 7, 1, 0, 0), datetime(2013, 10, 8, 1, 0, 0)]

        self.add_universe(ScheduledUniverse(self.date_rules.every_day(), self.time_rules.at(1, 0), self.select_assets))

    def select_assets(self, time):
        self.debug(f"Universe selection called: {Time}")
        expected_time = self._selection_time.pop(0)
        if expected_time != self.time:
            raise ValueError(f"Unexpected selection time {self.time} expected {expected_time}")

        return [ self._spy ]

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

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            self.set_holdings(self._spy, 1)

    def on_end_of_algorithm(self):
        if len(self._selection_time) > 0:
            raise ValueError("Unexpected selection times")
```


Instruction: You are a quantive developer 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 get access to futures history for a given root symbol.
It also shows how you can prefilter contracts easily based on expirations, and inspect the futures
chain to pick a specific contract to trade.

Output:
```python

from AlgorithmImports import *

class BasicTemplateFuturesHistoryAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2013, 10, 8)
        self.set_end_date(2013, 10, 9)
        self.set_cash(1000000)

        extended_market_hours = self.get_extended_market_hours()

        # Subscribe and set our expiry filter for the futures chain
        # find the front contract expiring no earlier than in 90 days
        future_es = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, extended_market_hours=extended_market_hours)
        future_es.set_filter(timedelta(0), timedelta(182))

        future_gc = self.add_future(Futures.Metals.GOLD, Resolution.MINUTE, extended_market_hours=extended_market_hours)
        future_gc.set_filter(timedelta(0), timedelta(182))

        self.set_benchmark(lambda x: 1000000)

        self.schedule.on(self.date_rules.every_day(), self.time_rules.every(timedelta(hours=1)), self.make_history_call)
        self._success_count = 0

    def make_history_call(self):
        history = self.history(self.securities.keys(), 10, Resolution.MINUTE)
        if len(history) < 10:
            raise AssertionError(f'Empty history at {self.time}')
        self._success_count += 1

    def on_end_of_algorithm(self):
        if self._success_count < self.get_expected_history_call_count():
            raise AssertionError(f'Scheduled Event did not assert history call as many times as expected: {self._success_count}/49')

    def on_data(self,slice):
        if self.portfolio.invested: return
        for chain in slice.future_chains:
            for contract in chain.value:
                self.log(f'{contract.symbol.value},' +
                         f'Bid={contract.bid_price} ' +
                         f'Ask={contract.ask_price} ' +
                         f'Last={contract.last_price} ' +
                         f'OI={contract.open_interest}')

    def on_securities_changed(self, changes):
        for change in changes.added_securities:
            history = self.history(change.symbol, 10, Resolution.MINUTE).sort_index(level='time', ascending=False)[:3]

            for index, row in history.iterrows():
                self.log(f'History: {index[1]} : {index[2]:%m/%d/%Y %I:%M:%S %p} > {row.close}')

    def on_order_event(self, order_event):
        # Order fill event handler. On an order fill update the resulting information is passed to this method.
        # Order event details containing details of the events
        self.log(f'{order_event}')

    def get_extended_market_hours(self):
        return False

    def get_expected_history_call_count(self):
        return 42
```


Instruction: You are a quantive developer 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.FuturesChains(IEnumerable{Symbol}, bool)"/>
method to get multiple futures chains.

Output:
```python

from AlgorithmImports import *

class FuturesChainsMultipleFullDataRegressionAlgorithm(QCAlgorithm):

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

        es_future = self.add_future(Futures.Indices.SP_500_E_MINI).symbol
        gc_future = self.add_future(Futures.Metals.GOLD).symbol

        chains = self.futures_chains([es_future, gc_future], flatten=True)

        self._es_contract = self.get_contract(chains, es_future)
        self._gc_contract = self.get_contract(chains, gc_future)

        self.add_future_contract(self._es_contract)
        self.add_future_contract(self._gc_contract)

    def get_contract(self, chains: FuturesChains, canonical: Symbol) -> Symbol:
        df = chains.data_frame

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

        # Get contracts expiring within 6 months, with the latest expiration date, and lowest price
        contracts = contracts.loc[(df.expiry <= self.time + timedelta(days=180))]
        contracts = contracts.sort_values(['expiry', 'lastprice'], ascending=[False, True])

        return contracts.index[0][1]

    def on_data(self, data):
        # Do some trading with the selected contract for sample purposes
        if not self.portfolio.invested:
            self.set_holdings(self._es_contract, 0.25)
            self.set_holdings(self._gc_contract, 0.25)
        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
: Futures framework algorithm that uses open interest to select the active contract.

Output:
```python

from AlgorithmImports import *

class OpenInterestFuturesRegressionAlgorithm(QCAlgorithm):

    expected_expiry_dates = {datetime(2013, 12, 27), datetime(2014,2,26)}

    def initialize(self):
        self.universe_settings.resolution = Resolution.TICK
        self.set_start_date(2013,10,8)
        self.set_end_date(2013,10,11)
        self.set_cash(10000000)

        # set framework models
        universe = OpenInterestFutureUniverseSelectionModel(self, lambda date_time: [Symbol.create(Futures.Metals.GOLD, SecurityType.FUTURE, Market.COMEX)], None, len(self.expected_expiry_dates))
        self.set_universe_selection(universe)

    def on_data(self,data):
        if self.transactions.orders_count == 0 and data.has_data:
            matched = list(filter(lambda s: not (s.id.date in self.expected_expiry_dates) and not s.is_canonical(), data.keys()))
            if len(matched) != 0:
                raise AssertionError(f"{len(matched)}/{len(data.keys())} were unexpected expiry date(s): " + ", ".join(list(map(lambda x: x.id.date, matched))))

            for symbol in data.keys():
                self.market_order(symbol, 1)
        elif any(p.value.invested for p in self.portfolio):
            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
: This regression algorithm tests Out of The Money (OTM) future option expiry for calls.
We expect 2 orders from the algorithm, which are:

  * Initial entry, buy ES Call Option (expiring OTM)
    - contract expires worthless, not exercised, so never opened a position in the underlying

  * Liquidation of worthless ES call option (expiring OTM)

Additionally, we test delistings for future options and assert that our
portfolio holdings reflect the orders the algorithm has submitted.

Output:
```python

from AlgorithmImports import *

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

        self.es19m20 = self.add_future_contract(
            Symbol.create_future(
                Futures.Indices.SP_500_E_MINI,
                Market.CME,
                datetime(2020, 6, 19)),
            Resolution.MINUTE).symbol

        # Select a future option expiring ITM, and adds it to the algorithm.
        self.es_option = self.add_future_option_contract(
            list(
                sorted(
                    [x for x in self.option_chain(self.es19m20)
                     if x.id.strike_price >= 3300.0 and x.id.option_right == OptionRight.CALL],
                    key=lambda x: x.id.strike_price
                )
            )[0], Resolution.MINUTE).symbol

        self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3300.0, datetime(2020, 6, 19))
        if self.es_option != self.expected_contract:
            raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")

        # Place order after regular market opens
        self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)

    def scheduled_market_order(self):
        self.market_order(self.es_option, 1)

    def on_data(self, data: Slice):
        # Assert delistings, so that we can make sure that we receive the delisting warnings at
        # the expected time. These assertions detect bug #4872
        for delisting in data.delistings.values():
            if delisting.type == DelistingType.WARNING:
                if delisting.time != datetime(2020, 6, 19):
                    raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")

            if delisting.type == DelistingType.DELISTED:
                if delisting.time != datetime(2020, 6, 20):
                    raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")

    def on_order_event(self, order_event: OrderEvent):
        if order_event.status != OrderStatus.FILLED:
            # There's lots of noise with OnOrderEvent, but we're only interested in fills.
            return

        if not self.securities.contains_key(order_event.symbol):
            raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")

        security = self.securities[order_event.symbol]
        if security.symbol == self.es19m20:
            raise AssertionError("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM")

        # Expected contract is ES19M20 Call Option expiring OTM @ 3300
        if (security.symbol == self.expected_contract):
            self.assert_future_option_contract_order(order_event, security)
        else:
            raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")

        self.log(f"{order_event}")

    def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):
        if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
            raise AssertionError(f"No holdings were created for option contract {option.symbol}")

        if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
            raise AssertionError("Holdings were found after a filled option exercise")

        if order_event.direction == OrderDirection.SELL and "OTM" not in order_event.message:
            raise AssertionError("Contract did not expire OTM")

        if "Exercise" in order_event.message:
            raise AssertionError("Exercised option, even though it expires OTM")

    def on_end_of_algorithm(self):
        if self.portfolio.invested:
            raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
```


Instruction: You are a quantive developer 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 we can specify a custom Shortable Provider

Output:
```python

from AlgorithmImports import *

class CustomShortableProviderRegressionAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_cash(10000000)
        self.set_start_date(2013,10,4)
        self.set_end_date(2013,10,6)
        self._spy = self.add_security(SecurityType.EQUITY, "SPY", Resolution.DAILY)
        self._spy.set_shortable_provider(CustomShortableProvider())

    def on_data(self, data: Slice) -> None:
        spy_shortable_quantity = self._spy.shortable_provider.shortable_quantity(self._spy.symbol, self.time)
        if spy_shortable_quantity and spy_shortable_quantity > 1000:
            self._order_id = self.sell("SPY", int(spy_shortable_quantity)).order_id

    def on_end_of_algorithm(self) -> None:
        transactions = self.transactions.orders_count
        if transactions != 1:
            raise AssertionError("Algorithm should have just 1 order, but was " + str(transactions))

        order_quantity = self.transactions.get_order_by_id(self._order_id).quantity
        if order_quantity != -1001:
            raise AssertionError(f"Quantity of order {self._order_id} should be -1001 but was {order_quantity}")

        fee_rate = self._spy.shortable_provider.fee_rate(self._spy.symbol, self.time)
        if fee_rate != 0.0025:
            raise AssertionError(f"Fee rate should be 0.0025, but was {fee_rate}")
        rebate_rate = self._spy.shortable_provider.rebate_rate(self._spy.symbol, self.time)
        if rebate_rate != 0.0507:
            raise AssertionError(f"Rebate rate should be 0.0507, but was {rebate_rate}")

class CustomShortableProvider(NullShortableProvider):
    def fee_rate(self, symbol: Symbol, local_time: datetime) -> float:
        return 0.0025
    def rebate_rate(self, symbol: Symbol, local_time: datetime) -> float:
        return 0.0507
    def shortable_quantity(self, symbol: Symbol, local_time: datetime) -> int:
        if local_time < datetime(2013,10,4,16,0,0):
            return 10
        return 1001
```


Instruction: You are a quantive developer 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 history requests for <see cref="OptionUniverse"/> type work as expected
and return the same data as the option chain provider.

Output:
```python

from AlgorithmImports import *

class OptionUniverseHistoryRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2015, 12, 25)
        self.set_end_date(2015, 12, 25)

        option = self.add_option("GOOG").symbol

        historical_options_data_df = self.history(option, 3, flatten=True)

        # Level 0 of the multi-index is the date, we expect 3 dates, 3 option chains
        if historical_options_data_df.index.levshape[0] != 3:
            raise AssertionError(f"Expected 3 option chains from history request, but got {historical_options_data_df.index.levshape[1]}")

        for date in historical_options_data_df.index.levels[0]:
            expected_chain = list(self.option_chain_provider.get_option_contract_list(option, date))
            expected_chain_count = len(expected_chain)

            actual_chain = historical_options_data_df.loc[date]
            actual_chain_count = len(actual_chain)

            if expected_chain_count != actual_chain_count:
                raise AssertionError(f"Expected {expected_chain_count} options in chain on {date}, but got {actual_chain_count}")

            for i, symbol in enumerate(actual_chain.index):
                expected_symbol = expected_chain[i]
                if symbol != expected_symbol:
                    raise AssertionError(f"Expected symbol {expected_symbol} at index {i} on {date}, but got {symbol}")
```


Instruction: You are a quantive developer 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 template framework algorithm uses framework components to define the algorithm.

Output:
```python

from AlgorithmImports import *

class BasicTemplateFrameworkAlgorithm(QCAlgorithm):
    '''Basic template framework algorithm uses framework components to define the algorithm.'''

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

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

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

        # Find more symbols here: http://quantconnect.com/data
        # Forex, CFD, Equities Resolutions: Tick, Second, Minute, Hour, Daily.
        # Futures Resolution: Tick, Second, Minute
        # Options Resolution: Minute Only.
        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))

        # We can define how often the EWPCM will rebalance if no new insight is submitted using:
        # Resolution Enum:
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY))
        # timedelta
        # self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(timedelta(2)))
        # A lamdda datetime -> datetime. In this case, we can use the pre-defined func at Expiry helper class
        # self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Expiry.END_OF_WEEK))

        self.set_execution(ImmediateExecutionModel())
        self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))

        self.debug("numpy test >>> print numpy.pi: " + str(np.pi))

    def on_order_event(self, order_event):
        if order_event.status == OrderStatus.FILLED:
            self.debug("Purchased Stock: {0}".format(order_event.symbol))
```


Instruction: You are a quantive developer 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 to test universe additions and removals with open positions

Output:
```python

from AlgorithmImports import *

class InceptionDateSelectionRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2013,10,1)
        self.set_end_date(2013,10,31)
        self.set_cash(100000)

        self.changes = None
        self.universe_settings.resolution = Resolution.HOUR

        # select IBM once a week, empty universe the other days
        self.add_universe_selection(CustomUniverseSelectionModel("my-custom-universe", lambda dt: ["IBM"] if dt.day % 7 == 0 else []))
        # Adds SPY 5 days after StartDate and keep it in Universe
        self.add_universe_selection(InceptionDateUniverseSelectionModel("spy-inception", {"SPY": self.start_date + timedelta(5)}))

    def on_data(self, slice):
        if self.changes is None:
           return

        # we'll simply go long each security we added to the universe
        for security in self.changes.added_securities:
            self.set_holdings(security.symbol, .5)

        self.changes = None

    def on_securities_changed(self, changes):
        # liquidate removed securities
        for security in changes.removed_securities:
            self.liquidate(security.symbol, "Removed from Universe")

        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
: Demonstration of the Market On Close order for US Equities.

Output:
```python

from AlgorithmImports import *

class MarketOnOpenOnCloseAlgorithm(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.equity = self.add_equity("SPY", Resolution.SECOND, fill_forward = True, extended_market_hours = True)
        self.__submitted_market_on_close_today = False
        self.__last = datetime.min

    def on_data(self, data):
        '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        if self.time.date() != self.__last.date():   # each morning submit a market on open order
            self.__submitted_market_on_close_today = False
            self.market_on_open_order("SPY", 100)
            self.__last = self.time

        if not self.__submitted_market_on_close_today and self.equity.exchange.exchange_open:   # once the exchange opens submit a market on close order
            self.__submitted_market_on_close_today = True
            self.market_on_close_order("SPY", -100)

    def on_order_event(self, fill):
        order = self.transactions.get_order_by_id(fill.order_id)
        self.log("{0} - {1}:: {2}".format(self.time, order.type, 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
: Regression algorithm illustrating the usage of the <see cref="QCAlgorithm.OptionChain(Symbol)"/> method
to get an option chain, 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 OptionChainFullDataRegressionAlgorithm(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

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

        # Demonstration using data frame:
        df = option_chain.data_frame
        # Get contracts expiring within 10 days, with an implied volatility greater than 0.5 and a delta less than 0.5
        contracts = df.loc[(df.expiry <= self.time + timedelta(days=10)) & (df.impliedvolatility > 0.5) & (df.delta < 0.5)]

        # Get the contract with the latest expiration date.
        # Note: the result of df.loc[] is a series, and its name is a tuple with a single element (contract symbol)
        self._option_contract = contracts.loc[contracts.expiry.idxmax()].name

        self.add_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.market_order(self._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
: This regression test is a version of "MarketOnCloseOrderBufferRegressionAlgorithm"

Output:
```python

from AlgorithmImports import *

class MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm(QCAlgorithm):
    '''This regression test is a version of "MarketOnCloseOrderBufferRegressionAlgorithm"
     where we test market-on-close modeling with data from the post market.'''
    _valid_order_ticket = None
    _invalid_order_ticket = None
    _valid_order_ticket_extended_market_hours = None

    def initialize(self) -> None:
        self.set_start_date(2013,10,7)   #Set Start Date
        self.set_end_date(2013,10,8)    #Set End Date

        self.add_equity("SPY", Resolution.MINUTE, extended_market_hours = True)

        def moc_at_mid_night():
            self._valid_order_ticket_at_midnight = self.market_on_close_order("SPY", 2)

        self.schedule.on(self.date_rules.tomorrow, self.time_rules.midnight, moc_at_mid_night)

        # Modify our submission buffer time to 10 minutes
        MarketOnCloseOrder.submission_time_buffer = timedelta(minutes=10)

    def on_data(self, data: Slice) -> None:
        # Test our ability to submit MarketOnCloseOrders
        # Because we set our buffer to 10 minutes, any order placed
        # before 3:50PM should be accepted, any after marked invalid

        # Will not throw an order error and execute
        if self.time.hour == 15 and self.time.minute == 49 and not self._valid_order_ticket:
            self._valid_order_ticket = self.market_on_close_order("SPY", 2)

        # Will throw an order error and be marked invalid
        if self.time.hour == 15 and self.time.minute == 51 and not self._invalid_order_ticket:
            self._invalid_order_ticket = self.market_on_close_order("SPY", 2)

        # Will not throw an order error and execute
        if self.time.hour == 16 and self.time.minute == 48 and not self._valid_order_ticket_extended_market_hours:
            self._valid_order_ticket_extended_market_hours = self.market_on_close_order("SPY", 2)

    def on_end_of_algorithm(self) -> None:
        # Set it back to default for other regressions
        MarketOnCloseOrder.submission_time_buffer = MarketOnCloseOrder.DEFAULT_SUBMISSION_TIME_BUFFER

        if self._valid_order_ticket.status != OrderStatus.FILLED:
            raise AssertionError("Valid order failed to fill")

        if self._invalid_order_ticket.status != OrderStatus.INVALID:
            raise AssertionError("Invalid order was not rejected")

        if self._valid_order_ticket_extended_market_hours.status != OrderStatus.FILLED:
            raise AssertionError("Valid order during extended market hours failed to 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
: Regression algorithm testing history requests for <see cref="FutureUniverse"/> type work as expected
and return the same data as the futures chain provider.

Output:
```python

from AlgorithmImports import *

class OptionUniverseHistoryRegressionAlgorithm(QCAlgorithm):

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

        future = self.add_future(Futures.Indices.SP_500_E_MINI).symbol

        historical_futures_data_df = self.history(FutureUniverse, future, 3, flatten=True)

        # Level 0 of the multi-index is the date, we expect 3 dates, 3 future chains
        if historical_futures_data_df.index.levshape[0] != 3:
            raise RegressionTestException(f"Expected 3 futures chains from history request, "
                                          f"but got {historical_futures_data_df.index.levshape[1]}")

        for date in historical_futures_data_df.index.levels[0]:
            expected_chain = list(self.future_chain_provider.get_future_contract_list(future, date))
            expected_chain_count = len(expected_chain)

            actual_chain = historical_futures_data_df.loc[date]
            actual_chain_count = len(actual_chain)

            if expected_chain_count != actual_chain_count:
                raise RegressionTestException(f"Expected {expected_chain_count} futures in chain on {date}, "
                                              f"but got {actual_chain_count}")

            for i, symbol in enumerate(actual_chain.index):
                expected_symbol = expected_chain[i]
                if symbol != expected_symbol:
                    raise RegressionTestException(f"Expected symbol {expected_symbol} at index "
                                                  f" {i} on {date}, but got {symbol}")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: def initialize(self) -> None:

Output:
```python

from AlgorithmImports import *

# <summary>
# Regression algorithm to test the behaviour of ARMA versus AR models at the same order of differencing.
# In particular, an ARIMA(1,1,1) and ARIMA(1,1,0) are instantiated while orders are placed if their difference
# is sufficiently large (which would be due to the inclusion of the MA(1) term).
# </summary>
class AutoRegressiveIntegratedMovingAverageRegressionAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
        self.set_start_date(2013, 1, 7)
        self.set_end_date(2013, 12, 11)
        self.settings.automatic_indicator_warm_up = True
        self.add_equity("SPY", Resolution.DAILY)
        self._arima = self.arima("SPY", 1, 1, 1, 50)
        self._ar = self.arima("SPY", 1, 1, 0, 50)
        self._last = None

    def on_data(self, data: Slice) -> None:
        '''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._arima.is_ready:
            if abs(self._arima.current.value - self._ar.current.value) > 1:
                if self._arima.current.value > self._last:
                    self.market_order("SPY", 1)
                else:
                    self.market_order("SPY", -1)
            self._last = self._arima.current.value
```


Instruction: You are a quantive developer 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 show how you can easily use the universe selection feature to fetch symbols
to be traded using the BaseData custom data system in combination with the AddUniverse{T} method.
AddUniverse{T} requires a function that will return the symbols to be traded.

Output:
```python

from AlgorithmImports import *

class DropboxBaseDataUniverseSelectionAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.universe_settings.resolution = Resolution.DAILY

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

        self.set_start_date(2017, 7, 6)
        self.set_end_date(2018, 7, 4)

        universe = self.add_universe(StockDataSource, self.stock_data_source)

        historical_selection_data = self.history(universe, 3)
        if len(historical_selection_data) != 3:
            raise ValueError(f"Unexpected universe data count {len(historical_selection_data)}")

        for universe_data in historical_selection_data["symbols"]:
            if len(universe_data) != 5:
                raise ValueError(f"Unexpected universe data receieved")

        self._changes = None

    def stock_data_source(self, data: list[DynamicData]) -> list[Symbol]:
        list = []
        for item in data:
            for symbol in item["Symbols"]:
                list.append(symbol)
        return list

    def on_data(self, slice: Slice) -> None:
        if slice.bars.count == 0:
           return
        if not self._changes:
           return

        # start fresh
        self.liquidate()

        percentage = 1 / slice.bars.count
        for trade_bar in slice.bars.values():
            self.set_holdings(trade_bar.symbol, percentage)

        # reset changes
        self._changes = None

    def on_securities_changed(self, changes: SecurityChanges) -> None:
        self._changes = changes

class StockDataSource(PythonData):

    def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:
        url = "https://www.dropbox.com/s/2l73mu97gcehmh7/daily-stock-picker-live.csv?dl=1" if is_live_mode else \
            "https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1"
        return SubscriptionDataSource(url, SubscriptionTransportMedium.REMOTE_FILE)

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

        stocks = StockDataSource()
        stocks.symbol = config.symbol

        csv = line.split(',')
        if is_live_mode:
            stocks.time = date
            stocks["Symbols"] = csv
        else:
            stocks.time = datetime.strptime(csv[0], "%Y%m%d")
            stocks["Symbols"] = csv[1:]
        return stocks
```


Instruction: You are a quantive developer 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 checks that adding data via AddData
works as expected

Output:
```python

from AlgorithmImports import *
from QuantConnect.Data.Custom.IconicTypes import *

class CustomDataIconicTypesAddDataRegressionAlgorithm(QCAlgorithm):

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

        twx_equity = self.add_equity("TWX", Resolution.DAILY).symbol
        custom_twx_symbol = self.add_data(LinkedData, twx_equity, Resolution.DAILY).symbol

        self.googl_equity = self.add_equity("GOOGL", Resolution.DAILY).symbol
        custom_googl_symbol = self.add_data(LinkedData, "GOOGL", Resolution.DAILY).symbol

        unlinked_data_symbol = self.add_data(UnlinkedData, "GOOGL", Resolution.DAILY).symbol
        unlinked_data_symbol_underlying_equity = Symbol.create("MSFT", SecurityType.EQUITY, Market.USA)
        unlinked_data_symbol_underlying = self.add_data(UnlinkedData, unlinked_data_symbol_underlying_equity, Resolution.DAILY).symbol

        option_symbol = self.add_option("TWX", Resolution.MINUTE).symbol
        custom_option_symbol = self.add_data(LinkedData, option_symbol, Resolution.DAILY).symbol

        if custom_twx_symbol.underlying != twx_equity:
            raise AssertionError(f"Underlying symbol for {custom_twx_symbol} is not equal to TWX equity. Expected {twx_equity} got {custom_twx_symbol.underlying}")
        if custom_googl_symbol.underlying != self.googl_equity:
            raise AssertionError(f"Underlying symbol for {custom_googl_symbol} is not equal to GOOGL equity. Expected {self.googl_equity} got {custom_googl_symbol.underlying}")
        if unlinked_data_symbol.has_underlying:
            raise AssertionError(f"Unlinked data type (no underlying) has underlying when it shouldn't. Found {unlinked_data_symbol.underlying}")
        if not unlinked_data_symbol_underlying.has_underlying:
            raise AssertionError("Unlinked data type (with underlying) has no underlying Symbol even though we added with Symbol")
        if unlinked_data_symbol_underlying.underlying != unlinked_data_symbol_underlying_equity:
            raise AssertionError(f"Unlinked data type underlying does not equal equity Symbol added. Expected {unlinked_data_symbol_underlying_equity} got {unlinked_data_symbol_underlying.underlying}")
        if custom_option_symbol.underlying != option_symbol:
            raise AssertionError(f"Option symbol not equal to custom underlying symbol. Expected {option_symbol} got {custom_option_symbol.underlying}")

        try:
            custom_data_no_cache = self.add_data(LinkedData, "AAPL", Resolution.DAILY)
            raise AssertionError("AAPL was found in the SymbolCache, though it should be missing")
        except InvalidOperationException as e:
            return

    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 and len(self.transactions.get_open_orders()) == 0:
            self.set_holdings(self.googl_equity, 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
: Using rolling windows for efficient storage of historical data; which automatically clears after a period of time.

Output:
```python

from AlgorithmImports import *

class RollingWindowAlgorithm(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,1)  #Set Start Date
        self.set_end_date(2013,11,1)    #Set End Date
        self.set_cash(100000)           #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.add_equity("SPY", Resolution.DAILY)

        # Creates a Rolling Window indicator to keep the 2 TradeBar
        self._window = RollingWindow(2)    # For other security types, use QuoteBar

        # Creates an indicator and adds to a rolling window when it is updated
        self._sma = self.sma("SPY", 5)
        self._sma.updated += self._sma_updated
        self._sma_win = RollingWindow(5)

    def _sma_updated(self, sender, updated):
        '''Adds updated values to rolling window'''
        self._sma_win.add(updated)

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

        # Add SPY TradeBar in rollling window
        self._window.add(data["SPY"])

        # Wait for windows to be ready.
        if not (self._window.is_ready and self._sma_win.is_ready): return

        curr_bar = self._window[0]                        # Current bar had index zero.
        past_bar = self._window[1]                        # Past bar has index one.
        self.log(f"Price: {past_bar.time} -> {past_bar.close} ... {curr_bar.time} -> {curr_bar.close}")

        curr_sma = self._sma_win[0]                       # Current SMA had index zero.
        past_sma = self._sma_win[self._sma_win.count-1]   # Oldest SMA has index of window count minus 1.
        self.log(f"SMA:   {past_sma.time} -> {past_sma.value} ... {curr_sma.time} -> {curr_sma.value}")

        if not self.portfolio.invested and curr_sma.value > past_sma.value:
            self.set_holdings("SPY", 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
: This example demonstrates how to implement a cross moving average for the futures front contract

Output:
```python

from AlgorithmImports import *

class EmaCrossFuturesFrontMonthAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2013, 10, 8)
        self.set_end_date(2013, 10, 10)
        self.set_cash(1000000)

        future = self.add_future(Futures.Metals.GOLD)

        # Only consider the front month contract
        # Update the universe once per day to improve performance
        future.set_filter(lambda x: x.front_month().only_apply_filter_at_market_open())

        # Symbol of the current contract
        self._symbol = None

        # Create two exponential moving averages
        self.fast = ExponentialMovingAverage(100)
        self.slow = ExponentialMovingAverage(300)
        self.tolerance = 0.001
        self.consolidator = None

        # Add a custom chart to track the EMA cross
        chart = Chart('EMA Cross')
        chart.add_series(Series('Fast', SeriesType.LINE, 0))
        chart.add_series(Series('Slow', SeriesType.LINE, 0))
        self.add_chart(chart)

    def on_data(self,slice):

        holding = None if self._symbol is None else self.portfolio.get(self._symbol)
        if holding is not None:
            # Buy the futures' front contract when the fast EMA is above the slow one
            if self.fast.current.value > self.slow.current.value * (1 + self.tolerance):
                if not holding.invested:
                    self.set_holdings(self._symbol, .1)
                    self.plot_ema()
            elif holding.invested:
                self.liquidate(self._symbol)
                self.plot_ema()

    def on_securities_changed(self, changes):
        if len(changes.removed_securities) > 0:
            # Remove the consolidator for the previous contract
            # and reset the indicators
            if self._symbol is not None and self.consolidator is not None:
                self.subscription_manager.remove_consolidator(self._symbol, self.consolidator)
                self.fast.reset()
                self.slow.reset()
            # We don't need to call Liquidate(_symbol),
            # since its positions are liquidated because the contract has expired.

        # Only one security will be added: the new front contract
        self._symbol = changes.added_securities[0].symbol

        # Create a new consolidator and register the indicators to it
        self.consolidator = self.resolve_consolidator(self._symbol, Resolution.MINUTE)
        self.register_indicator(self._symbol, self.fast, self.consolidator)
        self.register_indicator(self._symbol, self.slow, self.consolidator)

        #  Warm up the indicators
        self.warm_up_indicator(self._symbol, self.fast, Resolution.MINUTE)
        self.warm_up_indicator(self._symbol, self.slow, Resolution.MINUTE)

        self.plot_ema()

    def plot_ema(self):
        self.plot('EMA Cross', 'Fast', self.fast.current.value)
        self.plot('EMA Cross', 'Slow', self.slow.current.value)
```


Instruction: You are a quantive developer 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 CFD assets.

Output:
```python

from AlgorithmImports import *

class BasicTemplateCfdAlgorithm(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_account_currency('EUR')

        self.set_start_date(2019, 2, 20)
        self.set_end_date(2019, 2, 21)
        self.set_cash('EUR', 100000)

        self._symbol = self.add_cfd('DE30EUR').symbol

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

    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:
            slice: Slice object keyed by symbol containing the stock data
        '''
        # Access Data
        if data.quote_bars.contains_key(self._symbol):
            quote_bar = data.quote_bars[self._symbol]
            self.log(f"{quote_bar.end_time} :: {quote_bar.close}")

        if not self.portfolio.invested:
            self.set_holdings(self._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 algorithm tests and demonstrates EUREX futures subscription and trading:
- It tests contracts rollover by adding a continuous future and asserting that mapping happens at some point.
- It tests basic trading by buying a contract and holding it until expiration.
- It tests delisting and asserts the holdings are liquidated after that.

Output:
```python

from AlgorithmImports import *

class BasicTemplateEurexFuturesAlgorithm(QCAlgorithm):
    def __init__(self):
        super().__init__()
        self._continuous_contract = None
        self._mapped_symbol = None
        self._contract_to_trade = None
        self._mappings_count = 0
        self._bought_quantity = 0
        self._liquidated_quantity = 0
        self._delisted = False

    def initialize(self):
        self.set_start_date(2024, 5, 30)
        self.set_end_date(2024, 6, 23)

        self.set_account_currency(Currencies.EUR);
        self.set_cash(1000000)

        self._continuous_contract = self.add_future(
            Futures.Indices.EURO_STOXX_50,
            Resolution.MINUTE,
            data_normalization_mode=DataNormalizationMode.BACKWARDS_RATIO,
            data_mapping_mode=DataMappingMode.FIRST_DAY_MONTH,
            contract_depth_offset=0,
        )
        self._continuous_contract.set_filter(timedelta(days=0), timedelta(days=180))
        self._mapped_symbol = self._continuous_contract.mapped

        benchmark = self.add_index("SX5E")
        self.set_benchmark(benchmark.symbol)

        func_seeder = FuncSecuritySeeder(self.get_last_known_prices)
        self.set_security_initializer(lambda security: func_seeder.seed_security(security))

    def on_data(self, slice):
        for changed_event in slice.symbol_changed_events.values():
            self._mappings_count += 1
            if self._mappings_count > 1:
                raise AssertionError(f"{self.time} - Unexpected number of symbol changed events (mappings): {self._mappings_count}. Expected only 1.")

            self.debug(f"{self.time} - SymbolChanged event: {changed_event}")

            if changed_event.old_symbol != str(self._mapped_symbol.id):
                raise AssertionError(f"{self.time} - Unexpected symbol changed event old symbol: {changed_event}")

            if changed_event.new_symbol != str(self._continuous_contract.mapped.id):
                raise AssertionError(f"{self.time} - Unexpected symbol changed event new symbol: {changed_event}")

            # Let's trade the previous mapped contract, so we can hold it until expiration for testing
            # (will be sooner than the new mapped contract)
            self._contract_to_trade = self._mapped_symbol
            self._mapped_symbol = self._continuous_contract.mapped

        # Let's trade after the mapping is done
        if self._contract_to_trade is not None and self._bought_quantity == 0 and self.securities[self._contract_to_trade].exchange.exchange_open:
            self.buy(self._contract_to_trade, 1)

        if self._contract_to_trade is not None and slice.delistings.contains_key(self._contract_to_trade):
            delisting = slice.delistings[self._contract_to_trade]
            if delisting.type == DelistingType.DELISTED:
                self._delisted = True

                if self.portfolio.invested:
                    raise AssertionError(f"{self.time} - Portfolio should not be invested after the traded contract is delisted.")

    def on_order_event(self, order_event):
        if order_event.symbol != self._contract_to_trade:
            raise AssertionError(f"{self.time} - Unexpected order event symbol: {order_event.symbol}. Expected {self._contract_to_trade}")

        if order_event.direction == OrderDirection.BUY:
            if order_event.status == OrderStatus.FILLED:
                if self._bought_quantity != 0 and self._liquidated_quantity != 0:
                    raise AssertionError(f"{self.time} - Unexpected buy order event status: {order_event.status}")

                self._bought_quantity = order_event.quantity
        elif order_event.direction == OrderDirection.SELL:
            if order_event.status == OrderStatus.FILLED:
                if self._bought_quantity <= 0 and self._liquidated_quantity != 0:
                    raise AssertionError(f"{self.time} - Unexpected sell order event status: {order_event.status}")

                self._liquidated_quantity = order_event.quantity
                if self._liquidated_quantity != -self._bought_quantity:
                    raise AssertionError(f"{self.time} - Unexpected liquidated quantity: {self._liquidated_quantity}. Expected: {-self._bought_quantity}")

    def on_securities_changed(self, changes):
        for added_security in changes.added_securities:
            if added_security.symbol.security_type == SecurityType.FUTURE and added_security.symbol.is_canonical():
                self._mapped_symbol = self._continuous_contract.mapped

    def on_end_of_algorithm(self):
        if self._mappings_count == 0:
            raise AssertionError(f"Unexpected number of symbol changed events (mappings): {self._mappings_count}. Expected 1.")

        if not self._delisted:
            raise AssertionError("Contract was not delisted")

        # Make sure we traded and that the position was liquidated on delisting
        if self._bought_quantity <= 0 or self._liquidated_quantity >= 0:
            raise AssertionError(f"Unexpected sold quantity: {self._bought_quantity} and liquidated quantity: {self._liquidated_quantity}")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Strategy example algorithm using CAPE - a bubble indicator dataset saved in dropbox. CAPE is based on a macroeconomic indicator(CAPE Ratio),
we are looking for entry/exit points for momentum stocks CAPE data: January 1990 - December 2014
Goals:
Capitalize in overvalued markets by generating returns with momentum and selling before the crash
Capitalize in undervalued markets by purchasing stocks at bottom of trough

Output:
```python

 # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from AlgorithmImports import *

class BubbleAlgorithm(QCAlgorithm):

    def initialize(self):

        self.set_cash(100000)
        self.set_start_date(1998,1,1)
        self.set_end_date(2014,6,1)
        self._symbols = []
        self._macd_dic, self._rsi_dic = {},{}
        self._new_low, self._curr_cape = None, None
        self._counter, self._counter2 = 0, 0
        self._c, self._c_copy = np.empty([4]), np.empty([4])
        self._symbols.append("SPY")
        # add CAPE data
        self.add_data(Cape, "CAPE")

        # # Present Social Media Stocks:
        # self._symbols.append("FB"), self._symbols.append("LNKD"),self._symbols.append("GRPN"), self._symbols.append("TWTR")
        # self.set_start_date(2011, 1, 1)
        # self.set_end_date(2014, 12, 1)

        # # 2008 Financials
        # self._symbols.append("C"), self._symbols.append("AIG"), self._symbols.append("BAC"), self._symbols.append("HBOS")
        # self.set_start_date(2003, 1, 1)
        # self.set_end_date(2011, 1, 1)

        # # 2000 Dot.com
        # self._symbols.append("IPET"), self._symbols.append("WBVN"), self._symbols.append("GCTY")
        # self.set_start_date(1998, 1, 1)
        # self.set_end_date(2000, 1, 1)

        for stock in self._symbols:
            self.add_security(SecurityType.EQUITY, stock, Resolution.MINUTE)
            self._macd = self.macd(stock, 12, 26, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY)
            self._macd_dic[stock] = self._macd
            self._rsi = self.rsi(stock, 14, MovingAverageType.EXPONENTIAL, Resolution.DAILY)
            self._rsi_dic[stock] = self._rsi

    # Trying to find if current Cape is the lowest Cape in three months to indicate selling period
    def on_data(self, data):

        if self._curr_cape and self._new_low is not None:
            try:
                # Bubble territory
                if self._curr_cape > 20 and self._new_low == False:
                    for stock in self._symbols:
                    # Order stock based on MACD
                    # During market hours, stock is trading, and sufficient cash
                        if self.securities[stock].holdings.quantity == 0 and self._rsi_dic[stock].current.value < 70 \
                        and self.securities[stock].price != 0 \
                        and self.portfolio.cash > self.securities[stock].price * 100 \
                        and self.time.hour == 9 and self.time.minute == 31:
                            self.buy_stock(stock)
                    # Utilize RSI for overbought territories and liquidate that stock
                        if self._rsi_dic[stock].current.value > 70 and self.securities[stock].holdings.quantity > 0 \
                        and self.time.hour == 9 and self.time.minute == 31:
                            self.sell_stock(stock)

                # Undervalued territory
                elif self._new_low:
                    for stock in self._symbols:
                        # Sell stock based on MACD
                        if self.securities[stock].holdings.quantity > 0 and self._rsi_dic[stock].current.value > 30 \
                        and self.time.hour == 9 and self.time.minute == 31:
                            self.sell_stock(stock)
                        # Utilize RSI and MACD to understand oversold territories
                        elif self.securities[stock].holdings.quantity == 0 and self._rsi_dic[stock].current.value < 30 \
                        and self.securities[stock].price != 0 and self.portfolio.cash > self.securities[stock].price * 100 \
                        and self.time.hour == 9 and self.time.minute == 31:
                            self.buy_stock(stock)

                # Cape Ratio is missing from original data
                # Most recent cape data is most likely to be missing
                elif self._curr_cape == 0:
                    self.debug("Exiting due to no CAPE!")
                    self.quit("CAPE ratio not supplied in data, exiting.")

            except:
                # Do nothing
                return None

        if not data.contains_key("CAPE"): return
        self._new_low = False
        # Adds first four Cape Ratios to array c
        self._curr_cape = data["CAPE"].cape
        if self._counter < 4:
            self._c[self._counter] = self._curr_cape
            self._counter +=1
        # Replaces oldest Cape with current Cape
        # Checks to see if current Cape is lowest in the previous quarter
        # Indicating a sell off
        else:
            self._c_copy = self._c
            self._c_copy = np.sort(self._c_copy)
            if self._c_copy[0] > self._curr_cape:
                self._new_low = True
            self._c[self._counter2] = self._curr_cape
            self._counter2 += 1
            if self._counter2 == 4: self._counter2 = 0
        self.debug("Current Cape: " + str(self._curr_cape) + " on " + str(self.time))
        if self._new_low:
            self.debug("New Low has been hit on " + str(self.time))

    # Buy this symbol
    def buy_stock(self,symbol):
        s = self.securities[symbol].holdings
        if self._macd_dic[symbol].current.value>0:
            self.set_holdings(symbol, 1)
            self.debug("Purchasing: " + str(symbol) + "   MACD: " + str(self._macd_dic[symbol]) + "   RSI: " + str(self._rsi_dic[symbol])
                    + "   Price: " + str(round(self.securities[symbol].price, 2)) + "   Quantity: " + str(s.quantity))

    # Sell this symbol
    def sell_stock(self,symbol):
        s = self.securities[symbol].holdings
        if s.quantity > 0 and self._macd_dic[symbol].current.value < 0:
            self.liquidate(symbol)
            self.debug("Selling: " + str(symbol) + " at sell MACD: " + str(self._macd_dic[symbol]) + "   RSI: " + str(self._rsi_dic[symbol])
                    + "   Price: " + str(round(self.securities[symbol].price, 2)) + "   Profit from sale: " + str(s.last_trade_profit))

# CAPE Ratio for SP500 PE Ratio for avg inflation adjusted earnings for previous ten years Custom Data from DropBox
# Original Data from: http://www.econ.yale.edu/~shiller/data.htm
class Cape(PythonData):

    # Return the URL string source of the file. This will be converted to a stream
    # <param name="config">Configuration object</param>
    # <param name="date">Date of this source file</param>
    # <param name="is_live_mode">true if we're in live mode, false for backtesting mode</param>
    # <returns>String URL of source file.</returns>

    def get_source(self, config, date, is_live_mode):
        # Remember to add the "?dl=1" for dropbox links
        return SubscriptionDataSource("https://www.dropbox.com/s/ggt6blmib54q36e/CAPE.csv?dl=1", SubscriptionTransportMedium.REMOTE_FILE)

    ''' Reader Method : using set of arguments we specify read out type. Enumerate until
        the end of the data stream or file. E.g. Read CSV file line by line and convert into data types. '''

    # <returns>BaseData type set by Subscription Method.</returns>
    # <param name="config">Config.</param>
    # <param name="line">Line.</param>
    # <param name="date">Date.</param>
    # <param name="is_live_mode">true if we're in live mode, false for backtesting mode</param>

    def reader(self, config, line, date, is_live_mode):
        if not (line.strip() and line[0].isdigit()): return None

        # New Nifty object
        index = Cape()
        index.symbol = config.symbol

        try:
            # Example File Format:
            # Date   |  Price |  Div  | Earning | CPI  | FractionalDate | Interest Rate | RealPrice | RealDiv | RealEarnings | CAPE
            # 2014.06  1947.09  37.38   103.12   238.343    2014.37          2.6           1923.95     36.94        101.89     25.55
            data = line.split(',')
            # Dates must be in the format YYYY-MM-DD. If your data source does not have this format, you must use
            # DateTime.parse_exact() and explicit declare the format your data source has.
            index.time = datetime.strptime(data[0], "%Y-%m")
            index["Cape"] = float(data[10])
            index.value = data[10]

        except ValueError:
                # Do nothing
                return None

        return index
```