Instruction: You are a quantive developer 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 to demostrate the event handlers of Brokerage activities

Output:
```python

from AlgorithmImports import *

class BrokerageActivityEventHandlingAlgorithm(QCAlgorithm):

    ### <summary>
    ### Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
    ### </summary>
    def initialize(self):
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)
        self.set_cash(100000)

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

    ### <summary>
    ### on_data 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, data):
        if not self.portfolio.invested:
            self.set_holdings("SPY", 1)

    ### <summary>
    ### Brokerage message event handler. This method is called for all types of brokerage messages.
    ### </summary>
    def on_brokerage_message(self, message_event):
        self.debug(f"Brokerage meesage received - {message_event.to_string()}")

    ### <summary>
    ### Brokerage disconnected event handler. This method is called when the brokerage connection is lost.
    ### </summary>
    def on_brokerage_disconnect(self):
        self.debug(f"Brokerage disconnected!")

    ### <summary>
    ### Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.
    ### </summary>
    def on_brokerage_reconnect(self):
        self.debug(f"Brokerage reconnected!")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: This algorithm demonstrates the runtime addition and removal of securities from your algorithm.
With LEAN it is possible to add and remove securities after the initialization.

Output:
```python

from AlgorithmImports import *

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

        self._last_action = None

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        if self._last_action is not None and self._last_action.date() == self.time.date():
            return

        if not self.portfolio.invested:
            self.set_holdings("SPY", .5)
            self._last_action = self.time

        if self.time.weekday() == 1:
            self.add_equity("AIG")
            self.add_equity("BAC")
            self._last_action = self.time

        if self.time.weekday() == 2:
            self.set_holdings("AIG", .25)
            self.set_holdings("BAC", .25)
            self._last_action = self.time

        if self.time.weekday() == 3:
            self.remove_security("AIG")
            self.remove_security("BAC")
            self._last_action = self.time

    def on_order_event(self, order_event):
        if order_event.status == OrderStatus.SUBMITTED:
            self.debug("{0}: Submitted: {1}".format(self.time, self.transactions.get_order_by_id(order_event.order_id)))
        if order_event.status == OrderStatus.FILLED:
            self.debug("{0}: Filled: {1}".format(self.time, self.transactions.get_order_by_id(order_event.order_id)))
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Simple indicator demonstration algorithm of MACD

Output:
```python

from AlgorithmImports import *

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

        # define our daily macd(12,26) with a 9 day signal
        self.__macd = self.macd("SPY", 12, 26, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY)
        self.__previous = datetime.min
        self.plot_indicator("MACD", True, self.__macd, self.__macd.signal)
        self.plot_indicator("SPY", self.__macd.fast, self.__macd.slow)

    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.'''
        # wait for our macd to fully initialize
        if not self.__macd.is_ready: return

        # only once per day
        if self.__previous.date() == self.time.date(): return

        # define a small tolerance on our checks to avoid bouncing
        tolerance = 0.0025

        holdings = self.portfolio["SPY"].quantity

        signal_delta_percent = (self.__macd.current.value - self.__macd.signal.current.value)/self.__macd.fast.current.value

        # if our macd is greater than our signal, then let's go long
        if holdings <= 0 and signal_delta_percent > tolerance:  # 0.01%
            # longterm says buy as well
            self.set_holdings("SPY", 1.0)

        # of our macd is less than our signal, then let's go short
        elif holdings >= 0 and signal_delta_percent < -tolerance:
            self.liquidate("SPY")

        self.__previous = self.time
```


Instruction: You are a quantive developer 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 demonstrating how to access to options history for a given underlying equity security.

Output:
```python

from AlgorithmImports import *

class BasicTemplateOptionsHistoryAlgorithm(QCAlgorithm):
    ''' This example demonstrates how to get access to options history for a given underlying equity security.'''

    def initialize(self):
        # this test opens position in the first day of trading, lives through stock split (7 for 1), and closes adjusted position on the second day
        self.set_start_date(2015, 12, 24)
        self.set_end_date(2015, 12, 24)
        self.set_cash(1000000)

        option = self.add_option("GOOG")
        # add the initial contract filter
        # SetFilter method accepts timedelta objects or integer for days.
        # The following statements yield the same filtering criteria
        option.set_filter(-2, +2, 0, 180)
        # option.set_filter(-2,2, timedelta(0), timedelta(180))

        # set the pricing model for Greeks and volatility
        # find more pricing models https://www.quantconnect.com/lean/documentation/topic27704.html
        option.price_model = OptionPriceModels.crank_nicolson_fd()
        # set the warm-up period for the pricing model
        self.set_warm_up(TimeSpan.from_days(4))
        # set the benchmark to be the initial cash
        self.set_benchmark(lambda x: 1000000)

    def on_data(self,slice):
        if self.is_warming_up: return
        if not self.portfolio.invested:
            for chain in slice.option_chains:
                volatility = self.securities[chain.key.underlying].volatility_model.volatility
                for contract in chain.value:
                    self.log("{0},Bid={1} Ask={2} Last={3} OI={4} sigma={5:.3f} NPV={6:.3f} \
                              delta={7:.3f} gamma={8:.3f} vega={9:.3f} beta={10:.2f} theta={11:.2f} IV={12:.2f}".format(
                    contract.symbol.value,
                    contract.bid_price,
                    contract.ask_price,
                    contract.last_price,
                    contract.open_interest,
                    volatility,
                    contract.theoretical_price,
                    contract.greeks.delta,
                    contract.greeks.gamma,
                    contract.greeks.vega,
                    contract.greeks.rho,
                    contract.greeks.theta / 365,
                    contract.implied_volatility))

    def on_securities_changed(self, changes):
        for change in changes.added_securities:
            # only print options price
            if change.symbol.value == "GOOG": return
            history = self.history(change.symbol, 10, Resolution.MINUTE).sort_index(level='time', ascending=False)[:3]
            for index, row in history.iterrows():
                self.log("History: " + str(index[3])
                        + ": " + index[4].strftime("%m/%d/%Y %I:%M:%S %p")
                        + " > " + str(row.close))
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm demonstrating the use of custom data sourced from the object store

Output:
```python

from AlgorithmImports import *

class CustomDataObjectStoreRegressionAlgorithm(QCAlgorithm):
    custom_data = "2017-08-18 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-18 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-18 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-18 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-18 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-18 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-18 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-18 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-18 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-18 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-18 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-18 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-18 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-18 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-18 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-18 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57\n2017-08-19 01:00:00,5771.75,5792.9,5738.6,5760.2,140394424,5894.04\n2017-08-19 02:00:00,5709.35,5729.85,5683.1,5699.1,142041404,5462.45\n2017-08-19 03:00:00,5748.95,5819.4,5739.4,5808.4,124410018,5121.33\n2017-08-19 04:00:00,5820.4,5854.9,5770.25,5850.05,107160887,4560.84\n2017-08-19 05:00:00,5841.9,5863.4,5804.3,5813.6,117541145,4591.91\n2017-08-19 06:00:00,5805.75,5828.4,5777.9,5822.25,115539008,4643.17\n2017-08-19 07:00:00,5754.15,5755,5645.65,5655.9,198400131,7148\n2017-08-19 08:00:00,5639.9,5686.15,5616.85,5667.65,182410583,6697.18\n2017-08-19 09:00:00,5638.05,5640,5566.25,5590.25,193488581,6308.88\n2017-08-19 10:00:00,5606.95,5666.25,5570.25,5609.1,196571543,6792.49\n2017-08-19 11:00:00,5627.95,5635.25,5579.35,5588.7,160095940,5939.3\n2017-08-19 12:00:00,5647.95,5699.35,5630.95,5682.35,239029425,9184.29\n2017-08-19 13:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-19 14:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-19 15:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-19 16:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-19 17:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-19 18:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-19 19:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-19 20:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-19 21:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-19 22:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-19 23:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-21 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-21 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-21 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-21 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-21 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-21 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-21 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-21 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-21 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-21 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-21 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-21 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-21 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-21 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-21 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57"

    def initialize(self):
        self.set_start_date(2017, 8, 18)
        self.set_end_date(2017, 8, 21)
        self.set_cash(100000)

        self.set_benchmark(lambda x: 0)

        ExampleCustomData.custom_data_key = self.get_custom_data_key()

        self.custom_symbol = self.add_data(ExampleCustomData, "ExampleCustomData", Resolution.HOUR).symbol

        # Saving data here for demonstration and regression testing purposes.
        # In real scenarios, data has to be saved to the object store before the algorithm starts.
        self.save_data_to_object_store()

        self.received_data = []

    def on_data(self, slice: Slice):
        if slice.contains_key(self.custom_symbol):
            custom_data = slice.get(ExampleCustomData, self.custom_symbol)
            if custom_data.price == 0:
                raise AssertionError("Custom data price was not expected to be zero")

            self.received_data.append(custom_data)

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

        custom_security = self.securities[self.custom_symbol]
        if custom_security is None or custom_security.price == 0:
            raise AssertionError("Expected the custom security to be added to the algorithm securities and to have a price that is not zero")

        # Make sure history requests work as expected
        history = self.history(ExampleCustomData, self.custom_symbol, self.start_date, self.end_date, Resolution.HOUR)

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

        for i in range(len(self.received_data)):
            received_data = self.received_data[i]
            if (history.index[i][0] != received_data.symbol or
                history.index[i][1] != received_data.time or
                history[["value"]].values[i][0] != received_data.value or
                history[["open"]].values[i][0] != received_data.open or
                history[["high"]].values[i][0] != received_data.high or
                history[["low"]].values[i][0] != received_data.low or
                history[["close"]].values[i][0] != received_data.close):
                raise AssertionError("History request returned different data than expected")

    def get_custom_data_key(self):
        return "CustomData/ExampleCustomData"

    def save_data_to_object_store(self):
        self.object_store.save(self.get_custom_data_key(), self.custom_data)

class ExampleCustomData(PythonData):
    custom_data_key = ""

    def get_source(self, config, date, is_live):
        return SubscriptionDataSource(self.custom_data_key, SubscriptionTransportMedium.OBJECT_STORE, FileFormat.CSV)

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


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

Input:
Generate a LEAN Algorithm that can be described like this
: This algorithm showcases two margin related event handlers.
OnMarginCallWarning: Fired when a portfolio's remaining margin dips below 5% of the total portfolio value
OnMarginCall: Fired immediately before margin call orders are execued, this gives the algorithm a change to regain margin on its own through liquidation

Output:
```python

from AlgorithmImports import *

class MarginCallEventsAlgorithm(QCAlgorithm):
    """
    This algorithm showcases two margin related event handlers.
    on_margin_call_warning: Fired when a portfolio's remaining margin dips below 5% of the total portfolio value
    on_margin_call: Fired immediately before margin call orders are execued, this gives the algorithm a change to regain margin on its own through liquidation
    """

    def initialize(self):
        self.set_cash(100000)
        self.set_start_date(2013,10,1)
        self.set_end_date(2013,12,11)
        self.add_equity("SPY", Resolution.SECOND)
        # cranking up the leverage increases the odds of a margin call
        # when the security falls in value
        self.securities["SPY"].set_leverage(100)

    def on_data(self, data):
        if not self.portfolio.invested:
            self.set_holdings("SPY",100)

    def on_margin_call(self, requests):
        # Margin call event handler. This method is called right before the margin call orders are placed in the market.
        # <param name="requests">The orders to be executed to bring this algorithm within margin limits</param>
        # this code gets called BEFORE the orders are placed, so we can try to liquidate some of our positions
        # before we get the margin call orders executed. We could also modify these orders by changing their quantities
        for order in requests:

            # liquidate an extra 10% each time we get a margin call to give us more padding
            new_quantity = int(order.quantity * 1.1)
            requests.remove(order)
            requests.append(SubmitOrderRequest(order.order_type, order.security_type, order.symbol, new_quantity, order.stop_price, order.limit_price, self.time, "on_margin_call"))

        return requests

    def on_margin_call_warning(self):
        # Margin call warning event handler.
        # This method is called when portfolio.margin_remaining is under 5% of your portfolio.total_portfolio_value
        # a chance to prevent a margin call from occurring

        spy_holdings = self.securities["SPY"].holdings.quantity
        shares = int(-spy_holdings * 0.005)
        self.error("{0} - on_margin_call_warning(): Liquidating {1} shares of SPY to avoid margin call.".format(self.time, shares))
        self.market_order("SPY", shares)
```


Instruction: You are a quantive developer 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 used to test a fine and coarse selection methods returning Universe.UNCHANGED

Output:
```python

from AlgorithmImports import *

class UniverseUnchangedRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        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(2014,3,25)
        self.set_end_date(2014,4,7)

        self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(days = 1), 0.025, None))
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())

        self.add_universe(self.coarse_selection_function, self.fine_selection_function)

        self.number_of_symbols_fine = 2

    def coarse_selection_function(self, coarse):
        # the first and second selection
        if self.time.date() <= date(2014, 3, 26):
            tickers = [ "AAPL", "AIG", "IBM" ]
            return [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers ]

        # will skip fine selection
        return Universe.UNCHANGED

    def fine_selection_function(self, fine):
        if self.time.date() == date(2014, 3, 25):
            sorted_by_pe_ratio = sorted(fine, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)
            return [ x.symbol for x in sorted_by_pe_ratio[:self.number_of_symbols_fine] ]

        # the second selection will return unchanged, in the following fine selection will be skipped
        return Universe.UNCHANGED

    # assert security changes, throw if called more than once
    def on_securities_changed(self, changes):
        added_symbols = [ x.symbol for x in changes.added_securities ]
        if (len(changes.added_securities) != 2
            or self.time.date() != date(2014, 3, 25)
            or Symbol.create("AAPL", SecurityType.EQUITY, Market.USA) not in added_symbols
            or Symbol.create("IBM", SecurityType.EQUITY, Market.USA) not in added_symbols):
            raise ValueError("Unexpected security changes")
        self.log(f"OnSecuritiesChanged({self.time}):: {changes}")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting the behavior of Universe.SELECTED collection

Output:
```python

from AlgorithmImports import *

class UniverseSelectedRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2014, 3, 25)
        self.set_end_date(2014, 3, 27)

        self.universe_settings.resolution = Resolution.DAILY

        self._universe = self.add_universe(self.selection_function)
        self.selection_count = 0

    def selection_function(self, fundamentals):
        sorted_by_dollar_volume = sorted(fundamentals, key=lambda x: x.dollar_volume, reverse=True)

        sorted_by_dollar_volume = sorted_by_dollar_volume[self.selection_count:]
        self.selection_count = self.selection_count + 1

        # return the symbol objects of the top entries from our sorted collection
        return [ x.symbol for x in sorted_by_dollar_volume[:self.selection_count] ]

    def on_data(self, data):
        if Symbol.create("TSLA", SecurityType.EQUITY, Market.USA) in self._universe.selected:
            raise ValueError(f"TSLA shouldn't of been selected")

        self.buy(next(iter(self._universe.selected)), 1)

    def on_end_of_algorithm(self):
        if self.selection_count != 3:
            raise ValueError(f"Unexpected selection count {self.selection_count}")
        if self._universe.selected.count != 3 or self._universe.selected.count == self._universe.members.count:
            raise ValueError(f"Unexpected universe selected count {self._universe.selected.count}")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm reproducing data type bugs in the RegisterIndicator API. Related to GH 4205.

Output:
```python

from AlgorithmImports import *
from CustomDataRegressionAlgorithm import Bitcoin

class RegisterIndicatorRegressionAlgorithm(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):
        self.set_start_date(2020, 1, 5)
        self.set_end_date(2020, 1, 10)

        SP500 = Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME)
        self._symbol = _symbol = self.future_chain_provider.get_future_contract_list(SP500, (self.start_date + timedelta(days=1)))[0]
        self.add_future_contract(_symbol)

        # this collection will hold all indicators and at the end of the algorithm we will assert that all of them are ready
        self._indicators = []

        # this collection will be used to determine if the Selectors were called, we will assert so at the end of algorithm
        self._selector_called = [ False, False, False, False, False, False ]

        # First we will test that we can register our custom indicator using a QuoteBar consolidator
        indicator = CustomIndicator()
        consolidator = self.resolve_consolidator(_symbol, Resolution.MINUTE, QuoteBar)
        self.register_indicator(_symbol, indicator, consolidator)
        self._indicators.append(indicator)

        indicator2 = CustomIndicator()
        # We use the TimeDelta overload to fetch the consolidator
        consolidator = self.resolve_consolidator(_symbol, timedelta(minutes=1), QuoteBar)
        # We specify a custom selector to be used
        self.register_indicator(_symbol, indicator2, consolidator, lambda bar: self.set_selector_called(0) and bar)
        self._indicators.append(indicator2)

        # We use a IndicatorBase<IndicatorDataPoint> with QuoteBar data and a custom selector
        indicator3 = SimpleMovingAverage(10)
        consolidator = self.resolve_consolidator(_symbol, timedelta(minutes=1), QuoteBar)
        self.register_indicator(_symbol, indicator3, consolidator, lambda bar: self.set_selector_called(1) and (bar.ask.high - bar.bid.low))
        self._indicators.append(indicator3)

        # We test default consolidator resolution works correctly
        moving_average = SimpleMovingAverage(10)
        # Using Resolution, specifying custom selector and explicitly using TradeBar.volume
        self.register_indicator(_symbol, moving_average, Resolution.MINUTE, lambda bar: self.set_selector_called(2) and bar.volume)
        self._indicators.append(moving_average)

        moving_average2 = SimpleMovingAverage(10)
        # Using Resolution
        self.register_indicator(_symbol, moving_average2, Resolution.MINUTE)
        self._indicators.append(moving_average2)

        moving_average3 = SimpleMovingAverage(10)
        # Using timedelta
        self.register_indicator(_symbol, moving_average3, timedelta(minutes=1))
        self._indicators.append(moving_average3)

        moving_average4 = SimpleMovingAverage(10)
        # Using time_delta, specifying custom selector and explicitly using TradeBar.volume
        self.register_indicator(_symbol, moving_average4, timedelta(minutes=1), lambda bar: self.set_selector_called(3) and bar.volume)
        self._indicators.append(moving_average4)

        # Test custom data is able to register correctly and indicators updated
        symbol_custom = self.add_data(Bitcoin, "BTC", Resolution.MINUTE).symbol

        sma_custom_data = SimpleMovingAverage(1)
        self.register_indicator(symbol_custom, sma_custom_data, timedelta(minutes=1), lambda bar: self.set_selector_called(4) and bar.volume)
        self._indicators.append(sma_custom_data)

        sma_custom_data2 = SimpleMovingAverage(1)
        self.register_indicator(symbol_custom, sma_custom_data2, Resolution.MINUTE)
        self._indicators.append(sma_custom_data2)

        sma_custom_data3 = SimpleMovingAverage(1)
        consolidator = self.resolve_consolidator(symbol_custom, timedelta(minutes=1))
        self.register_indicator(symbol_custom, sma_custom_data3, consolidator, lambda bar: self.set_selector_called(5) and bar.volume)
        self._indicators.append(sma_custom_data3)

    def set_selector_called(self, position):
        self._selector_called[position] = True
        return True

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

    def on_end_of_algorithm(self):
        if any(not was_called for was_called in self._selector_called):
            raise ValueError("All selectors should of been called")
        if any(not indicator.is_ready for indicator in self._indicators):
            raise ValueError("All indicators should be ready")
        self.log(f'Total of {len(self._indicators)} are ready')

class CustomIndicator(PythonIndicator):
    def __init__(self):
        super().__init__()
        self.name = "Jose"
        self.value = 0

    def update(self, input):
        self.value = input.ask.high
        return 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
: Tests the delisting of the composite Symbol (ETF symbol) and the removal of
the universe and the symbol from the algorithm.

Output:
```python

from AlgorithmImports import *

class ETFConstituentUniverseCompositeDelistingRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2020, 12, 1)
        self.set_end_date(2021, 1, 31)
        self.set_cash(100000)

        self.universe_symbol_count = 0
        self.universe_selection_done = False
        self.universe_added = False
        self.universe_removed = False

        self.universe_settings.resolution = Resolution.HOUR
        self.delisting_date = date(2021, 1, 21)

        self.aapl = self.add_equity("AAPL", Resolution.HOUR).symbol
        self.gdvd = self.add_equity("GDVD", Resolution.HOUR).symbol

        self.add_universe(self.universe.etf(self.gdvd, self.universe_settings, self.filter_etfs))

    def filter_etfs(self, constituents):
        self.universe_selection_done = True

        if self.utc_time.date() > self.delisting_date:
            raise AssertionError(f"Performing constituent universe selection on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')} after composite ETF has been delisted")

        constituent_symbols = [i.symbol for i in constituents]
        self.universe_symbol_count = len(set(constituent_symbols))

        return constituent_symbols

    def on_data(self, data):
        if self.utc_time.date() > self.delisting_date and any([i != self.aapl for i in data.keys()]):
            raise AssertionError("Received unexpected slice in OnData(...) after universe was deselected")

        if not self.portfolio.invested:
            self.set_holdings(self.aapl, 0.5)

    def on_securities_changed(self, changes):
        if len(changes.added_securities) != 0 and self.utc_time.date() > self.delisting_date:
            raise AssertionError("New securities added after ETF constituents were delisted")

        # Since we added the etf subscription it will get delisted and send us a removal event
        expected_changes_count = self.universe_symbol_count + 1

        if self.universe_selection_done:
            # "_universe_symbol_count + 1" because selection is done right away,
            # so AddedSecurities includes all ETF constituents (including APPL) plus GDVD
            self.universe_added = self.universe_added or len(changes.added_securities) == expected_changes_count

        # TODO: shouldn't be sending AAPL as a removed security since it was added by another universe
        self.universe_removed = self.universe_removed or (
            len(changes.removed_securities) == expected_changes_count and
            self.utc_time.date() >= self.delisting_date and
            self.utc_time.date() < self.end_date.date())

    def on_end_of_algorithm(self):
        if not self.universe_added:
            raise AssertionError("ETF constituent universe was never added to the algorithm")
        if not self.universe_removed:
            raise AssertionError("ETF constituent universe was not removed from the algorithm after delisting")
        if len(self.active_securities) > 2:
            raise AssertionError(f"Expected less than 2 securities after algorithm ended, found {len(self.securities)}")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.
This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.

All orders are sent from the brokerage, none of them will be placed by the algorithm.

Output:
```python

from AlgorithmImports import *

class CustomBrokerageSideOrderHandlingRegressionPartialAlgorithm(QCAlgorithm):
    '''Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.
     This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.

     All orders are sent from the brokerage, none of them will be placed by the algorithm.'''

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

        self.set_brokerage_message_handler(CustomBrokerageMessageHandler(self))

        self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)

    def on_end_of_algorithm(self):
        # The security should have been added
        if not self.securities.contains_key(self._spy):
            raise AssertionError("Expected security to have been added")

        if self.transactions.orders_count == 0:
            raise AssertionError("Expected orders to be added from brokerage side")

        if len(list(self.portfolio.positions.groups)) != 1:
            raise AssertionError("Expected only one position")

class CustomBrokerageMessageHandler(DefaultBrokerageMessageHandler):
    def __init__(self, algorithm):
        super().__init__(algorithm)
        self._algorithm = algorithm

    def handle_order(self, event_args):
        order = event_args.order
        if order.tag is None or not order.tag.isdigit():
            raise AssertionError("Expected all new brokerage-side orders to have a valid tag")

        # We will only process orders with even tags
        return int(order.tag) % 2 == 0
```


Instruction: You are a quantive developer 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 *
import base64

class DropboxUniverseSelectionAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2017, 7, 4)
        self.set_end_date(2018, 7, 4)

        self._backtest_symbols_per_day = {}
        self._current_universe = []

        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.add_universe("my-dropbox-universe", self.selector)

    def selector(self, date: datetime) -> list[str]:
        # handle live mode file format
        if self.live_mode:
            # fetch the file from dropbox
            str = self.download("https://www.dropbox.com/s/2l73mu97gcehmh7/daily-stock-picker-live.csv?dl=1")
            # if we have a file for today, return symbols, else leave universe unchanged
            self._current_universe = str.split(',') if len(str) > 0 else self._current_universe
            return self._current_universe

        # backtest - first cache the entire file
        if len(self._backtest_symbols_per_day) == 0:

            # No need for headers for authorization with dropbox, these two lines are for example purposes
            byte_key = base64.b64encode("UserName:Password".encode('ASCII'))
            # The headers must be passed to the Download method as dictionary
            headers = { 'Authorization' : f'Basic ({byte_key.decode("ASCII")})' }

            str = self.download("https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1", headers)
            for line in str.splitlines():
                data = line.split(',')
                self._backtest_symbols_per_day[data[0]] = data[1:]

        index = date.strftime("%Y%m%d")
        self._current_universe = self._backtest_symbols_per_day.get(index, self._current_universe)

        return self._current_universe

    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
```


Instruction: You are a quantive developer 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 showing how to implement a custom universe selection model and asserting it's behavior

Output:
```python

from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel

class CustomUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2014,3,24)
        self.set_end_date(2014,4,7)

        self.universe_settings.resolution = Resolution.DAILY
        self.set_universe_selection(MyCustomUniverseSelectionModel())

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

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            for kvp in self.active_securities:
                self.set_holdings(kvp.key, 0.1)

class MyCustomUniverseSelectionModel(FundamentalUniverseSelectionModel):

    def __init__(self, universe_settings = None):
        super().__init__(universe_settings)
        self._selected = False

    def select(self, algorithm, fundamental):
        if not self._selected:
            self._selected = True
            return [ Symbol.create('AAPL', SecurityType.EQUITY, Market.USA) ]
        return Universe.UNCHANGED
```


Instruction: You are a quantive developer 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 the indicator history api

Output:
```python

from AlgorithmImports import *

class IndicatorHistoryRegressionAlgorithm(QCAlgorithm):
    '''Regression algorithm asserting the behavior of the indicator history api'''

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

        self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol

    def on_data(self, slice: Slice):
        self.bollinger_bands = BollingerBands("BB", 20, 2.0, MovingAverageType.SIMPLE)

        if self.bollinger_bands.window.is_ready:
            raise ValueError("Unexpected ready bollinger bands state")

        indicatorHistory = self.indicator_history(self.bollinger_bands, self._symbol, 50)

        self.debug(f"indicatorHistory: {indicatorHistory}")

        self.debug(f"data_frame: {indicatorHistory.data_frame}")

        if not self.bollinger_bands.window.is_ready:
            raise ValueError("Unexpected not ready bollinger bands state")

        # we ask for 50 data points
        if indicatorHistory.count != 50:
            raise ValueError(f"Unexpected indicators values {indicatorHistory.count}")

        for indicatorDataPoints in indicatorHistory:
            middle_band = indicatorDataPoints["middle_band"]
            self.debug(f"BB @{indicatorDataPoints.current}: middle_band: {middle_band} upper_band: {indicatorDataPoints.upper_band}")
            if indicatorDataPoints == 0:
                raise ValueError(f"Unexpected indicators point {indicatorDataPoints}")

        currentValues = indicatorHistory.current
        if len(currentValues) != 50 or len([x for x in currentValues if x.value == 0]) > 0:
            raise ValueError(f"Unexpected indicators current values {len(currentValues)}")
        upperBandPoints = indicatorHistory["upper_band"]
        if len(upperBandPoints) != 50 or len([x for x in upperBandPoints if x.value == 0]) > 0:
            raise ValueError(f"Unexpected indicators upperBandPoints values {len(upperBandPoints)}")

        # We are done now!
        self.quit()
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration of how to use custom security properties.
In this algorithm we trade a security based on the values of a slow and fast EMAs which are stored in the security itself.

Output:
```python

from cmath import isclose
from AlgorithmImports import *

class SecurityCustomPropertiesAlgorithm(QCAlgorithm):
    '''Demonstration of how to use custom security properties.
    In this algorithm we trade a security based on the values of a slow and fast EMAs which are stored in the security itself.'''

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

        self.spy = self.add_equity("SPY", Resolution.MINUTE)

        # Using the dynamic interface to store our indicator as a custom property.
        self.spy.slow_ema = self.ema(self.spy.symbol, 30, Resolution.MINUTE)

        # Using the generic interface to store our indicator as a custom property.
        self.spy.add("fast_ema", self.ema(self.spy.symbol, 60, Resolution.MINUTE))

        # Using the indexer to store our indicator as a custom property
        self.spy["bb"] = self.bb(self.spy.symbol, 20, 1, MovingAverageType.SIMPLE, Resolution.MINUTE)

        # Fee factor to be used by the custom fee model
        self.spy.fee_factor = 0.00002
        self.spy.set_fee_model(CustomFeeModel())

        # This property will be used to store the prices used to calculate the fees in order to assert the correct fee factor is used.
        self.spy.orders_fees_prices = {}

    def on_data(self, data):
        if not self.spy.fast_ema.is_ready:
            return

        if not self.portfolio.invested:
            # Using the property and the generic interface to access our indicator
            if self.spy.slow_ema > self.spy.fast_ema:
                self.set_holdings(self.spy.symbol, 1)
        else:
            if self.spy.get[ExponentialMovingAverage]("slow_ema") < self.spy.get[ExponentialMovingAverage]("fast_ema"):
                self.liquidate(self.spy.symbol)

        # Using the indexer to access our indicator
        bb: BollingerBands = self.spy["bb"]
        self.plot("bb", bb.upper_band, bb.middle_band, bb.lower_band)

    def on_order_event(self, order_event):
        if order_event.status == OrderStatus.FILLED:
            fee = order_event.order_fee
            expected_fee = self.spy.orders_fees_prices[order_event.order_id] * order_event.absolute_fill_quantity * self.spy.fee_factor
            if not isclose(fee.value.amount, expected_fee, rel_tol=1e-15):
                raise AssertionError(f"Custom fee model failed to set the correct fee. Expected: {expected_fee}. Actual: {fee.value.amount}")

    def on_end_of_algorithm(self):
        if self.transactions.orders_count == 0:
            raise AssertionError("No orders executed")

class CustomFeeModel(FeeModel):
    '''This custom fee is implemented for demonstration purposes only.'''

    def get_order_fee(self, parameters):
        security = parameters.security
        # custom fee math using the fee factor stored in security instance
        fee_factor = security.fee_factor
        if fee_factor is None:
            fee_factor = 0.00001

        # Store the price used to calculate the fee for this order
        security["orders_fees_prices"][parameters.order.id] = security.price

        fee = max(1.0, security.price * parameters.order.absolute_quantity * fee_factor)

        return OrderFee(CashAmount(fee, "USD"))
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting that using separate coarse & fine selection with async universe settings is not allowed

Output:
```python

from AlgorithmImports import *

class CoarseFineAsyncUniverseRegressionAlgorithm(QCAlgorithm):

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

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

        self.universe_settings.asynchronous = True

        threw_exception = False
        try:
            self.add_universe(self.coarse_selection_function, self.fine_selection_function)
        except:
            # expected
            threw_exception = True
            pass

        if not threw_exception:
            raise ValueError("Expected exception to be thrown for AddUniverse")

        self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.coarse_selection_function, self.fine_selection_function))

    def coarse_selection_function(self, coarse):
        return []

    def fine_selection_function(self, fine):
        return []
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Base regression algorithm exercising different style options with option price models that might
or might not support them. Also, if the option style is supported, greeks are asserted to be accesible and have valid values.

Output:
```python

from AlgorithmImports import *

class OptionPriceModelForOptionStylesBaseRegressionAlgorithm(QCAlgorithm):
    def __init__(self) -> None:
        super().__init__()
        self._option_style_is_supported = False
        self._check_greeks = True
        self._tried_greeks_calculation = False
        self._option = None

    def on_data(self, slice: Slice) -> None:
        if self.is_warming_up:
            return

        for kvp in slice.option_chains:
            if not self._option or kvp.key != self._option.symbol:
                continue

            self.check_greeks([contract for contract in kvp.value])

    def on_end_of_day(self, symbol: Symbol) -> None:
        self._check_greeks = True

    def on_end_of_algorithm(self) -> None:
        if not self._tried_greeks_calculation:
            raise AssertionError("Expected greeks to be accessed")

    def init(self, option: Option, option_style_is_supported: bool) -> None:
        self._option = option
        self._option_style_is_supported = option_style_is_supported
        self._check_greeks = True
        self._tried_greeks_calculation = False

    def check_greeks(self, contracts: list[OptionContract]) -> None:
        if not self._check_greeks or len(contracts) == 0 or not self._option:
            return

        self._check_greeks = False
        self._tried_greeks_calculation = True

        for contract in contracts:
            greeks = None
            try:
                greeks = contract.greeks

                # Greeks should have not been successfully accessed if the option style is not supported
                option_style_str = 'American' if self._option.style == OptionStyle.AMERICAN else 'European'
                if not self._option_style_is_supported:
                    raise AssertionError(f'Expected greeks not to be calculated for {contract.symbol.value}, an {option_style_str} style option, using {type(self._option.price_model).__name__}, which does not support them, but they were')
            except ArgumentException:
                # ArgumentException is only expected if the option style is not supported
                if self._option_style_is_supported:
                    raise AssertionError(f'Expected greeks to be calculated for {contract.symbol.value}, an {option_style_str} style option, using {type(self._option.price_model).__name__}, which supports them, but they were not')

            # Greeks should be valid if they were successfuly accessed for supported option style
            # Delta can be {-1, 0, 1} if the price is too wild, rho can be 0 if risk free rate is 0
            # Vega can be 0 if the price is very off from theoretical price, Gamma = 0 if Delta belongs to {-1, 1}
            if (self._option_style_is_supported
                and (not greeks
                    or ((contract.right == OptionRight.CALL and (greeks.delta < 0.0 or greeks.delta > 1.0 or greeks.rho < 0.0))
                        or (contract.right == OptionRight.PUT and (greeks.delta < -1.0 or greeks.delta > 0.0 or greeks.rho > 0.0))
                        or greeks.theta == 0.0 or greeks.vega < 0.0 or greeks.gamma < 0.0))):
                raise AssertionError(f'Expected greeks to have valid values. Greeks were: Delta: {greeks.delta}, Rho: {greeks.rho}, Theta: {greeks.theta}, Vega: {greeks.vega}, Gamma: {greeks.gamma}')

```


Instruction: You are a quantive developer 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 that we only receive the option chain for a single future contract
in the option universe filter.

Output:
```python

from AlgorithmImports import *

class AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.invested = False
        self.on_data_reached = False
        self.option_filter_ran = False
        self.symbols_received = []
        self.expected_symbols_received = []
        self.data_received = {}

        self.set_start_date(2020, 1, 4)
        self.set_end_date(2020, 1, 8)

        self.es = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, Market.CME)
        self.es.set_filter(lambda future_filter: future_filter.expiration(0, 365).expiration_cycle([3, 6]))

        self.add_future_option(self.es.symbol, self.option_contract_universe_filter_function)

    def option_contract_universe_filter_function(self, option_contracts: OptionFilterUniverse) -> OptionFilterUniverse:
        self.option_filter_ran = True

        expiry_dates = list(set([x.symbol.underlying.id.date for x in option_contracts]))
        expiry = None if not any(expiry_dates) else expiry_dates[0]

        symbols = [x.symbol.underlying for x in option_contracts]
        symbol = None if not any(symbols) else symbols[0]

        if expiry is None or symbol is None:
            raise AssertionError("Expected a single Option contract in the chain, found 0 contracts")

        self.expected_symbols_received.extend([x.symbol for x in option_contracts])

        return option_contracts

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

        self.on_data_reached = True
        has_option_quote_bars = False

        for qb in data.quote_bars.values():
            if qb.symbol.security_type != SecurityType.FUTURE_OPTION:
                continue

            has_option_quote_bars = True

            self.symbols_received.append(qb.symbol)
            if qb.symbol not in self.data_received:
                self.data_received[qb.symbol] = []

            self.data_received[qb.symbol].append(qb)

        if self.invested or not has_option_quote_bars:
            return

        for chain in sorted(data.option_chains.values(), key=lambda chain: chain.symbol.underlying.id.date):
            future_invested = False
            option_invested = False

            for option in chain.contracts.keys():
                if future_invested and option_invested:
                    return

                future = option.underlying

                if not option_invested and data.contains_key(option):
                    self.market_order(option, 1)
                    self.invested = True
                    option_invested = True

                if not future_invested and data.contains_key(future):
                    self.market_order(future, 1)
                    self.invested = True
                    future_invested = True

    def on_end_of_algorithm(self):
        super().on_end_of_algorithm()
        self.symbols_received = list(set(self.symbols_received))
        self.expected_symbols_received = list(set(self.expected_symbols_received))

        if not self.option_filter_ran:
            raise AssertionError("Option chain filter was never ran")
        if not self.on_data_reached:
            raise AssertionError("OnData() was never called.")
        if len(self.symbols_received) != len(self.expected_symbols_received):
            raise AssertionError(f"Expected {len(self.expected_symbols_received)} option contracts Symbols, found {len(self.symbols_received)}")

        missing_symbols = [expected_symbol for expected_symbol in self.expected_symbols_received if expected_symbol not in self.symbols_received]
        if any(missing_symbols):
            raise AssertionError(f'Symbols: "{", ".join(missing_symbols)}" were not found in OnData')

        for expected_symbol in self.expected_symbols_received:
            data = self.data_received[expected_symbol]
            for data_point in data:
                data_point.end_time = datetime(1970, 1, 1)

            non_dupe_data_count = len(set(data))
            if non_dupe_data_count < 1000:
                raise AssertionError(f"Received too few data points. Expected >=1000, found {non_dupe_data_count} for {expected_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 assert the behavior of <see cref="MacdAlphaModel"/>.

Output:
```python

from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Alphas.MacdAlphaModel import MacdAlphaModel

class MacdAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):

    def initialize(self):
        super().initialize()
        self.set_alpha(MacdAlphaModel())

    def on_end_of_algorithm(self):
        expected = 4
        if self.insights.total_count != expected:
           raise AssertionError(f"The total number of insights should be {expected}. Actual: {self.insights.total_count}")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Tests that orders are denied if they exceed the max shortable quantity.

Output:
```python

from AlgorithmImports import *

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

class ShortableProviderOrdersRejectedRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.orders_allowed = []
        self.orders_denied = []
        self.initialized = False
        self.invalidated_allowed_order = False
        self.invalidated_new_order_with_portfolio_holdings = False

        self.set_start_date(2013, 10, 4)
        self.set_end_date(2013, 10, 11)
        self.set_cash(10000000)

        self.spy = self.add_equity("SPY", Resolution.MINUTE)
        self.aig = self.add_equity("AIG", Resolution.MINUTE)

        self.spy.set_shortable_provider(RegressionTestShortableProvider())
        self.aig.set_shortable_provider(RegressionTestShortableProvider())

    def on_data(self, data):
        if not self.initialized:
            self.handle_order(self.limit_order(self.spy.symbol, -1001, 10000)) # Should be canceled, exceeds the max shortable quantity
            order_ticket = self.limit_order(self.spy.symbol, -1000, 10000)
            self.handle_order(order_ticket) # Allowed, orders at or below 1000 should be accepted
            self.handle_order(self.limit_order(self.spy.symbol, -10, 0.01)) # Should be canceled, the total quantity we would be short would exceed the max shortable quantity.

            response = order_ticket.update_quantity(-999) # should be allowed, we are reducing the quantity we want to short
            if not response.is_success:
                raise ValueError("Order update should of succeeded!")

            self.initialized = True
            return

        if not self.invalidated_allowed_order:
            if len(self.orders_allowed) != 1:
                raise AssertionError(f"Expected 1 successful order, found: {len(self.orders_allowed)}")
            if len(self.orders_denied) != 2:
                raise AssertionError(f"Expected 2 failed orders, found: {len(self.orders_denied)}")

            allowed_order = self.orders_allowed[0]
            order_update = UpdateOrderFields()
            order_update.limit_price = 0.01
            order_update.quantity = -1001
            order_update.tag = "Testing updating and exceeding maximum quantity"

            response = allowed_order.update(order_update)
            if response.error_code != OrderResponseErrorCode.EXCEEDS_SHORTABLE_QUANTITY:
                raise AssertionError(f"Expected order to fail due to exceeded shortable quantity, found: {response.error_code}")

            cancel_response = allowed_order.cancel()
            if cancel_response.is_error:
                raise AssertionError("Expected to be able to cancel open order after bad qty update")

            self.invalidated_allowed_order = True
            self.orders_denied.clear()
            self.orders_allowed.clear()
            return

        if not self.invalidated_new_order_with_portfolio_holdings:
            self.handle_order(self.market_order(self.spy.symbol, -1000)) # Should succeed, no holdings and no open orders to stop this
            spy_shares = self.portfolio[self.spy.symbol].quantity
            if spy_shares != -1000:
                raise AssertionError(f"Expected -1000 shares in portfolio, found: {spy_shares}")

            self.handle_order(self.limit_order(self.spy.symbol, -1, 0.01)) # Should fail, portfolio holdings are at the max shortable quantity.
            if len(self.orders_denied) != 1:
                raise AssertionError(f"Expected limit order to fail due to existing holdings, but found {len(self.orders_denied)} failures")

            self.orders_allowed.clear()
            self.orders_denied.clear()

            self.handle_order(self.market_order(self.aig.symbol, -1001))
            if len(self.orders_allowed) != 1:
                raise AssertionError(f"Expected market order of -1001 BAC to not fail")

            self.invalidated_new_order_with_portfolio_holdings = True

    def handle_order(self, order_ticket):
        if order_ticket.submit_request.status == OrderRequestStatus.ERROR:
            self.orders_denied.append(order_ticket)
            return

        self.orders_allowed.append(order_ticket)
```


Instruction: You are a quantive developer 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 using FutureOptions daily resolution

Output:
```python

from AlgorithmImports import *

class FutureOptionHourlyRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2020, 1, 7)
        self.set_end_date(2020, 1, 8)
        resolution = Resolution.HOUR

        # Add our underlying future contract
        self.es = self.add_future_contract(
            Symbol.create_future(
                Futures.Indices.SP_500_E_MINI,
                Market.CME,
                datetime(2020, 3, 20)
            ),
            resolution).symbol

        # Attempt to fetch a specific ITM future option contract
        es_options = [
            self.add_future_option_contract(x, resolution).symbol for x in (self.option_chain_provider.get_option_contract_list(self.es, self.time)) if x.id.strike_price == 3200 and x.id.option_right == OptionRight.CALL
        ]
        self.es_option = es_options[0]

        # Validate it is the expected contract
        expected_contract = Symbol.create_option(self.es, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200, datetime(2020, 3, 20))
        if self.es_option != expected_contract:
            raise AssertionError(f"Contract {self.es_option} was not the expected contract {expected_contract}")

        # Schedule a purchase of this contract at noon
        self.schedule.on(self.date_rules.today, self.time_rules.noon, self.schedule_callback_buy)

        # Schedule liquidation at 2pm when the market is open
        self.schedule.on(self.date_rules.today, self.time_rules.at(17,0,0), self.schedule_callback_liquidate)

    def schedule_callback_buy(self):
        self.ticket = self.market_order(self.es_option, 1)

    def on_data(self, slice):
        # Assert we are only getting data at 7PM (12AM UTC)
        if slice.time.minute != 0:
            raise AssertionError(f"Expected data only on hourly intervals; instead was {slice.time}")

    def schedule_callback_liquidate(self):
        self.liquidate()

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

        if self.ticket.status != OrderStatus.FILLED:
            raise AssertionError("Future option order failed to fill correctly")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Universe Selection regression algorithm simulates an edge case. In one week, Google listed two new symbols, delisted one of them and changed tickers.

Output:
```python

from AlgorithmImports import *

class UniverseSelectionRegressionAlgorithm(QCAlgorithm):

    def initialize(self):

        self.set_start_date(2014,3,22)   #Set Start Date
        self.set_end_date(2014,4,7)      #Set End Date
        self.set_cash(100000)           #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        # security that exists with no mappings
        self.add_equity("SPY", Resolution.DAILY)
        # security that doesn't exist until half way in backtest (comes in as GOOCV)
        self.add_equity("GOOG", Resolution.DAILY)

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

        self.delisted_symbols = []
        self.changes = None

    def coarse_selection_function(self, coarse):
        return [ c.symbol for c in coarse if c.symbol.value == "GOOG" or c.symbol.value == "GOOCV" or c.symbol.value == "GOOAV" or c.symbol.value == "GOOGL" ]

    def on_data(self, data):
        if self.transactions.orders_count == 0:
            self.market_order("SPY", 100)

        for kvp in data.delistings:
            self.delisted_symbols.append(kvp.key)

        if self.changes is None:
            return

        if not all(data.bars.contains_key(x.symbol) for x in self.changes.added_securities):
            return

        for security in self.changes.added_securities:
            self.log("{0}: Added Security: {1}".format(self.time, security.symbol))
            self.market_on_open_order(security.symbol, 100)

        for security in self.changes.removed_securities:
            self.log("{0}: Removed Security: {1}".format(self.time, security.symbol))
            if security.symbol not in self.delisted_symbols:
                self.log("Not in delisted: {0}:".format(security.symbol))
                self.market_on_open_order(security.symbol, -100)

        self.changes = None

    def on_securities_changed(self, changes):
        self.changes = changes

    def on_order_event(self, orderEvent):
        if orderEvent.status == OrderStatus.SUBMITTED:
            self.log("{0}: Submitted: {1}".format(self.time, self.transactions.get_order_by_id(orderEvent.order_id)))
        if orderEvent.status == OrderStatus.FILLED:
            self.log("{0}: Filled: {1}".format(self.time, self.transactions.get_order_by_id(orderEvent.order_id)))
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration of using the ETFConstituentsUniverseSelectionModel with simple ticker

Output:
```python

from AlgorithmImports import *
from Selection.ETFConstituentsUniverseSelectionModel import *
from ETFConstituentsFrameworkAlgorithm import ETFConstituentsFrameworkAlgorithm

class ETFConstituentsFrameworkWithDifferentSelectionModelAlgorithm(ETFConstituentsFrameworkAlgorithm):

    def initialize(self):
        super().initialize()

        self.set_universe_selection(ETFConstituentsUniverseSelectionModel("SPY", self.universe_settings, self.etf_constituents_filter))
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Example algorithm showing and asserting the usage of the "ShortMarginInterestRateModel"
paired with a "IShortableProvider" instance, for example "InteractiveBrokersShortableProvider"

Output:
```python

from AlgorithmImports import *

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

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

        self._short = self.add_equity("SPY", Resolution.HOUR)
        self._long = self.add_equity("AAPL", Resolution.HOUR)

        for security in [ self._short, self._long]:
            security.set_shortable_provider(LocalDiskShortableProvider("testbrokerage"))
            security.margin_interest_rate_model = ShortMarginInterestRateModel()

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

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            self.set_holdings("SPY", -0.5)
            self.set_holdings("AAPL", 0.5)

    def on_end_of_algorithm(self):
        if self._short.margin_interest_rate_model.amount >= 0:
            raise RegressionTestException("Expected short fee interest rate to be charged")

        if self._long.margin_interest_rate_model.amount <= 0:
            raise RegressionTestException("Expected short fee interest rate to be earned")
```


Instruction: You are a quantive developer 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 is an option split regression algorithm

Output:
```python

from AlgorithmImports import *

class OptionRenameRegressionAlgorithm(QCAlgorithm):

    def initialize(self):

        self.set_cash(1000000)
        self.set_start_date(2013,6,28)
        self.set_end_date(2013,7,2)
        option = self.add_option("TFCFA")

        # set our strike/expiry filter for this option chain
        option.set_filter(-1, 1, timedelta(0), timedelta(3650))
        # use the underlying equity as the benchmark
        self.set_benchmark("TFCFA")

    def on_data(self, slice):
        ''' Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
        <param name="slice">The current slice of data keyed by symbol string</param> '''
        if not self.portfolio.invested:
            for kvp in slice.option_chains:
                chain = kvp.value
                if self.time.day == 28 and self.time.hour > 9 and self.time.minute > 0:

                    contracts = [i for i in sorted(chain, key=lambda x:x.expiry)
                                         if i.right ==  OptionRight.CALL and
                                            i.strike == 33 and
                                            i.expiry.date() == datetime(2013,8,17).date()]
                    if contracts:
                        # Buying option
                        contract = contracts[0]
                        self.buy(contract.symbol, 1)
                        # Buy the undelying stock
                        underlying_symbol = contract.symbol.underlying
                        self.buy (underlying_symbol, 100)
                        # check
                        if float(contract.ask_price) != 1.1:
                            raise ValueError("Regression test failed: current ask price was not loaded from NWSA backtest file and is not $1.1")
        elif self.time.day == 2 and self.time.hour > 14 and self.time.minute > 0:
            for kvp in slice.option_chains:
                chain = kvp.value
                self.liquidate()
                contracts = [i for i in sorted(chain, key=lambda x:x.expiry)
                                        if i.right ==  OptionRight.CALL and
                                           i.strike == 33 and
                                           i.expiry.date() == datetime(2013,8,17).date()]
            if contracts:
                contract = contracts[0]
                self.log("Bid Price" + str(contract.bid_price))
                if float(contract.bid_price) != 0.05:
                    raise ValueError("Regression test failed: current bid price was not loaded from FOXA file and is not $0.05")

    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
: Tests the delisting of the composite Symbol (ETF symbol) and the removal of
the universe and the symbol from the algorithm, without adding a subscription via AddEquity

Output:
```python

from AlgorithmImports import *

class ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2020, 12, 1)
        self.set_end_date(2021, 1, 31)
        self.set_cash(100000)

        self.universe_symbol_count = 0
        self.universe_selection_done = False
        self.universe_added = False
        self.universe_removed = False

        self.universe_settings.resolution = Resolution.HOUR
        self.delisting_date = date(2021, 1, 21)

        self.aapl = self.add_equity("AAPL", Resolution.HOUR).symbol
        self.gdvd = Symbol.create("GDVD", SecurityType.EQUITY, Market.USA)

        self.add_universe(self.universe.etf(self.gdvd, self.universe_settings, self.filter_etfs))

    def filter_etfs(self, constituents):
        self.universe_selection_done = True

        if self.utc_time.date() > self.delisting_date:
            raise AssertionError(f"Performing constituent universe selection on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')} after composite ETF has been delisted")

        constituent_symbols = [i.symbol for i in constituents]
        self.universe_symbol_count = len(set(constituent_symbols))

        return constituent_symbols

    def on_data(self, data):
        if self.utc_time.date() > self.delisting_date and any([i != self.aapl for i in data.keys()]):
            raise AssertionError("Received unexpected slice in OnData(...) after universe was deselected")

        if not self.portfolio.invested:
            self.set_holdings(self.aapl, 0.5)

    def on_securities_changed(self, changes):
        if len(changes.added_securities) != 0 and self.utc_time.date() > self.delisting_date:
            raise AssertionError("New securities added after ETF constituents were delisted")

        if self.universe_selection_done:
            self.universe_added = self.universe_added or len(changes.added_securities) == self.universe_symbol_count

        # TODO: shouldn't be sending AAPL as a removed security since it was added by another universe
        self.universe_removed = self.universe_removed or (
            len(changes.removed_securities) == self.universe_symbol_count and
            self.utc_time.date() >= self.delisting_date and
            self.utc_time.date() < self.end_date.date())

    def on_end_of_algorithm(self):
        if not self.universe_added:
            raise AssertionError("ETF constituent universe was never added to the algorithm")
        if not self.universe_removed:
            raise AssertionError("ETF constituent universe was not removed from the algorithm after delisting")
        if len(self.active_securities) > 2:
            raise AssertionError(f"Expected less than 2 securities after algorithm ended, found {len(self.securities)}")
```


Instruction: You are a quantive developer 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 add options for a given underlying equity security.
It also shows how you can prefilter contracts easily based on strikes and expirations.
It also shows how you can inspect the option chain to pick a specific option contract to trade.

Output:
```python

from AlgorithmImports import *

class BasicTemplateOptionsFilterUniverseAlgorithm(QCAlgorithm):
    underlying_ticker = "GOOG"

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

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

        # Set our custom universe filter
        option.set_filter(self.filter_function)

        # use the underlying equity as the benchmark
        self.set_benchmark(equity.symbol)

    def filter_function(self, universe):
        #Expires today, is a call, and is within 10 dollars of the current price
        universe = universe.weeklys_only().expiration(0, 1)
        return [symbol for symbol in universe
                if symbol.id.option_right != OptionRight.PUT
                and -10 < universe.underlying.price - symbol.id.strike_price < 10]

    def on_data(self, slice):
        if self.portfolio.invested: return

        for kvp in slice.option_chains:

            if kvp.key != self.option_symbol: continue

            # Get the first call strike under market price expiring today
            chain = kvp.value
            contracts = [option for option in sorted(chain, key = lambda x:x.strike, reverse = True)
                         if option.expiry.date() == self.time.date()
                         and option.strike < chain.underlying.price]

            if contracts:
                self.market_order(contracts[0].symbol, 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
: Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks.

Output:
```python

from AlgorithmImports import *

class CoarseFineFundamentalComboAlgorithm(QCAlgorithm):

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

        self.set_start_date(2014,1,1)  #Set Start Date
        self.set_end_date(2015,1,1)    #Set End Date
        self.set_cash(50000)            #Set Strategy Cash

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

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

        self.__number_of_symbols = 5
        self.__number_of_symbols_fine = 2
        self._changes = None

    # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
    def coarse_selection_function(self, coarse):
        # sort descending by daily dollar volume
        sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)

        # return the symbol objects of the top entries from our sorted collection
        return [ x.symbol for x in sorted_by_dollar_volume[:self.__number_of_symbols] ]

    # sort the data by P/E ratio and take the top 'NumberOfSymbolsFine'
    def fine_selection_function(self, fine):
        # sort descending by P/E ratio
        sorted_by_pe_ratio = sorted(fine, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)

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

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

        # liquidate removed securities
        for security in self._changes.removed_securities:
            if security.invested:
                self.liquidate(security.symbol)

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

        self._changes = None

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


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

Input:
Generate a LEAN Algorithm that can be described like this
: Mean Variance Optimization algorithm
Uses the HistoricalReturnsAlphaModel and the MeanVarianceOptimizationPortfolioConstructionModel
to create an algorithm that rebalances the portfolio according to modern portfolio theory

Output:
```python

from AlgorithmImports import *
from Portfolio.MeanVarianceOptimizationPortfolioConstructionModel import *

class MeanVarianceOptimizationFrameworkAlgorithm(QCAlgorithm):
    '''Mean Variance Optimization algorithm.'''

    def initialize(self):

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

        self.settings.rebalance_portfolio_on_insight_changes = False

        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._symbols = [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in [ 'AIG', 'BAC', 'IBM', 'SPY' ] ]

        # set algorithm framework models
        self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selector))
        self.set_alpha(HistoricalReturnsAlphaModel(resolution = Resolution.DAILY))
        self.set_portfolio_construction(MeanVarianceOptimizationPortfolioConstructionModel())
        self.set_execution(ImmediateExecutionModel())
        self.set_risk_management(NullRiskManagementModel())

    def coarse_selector(self, coarse):
        # Drops SPY after the 8th
        last = 3 if self.time.day > 8 else len(self._symbols)

        return self._symbols[0:last]

    def on_order_event(self,  order_event):
        if order_event.status == OrderStatus.FILLED:
            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
: Basic template algorithm for the Axos brokerage

Output:
```python

from AlgorithmImports import *

class BasicTemplateAxosAlgorithm(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.set_brokerage_model(BrokerageName.AXOS)
        self.add_equity("SPY", Resolution.MINUTE)

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

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            # will set 25% of our buying power with a market order
            self.set_holdings("SPY", 0.25)
            self.debug("Purchased 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 for testing parameterized regression algorithms get valid parameters.

Output:
```python

from AlgorithmImports import *

class GetParameterRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2013, 10, 7)
        self.check_parameter(None, self.get_parameter("non-existing"), "GetParameter(\"non-existing\")")
        self.check_parameter("100", self.get_parameter("non-existing", "100"), "GetParameter(\"non-existing\", \"100\")")
        self.check_parameter(100, self.get_parameter("non-existing", 100), "GetParameter(\"non-existing\", 100)")
        self.check_parameter(100.0, self.get_parameter("non-existing", 100.0), "GetParameter(\"non-existing\", 100.0)")

        self.check_parameter("10", self.get_parameter("ema-fast"), "GetParameter(\"ema-fast\")")
        self.check_parameter(10, self.get_parameter("ema-fast", 100), "GetParameter(\"ema-fast\", 100)")
        self.check_parameter(10.0, self.get_parameter("ema-fast", 100.0), "GetParameter(\"ema-fast\", 100.0)")

        self.quit()

    def check_parameter(self, expected, actual, call):
        if expected == None and actual != None:
            raise AssertionError(f"{call} should have returned null but returned {actual} ({type(actual)})")

        if expected != None and actual == None:
            raise AssertionError(f"{call} should have returned {expected} ({type(expected)}) but returned null")

        if expected != None and actual != None and type(expected) != type(actual) or expected != actual:
            raise AssertionError(f"{call} should have returned {expected} ({type(expected)}) but returned {actual} ({type(actual)})")
```


Instruction: You are a quantive developer 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 show casing and asserting the behavior of creating a consolidator specifying the start time

Output:
```python

from AlgorithmImports import *
from collections import deque

class ConsolidatorStartTimeRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013, 10, 4)
        self.set_end_date(2013, 10, 4)

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

        consolidator = TradeBarConsolidator(timedelta(hours=1), start_time=timedelta(hours=9, minutes=30))
        consolidator.data_consolidated += self.bar_handler
        self.subscription_manager.add_consolidator("SPY", consolidator)

        self._expectedConsolidationTime = deque()
        self._expectedConsolidationTime.append(time(14, 30))
        self._expectedConsolidationTime.append(time(13, 30))
        self._expectedConsolidationTime.append(time(12, 30))
        self._expectedConsolidationTime.append(time(11, 30))
        self._expectedConsolidationTime.append(time(10, 30))
        self._expectedConsolidationTime.append(time(9, 30))

    def bar_handler(self, _, bar):
        if self.time != bar.end_time:
            raise RegressionTestException(f"Unexpected consolidation time {bar.Time} != {Time}!")

        self.debug(f"{self.time} - Consolidation")
        expected = self._expectedConsolidationTime.pop()
        if bar.time.time() != expected:
            raise RegressionTestException(f"Unexpected consolidation time {bar.time.time()} != {expected}!")

        if bar.period != timedelta(hours=1):
            raise RegressionTestException(f"Unexpected consolidation period {bar.period}!")

    def on_end_of_algorithm(self):
        if len(self._expectedConsolidationTime) > 0:
            raise RegressionTestException("Unexpected consolidation 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
: Framework algorithm that uses the EmaCrossUniverseSelectionModel to
select the universe based on a moving average cross.

Output:
```python

from AlgorithmImports import *
from Alphas.ConstantAlphaModel import ConstantAlphaModel
from Selection.EmaCrossUniverseSelectionModel import EmaCrossUniverseSelectionModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel

class EmaCrossUniverseSelectionFrameworkAlgorithm(QCAlgorithm):
    '''Framework algorithm that uses the EmaCrossUniverseSelectionModel to select the universe based on a moving average cross.'''

    def initialize(self):

        self.set_start_date(2013,1,1)
        self.set_end_date(2015,1,1)
        self.set_cash(100000)

        fast_period = 100
        slow_period = 300
        count = 10

        self.universe_settings.leverage = 2.0
        self.universe_settings.resolution = Resolution.DAILY

        self.set_universe_selection(EmaCrossUniverseSelectionModel(fast_period, slow_period, count))
        self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1), None, None))
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
```


Instruction: You are a quantive developer 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 add options for a given underlying equity security.
It also shows how you can prefilter contracts easily based on strikes and expirations.
It also shows how you can inspect the option chain to pick a specific option contract to trade.

Output:
```python

from AlgorithmImports import *

class BasicTemplateOptionTradesAlgorithm(QCAlgorithm):

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

        option = self.add_option("GOOG")

        # add the initial contract filter
        # SetFilter method accepts timedelta objects or integer for days.
        # The following statements yield the same filtering criteria
        option.set_filter(-2, +2, 0, 10)
        # option.set_filter(-2, +2, timedelta(0), timedelta(10))

        # use the underlying equity as the benchmark
        self.set_benchmark("GOOG")

    def on_data(self,slice):
        if not self.portfolio.invested:
            for kvp in slice.option_chains:
                chain = kvp.value
                # find the second call strike under market price expiring today
                contracts = sorted(sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike)),
                                                 key = lambda x: x.expiry, reverse=False)

                if len(contracts) == 0: continue
                if contracts[0] != None:
                    self.market_order(contracts[0].symbol, 1)
        else:
            self.liquidate()

        for kpv in slice.bars:
            self.log("---> OnData: {0}, {1}, {2}".format(self.time, kpv.key.value, str(kpv.value.close)))

    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
: Example algorithm showing that Slice, Securities and Portfolio behave as a Python Dictionary

Output:
```python

from AlgorithmImports import *

class PythonDictionaryFeatureRegressionAlgorithm(QCAlgorithm):
    '''Example algorithm showing that Slice, Securities and Portfolio behave as a Python Dictionary'''

    def initialize(self):

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

        self.spy_symbol = self.add_equity("SPY").symbol
        self.ibm_symbol = self.add_equity("IBM").symbol
        self.aig_symbol = self.add_equity("AIG").symbol
        self.aapl_symbol = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)

        date_rules = self.date_rules.on(2013, 10, 7)
        self.schedule.on(date_rules, self.time_rules.at(13, 0), self.test_securities_dictionary)
        self.schedule.on(date_rules, self.time_rules.at(14, 0), self.test_portfolio_dictionary)
        self.schedule.on(date_rules, self.time_rules.at(15, 0), self.test_slice_dictionary)

    def test_slice_dictionary(self):
        slice = self.current_slice

        symbols = ', '.join([f'{x}' for x in slice.keys()])
        slice_data = ', '.join([f'{x}' for x in slice.values()])
        slice_bars = ', '.join([f'{x}' for x in slice.bars.values()])

        if "SPY" not in slice:
            raise AssertionError('SPY (string) is not in Slice')

        if self.spy_symbol not in slice:
            raise AssertionError('SPY (Symbol) is not in Slice')

        spy = slice.get(self.spy_symbol)
        if spy is None:
            raise AssertionError('SPY is not in Slice')

        for symbol, bar in slice.bars.items():
            self.plot(symbol, 'Price', bar.close)

    def test_securities_dictionary(self):
        symbols = ', '.join([f'{x}' for x in self.securities.keys()])
        leverages = ', '.join([str(x.get_last_data()) for x in self.securities.values()])

        if "IBM" not in self.securities:
            raise AssertionError('IBM (string) is not in Securities')

        if self.ibm_symbol not in self.securities:
            raise AssertionError('IBM (Symbol) is not in Securities')

        ibm = self.securities.get(self.ibm_symbol)
        if ibm is None:
            raise AssertionError('ibm is None')

        aapl = self.securities.get(self.aapl_symbol)
        if aapl is not None:
            raise AssertionError('aapl is not None')

        for symbol, security in self.securities.items():
            self.plot(symbol, 'Price', security.price)

    def test_portfolio_dictionary(self):
        symbols = ', '.join([f'{x}' for x in self.portfolio.keys()])
        leverages = ', '.join([f'{x.symbol}: {x.leverage}' for x in self.portfolio.values()])

        if "AIG" not in self.securities:
            raise AssertionError('AIG (string) is not in Portfolio')

        if self.aig_symbol not in self.securities:
            raise AssertionError('AIG (Symbol) is not in Portfolio')

        aig = self.portfolio.get(self.aig_symbol)
        if aig is None:
            raise AssertionError('aig is None')

        aapl = self.portfolio.get(self.aapl_symbol)
        if aapl is not None:
            raise AssertionError('aapl is not None')

        for symbol, holdings in self.portfolio.items():
            msg = f'{symbol}: {holdings.leverage}'

    def on_end_of_algorithm(self):

        portfolio_copy = self.portfolio.copy()
        try:
            self.portfolio.clear()  # Throws exception
        except Exception as e:
            self.debug(e)

        bar = self.securities.pop("SPY")
        length = len(self.securities)
        if length != 2:
            raise AssertionError(f'After popping SPY, Securities should have 2 elements, {length} found')

        securities_copy = self.securities.copy()
        self.securities.clear()    # Does not throw

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

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            self.set_holdings("SPY", 1/3)
            self.set_holdings("IBM", 1/3)
            self.set_holdings("AIG", 1/3)
```