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

Input:
Generate a LEAN Algorithm that can be described like this
: This regression algorithm tests Out of The Money (OTM) future option expiry for short puts.
We expect 2 orders from the algorithm, which are:

  * Initial entry, sell ES Put Option (expiring OTM)
    - Profit the option premium, since the option was not assigned.

  * Liquidation of ES put OTM contract on the last trade date

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

Output:
```python

from AlgorithmImports import *

class FutureOptionShortPutOTMExpiryRegressionAlgorithm(QCAlgorithm):

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

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

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

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

        self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)

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

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

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

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

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

        security = self.securities[order_event.symbol]
        if security.symbol == self.es19m20:
            raise AssertionError(f"Expected no order events for underlying Symbol {security.symbol}")

        if security.symbol == self.expected_contract:
            self.assert_future_option_contract_order(order_event, security)

        else:
            raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")

        self.log(f"{order_event}")

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

        if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:
            raise AssertionError("Expected no options holdings after closing position")

        if order_event.is_assignment:
            raise AssertionError(f"Assignment was not expected for {order_event.symbol}")

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


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

Input:
Generate a LEAN Algorithm that can be described like this
: # Keep new created instance of stop_market_order

Output:
```python

from AlgorithmImports import *

# <summary>
# This example demonstrates how to create future 'stop_market_order' in extended Market Hours time
# </summary>

class FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm(QCAlgorithm):
    # Keep new created instance of stop_market_order
    _stop_market_ticket = None

    # Initialize the Algorithm and Prepare Required Data
    def initialize(self) -> None:
        self.set_start_date(2013, 10, 6)
        self.set_end_date(2013, 10, 12)

        # Add mini SP500 future with extended Market hours flag
        self._sp_500_e_mini = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, extended_market_hours=True)

        # Init new schedule event with params: every_day, 19:00:00 PM, what should to do
        self.schedule.on(self.date_rules.every_day(),self.time_rules.at(19, 0),self.make_market_and_stop_market_order)

    # This method is opened 2 new orders by scheduler
    def make_market_and_stop_market_order(self) -> None:
        # Don't place orders at the end of the last date, the market-on-stop order won't have time to fill
        if self.time.date() == self.end_date.date() - timedelta(1) or  not self._sp_500_e_mini.mapped:
            return

        self.market_order(self._sp_500_e_mini.mapped, 1)
        self._stop_market_ticket = self.stop_market_order(self._sp_500_e_mini.mapped, -1, self._sp_500_e_mini.price * 1.1)

    # New Data Event handler receiving all subscription data in a single event
    def on_data(self, slice: Slice) -> None:
        if (self._stop_market_ticket == None or self._stop_market_ticket.status != OrderStatus.SUBMITTED):
            return None

        self.stop_price = self._stop_market_ticket.get(OrderField.STOP_PRICE)
        self.bar = self.securities[self._stop_market_ticket.symbol].cache.get_data()

    # An order fill update the resulting information is passed to this method.
    def on_order_event(self, order_event: OrderEvent) -> None:
        if self.transactions.get_order_by_id(order_event.order_id).type is not OrderType.STOP_MARKET:
            return None

        if order_event.status == OrderStatus.FILLED:
            # Get Exchange Hours for specific security
            exchange_hours = self.market_hours_database.get_exchange_hours(self._sp_500_e_mini.subscription_data_config)

            # Validate, Exchange is opened explicitly
            if (not exchange_hours.is_open(order_event.utc_time, self._sp_500_e_mini.is_extended_market_hours)):
                raise AssertionError("The Exchange hours was closed, verify 'extended_market_hours' flag in Initialize() when added new security(ies)")

    def on_end_of_algorithm(self) -> None:
        self.stop_market_orders = self.transactions.get_orders(lambda o: o.type is OrderType.STOP_MARKET)

        for o in self.stop_market_orders:
            if o.status != OrderStatus.FILLED:
                raise AssertionError("The Algorithms was not handled any StopMarketOrders")
```


Instruction: You are a quantive developer 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 test for history and warm up using the data available in open source.

Output:
```python

from AlgorithmImports import *

class IndicatorWarmupAlgorithm(QCAlgorithm):

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

        self.set_start_date(2013, 10, 8)   #Set Start Date
        self.set_end_date(2013, 10, 11)    #Set End Date
        self.set_cash(1000000)            #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.add_equity("SPY")
        self.add_equity("IBM")
        self.add_equity("BAC")
        self.add_equity("GOOG", Resolution.DAILY)
        self.add_equity("GOOGL", Resolution.DAILY)

        self.__sd = { }
        for security in self.securities:
            self.__sd[security.key] = self.SymbolData(security.key, self)

        # we want to warm up our algorithm
        self.set_warmup(self.SymbolData.REQUIRED_BARS_WARMUP)

    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
        '''
        # we are only using warmup for indicator spooling, so wait for us to be warm then continue
        if self.is_warming_up: return

        for sd in self.__sd.values():
            last_price_time = sd.close.current.time
            if self.round_down(last_price_time, sd.security.subscription_data_config.increment):
                sd.update()

    def on_order_event(self, fill):
        sd = self.__sd.get(fill.symbol, None)
        if sd is not None:
            sd.on_order_event(fill)

    def round_down(self, time, increment):
        if increment.days != 0:
            return time.hour == 0 and time.minute == 0 and time.second == 0
        else:
            return time.second == 0

    class SymbolData:
        REQUIRED_BARS_WARMUP = 40
        PERCENT_TOLERANCE = 0.001
        PERCENT_GLOBAL_STOP_LOSS = 0.01
        LOT_SIZE = 10

        def __init__(self, symbol, algorithm):
            self.symbol = symbol
            self.__algorithm = algorithm   # if we're receiving daily

            self.__current_stop_loss = None

            self.security = algorithm.securities[symbol]
            self.close = algorithm.identity(symbol)
            self._adx = algorithm.adx(symbol, 14)
            self._ema = algorithm.ema(symbol, 14)
            self._macd = algorithm.macd(symbol, 12, 26, 9)

            self.is_ready = self.close.is_ready and self._adx.is_ready and self._ema.is_ready and self._macd.is_ready
            self.is_uptrend = False
            self.is_downtrend = False

        def update(self):
            self.is_ready = self.close.is_ready and self._adx.is_ready and self._ema.is_ready and self._macd.is_ready

            tolerance = 1 - self.PERCENT_TOLERANCE
            self.is_uptrend = self._macd.signal.current.value > self._macd.current.value * tolerance and\
                self._ema.current.value > self.close.current.value * tolerance

            self.is_downtrend = self._macd.signal.current.value < self._macd.current.value * tolerance and\
                self._ema.current.value < self.close.current.value * tolerance

            self.try_enter()
            self.try_exit()

        def try_enter(self):
            # can't enter if we're already in
            if self.security.invested: return False

            qty = 0
            limit = 0.0

            if self.is_uptrend:
                # 100 order lots
                qty = self.LOT_SIZE
                limit = self.security.low
            elif self.is_downtrend:
                qty = -self.LOT_SIZE
                limit = self.security.high

            if qty != 0:
                ticket = self.__algorithm.limit_order(self.symbol, qty, limit, tag="TryEnter at: {0}".format(limit))

        def try_exit(self):
            # can't exit if we haven't entered
            if not self.security.invested: return

            limit = 0
            qty = self.security.holdings.quantity
            exit_tolerance = 1 + 2 * self.PERCENT_TOLERANCE
            if self.security.holdings.is_long and self.close.current.value * exit_tolerance < self._ema.current.value:
                limit = self.security.high
            elif self.security.holdings.is_short and self.close.current.value > self._ema.current.value * exit_tolerance:
                limit = self.security.low

            if limit != 0:
                ticket = self.__algorithm.limit_order(self.symbol, -qty, limit, tag="TryExit at: {0}".format(limit))

        def on_order_event(self, fill):
            if fill.status != OrderStatus.FILLED: return

            qty = self.security.holdings.quantity

            # if we just finished entering, place a stop loss as well
            if self.security.invested:
                stop = fill.fill_price*(1 - self.PERCENT_GLOBAL_STOP_LOSS) if self.security.holdings.is_long \
                    else fill.fill_price*(1 + self.PERCENT_GLOBAL_STOP_LOSS)

                self.__current_stop_loss = self.__algorithm.stop_market_order(self.symbol, -qty, stop, tag="StopLoss at: {0}".format(stop))

            # check for an exit, cancel the stop loss
            elif (self.__current_stop_loss is not None and self.__current_stop_loss.status is not OrderStatus.FILLED):
                # cancel our current stop loss
                self.__current_stop_loss.cancel("Exited position")
                self.__current_stop_loss = None
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: In this algorithm we demonstrate how to use the coarse fundamental data to define a universe as the top dollar volume and set the algorithm to use raw prices

Output:
```python

from AlgorithmImports import *

class RawPricesCoarseUniverseAlgorithm(QCAlgorithm):

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

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

        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

        # Set the security initializer with the characteristics defined in CustomSecurityInitializer
        self.set_security_initializer(self.custom_security_initializer)

        # this add universe method accepts a single parameter that is a function that
        # accepts an IEnumerable<CoarseFundamental> and returns IEnumerable<Symbol>
        self.add_universe(self.coarse_selection_function)

        self.__number_of_symbols = 5

    def custom_security_initializer(self, security):
        '''Initialize the security with raw prices and zero fees
        Args:
            security: Security which characteristics we want to change'''
        security.set_data_normalization_mode(DataNormalizationMode.RAW)
        security.set_fee_model(ConstantFeeModel(0))

    # 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] ]

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

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

    def on_order_event(self, order_event):
        if order_event.status == OrderStatus.FILLED:
            self.log(f"OnOrderEvent({self.utc_time}):: {order_event}")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm to assert the behavior of <see cref="MaximumDrawdownPercentPortfolio"/>.

Output:
```python

from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Risk.CompositeRiskManagementModel import CompositeRiskManagementModel
from Risk.MaximumDrawdownPercentPortfolio import MaximumDrawdownPercentPortfolio

class MaximumDrawdownPercentPortfolioFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):

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

        # define risk management model as a composite of several risk management models
        self.set_risk_management(CompositeRiskManagementModel(
            MaximumDrawdownPercentPortfolio(0.01),         # Avoid loss of initial capital
            MaximumDrawdownPercentPortfolio(0.015, True)   # Avoid profit losses
            ))
```


Instruction: You are a quantive developer 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 ScheduledUniverseSelectionModel scheduling functions.

Output:
```python

from AlgorithmImports import *

class ScheduledUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):
    '''Regression algorithm for testing ScheduledUniverseSelectionModel scheduling functions.'''

    def initialize(self):

        self.universe_settings.resolution = Resolution.HOUR

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

        self.set_start_date(2017, 1, 1)
        self.set_end_date(2017, 2, 1)

        # selection will run on mon/tues/thurs at 00:00/06:00/12:00/18:00
        self.set_universe_selection(ScheduledUniverseSelectionModel(
            self.date_rules.every(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.THURSDAY),
            self.time_rules.every(timedelta(hours = 12)),
            self.select_symbols
            ))

        self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())

        # some days of the week have different behavior the first time -- less securities to remove
        self.seen_days = []

    def select_symbols(self, dateTime):

        symbols = []
        weekday = dateTime.weekday()

        if weekday == 0 or weekday == 1:
            symbols.append(Symbol.create('SPY', SecurityType.EQUITY, Market.USA))
        elif weekday == 2:
            # given the date/time rules specified in Initialize, this symbol will never be selected (not invoked on wednesdays)
            symbols.append(Symbol.create('AAPL', SecurityType.EQUITY, Market.USA))
        else:
            symbols.append(Symbol.create('IBM', SecurityType.EQUITY, Market.USA))

        if weekday == 1 or weekday == 3:
            symbols.append(Symbol.create('EURUSD', SecurityType.FOREX, Market.OANDA))
        elif weekday == 4:
            # given the date/time rules specified in Initialize, this symbol will never be selected (every 6 hours never lands on hour==1)
            symbols.append(Symbol.create('EURGBP', SecurityType.FOREX, Market.OANDA))
        else:
            symbols.append(Symbol.create('NZDUSD', SecurityType.FOREX, Market.OANDA))

        return symbols

    def on_securities_changed(self, changes):
        self.log("{}: {}".format(self.time, changes))

        weekday = self.time.weekday()

        if weekday == 0:
            self.expect_additions(changes, 'SPY', 'NZDUSD')
            if weekday not in self.seen_days:
                self.seen_days.append(weekday)
                self.expect_removals(changes, None)
            else:
                self.expect_removals(changes, 'EURUSD', 'IBM')

        if weekday == 1:
            self.expect_additions(changes, 'EURUSD')
            if weekday not in self.seen_days:
                self.seen_days.append(weekday)
                self.expect_removals(changes, 'NZDUSD')
            else:
                self.expect_removals(changes, 'NZDUSD')

        if weekday == 2 or weekday == 4:
            # selection function not invoked on wednesdays (2) or friday (4)
            self.expect_additions(changes, None)
            self.expect_removals(changes, None)

        if weekday == 3:
            self.expect_additions(changes, "IBM")
            self.expect_removals(changes, "SPY")

    def on_order_event(self, orderEvent):
        self.log("{}: {}".format(self.time, orderEvent))

    def expect_additions(self, changes, *tickers):
        if tickers is None and changes.added_securities.count > 0:
            raise AssertionError("{}: Expected no additions: {}".format(self.time, self.time.weekday()))

        for ticker in tickers:
            if ticker is not None and ticker not in [s.symbol.value for s in changes.added_securities]:
                raise AssertionError("{}: Expected {} to be added: {}".format(self.time, ticker, self.time.weekday()))

    def expect_removals(self, changes, *tickers):
        if tickers is None and changes.removed_securities.count > 0:
            raise AssertionError("{}: Expected no removals: {}".format(self.time, self.time.weekday()))

        for ticker in tickers:
            if ticker is not None and ticker not in [s.symbol.value for s in changes.removed_securities]:
                raise AssertionError("{}: Expected {} to be removed: {}".format(self.time, ticker, self.time.weekday()))
```


Instruction: You are a quantive developer 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 requesting daily resolution data for US Equities.
This is a simple regression test algorithm using a skeleton algorithm and requesting daily data.

Output:
```python

from AlgorithmImports import *

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

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

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            self.set_holdings("SPY", 1)
            self.debug("Purchased Stock")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration of the Option Chain Provider -- a much faster mechanism for manually specifying the option contracts you'd like to recieve
data for and manually subscribing to them.

Output:
```python

from AlgorithmImports import *

class OptionChainProviderAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2015, 12, 24)
        self.set_end_date(2015, 12, 24)
        self.set_cash(100000)
        # add the underlying asset
        self.equity = self.add_equity("GOOG", Resolution.MINUTE)
        self.equity.set_data_normalization_mode(DataNormalizationMode.RAW)
        # initialize the option contract with empty string
        self.contract = str()
        self.contracts_added = set()

    def on_data(self, data):

        if not self.portfolio[self.equity.symbol].invested:
            self.market_order(self.equity.symbol, 100)

        if not (self.securities.contains_key(self.contract) and self.portfolio[self.contract].invested):
            self.contract = self.options_filter(data)

        if self.securities.contains_key(self.contract) and not self.portfolio[self.contract].invested:
            self.market_order(self.contract, -1)

    def options_filter(self, data):
        ''' OptionChainProvider gets a list of option contracts for an underlying symbol at requested date.
            Then you can manually filter the contract list returned by GetOptionContractList.
            The manual filtering will be limited to the information included in the Symbol
            (strike, expiration, type, style) and/or prices from a History call '''

        contracts = self.option_chain_provider.get_option_contract_list(self.equity.symbol, data.time)
        self.underlying_price = self.securities[self.equity.symbol].price
        # filter the out-of-money call options from the contract list which expire in 10 to 30 days from now on
        otm_calls = [i for i in contracts if i.id.option_right == OptionRight.CALL and
                                            i.id.strike_price - self.underlying_price > 0 and
                                            10 < (i.id.date - data.time).days < 30]
        if len(otm_calls) > 0:
            contract = sorted(sorted(otm_calls, key = lambda x: x.id.date),
                                                     key = lambda x: x.id.strike_price - self.underlying_price)[0]
            if contract not in self.contracts_added:
                self.contracts_added.add(contract)
                # use AddOptionContract() to subscribe the data for specified contract
                self.add_option_contract(contract, Resolution.MINUTE)
            return contract
        else:
            return str()
```


Instruction: You are a quantive developer 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 option exercise and assignment functionality
We open two positions and go with them into expiration. We expect to see our long position exercised and short position assigned.

Output:
```python

from AlgorithmImports import *

class OptionExerciseAssignRegressionAlgorithm(QCAlgorithm):

    underlying_ticker = "GOOG"

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

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

        # set our strike/expiry filter for this option chain
        self.option.set_filter(self.universe_func)

        self.set_benchmark(self.equity.symbol)
        self._assigned_option = False

    def on_data(self, slice):
        if self.portfolio.invested: return
        for kvp in slice.option_chains:
            chain = kvp.value
            # find the call options expiring today
            contracts = filter(lambda x:
                               x.expiry.date() == self.time.date() and
                               x.strike < chain.underlying.price and
                               x.right == OptionRight.CALL, chain)

            # sorted the contracts by their strikes, find the second strike under market price
            sorted_contracts = sorted(contracts, key = lambda x: x.strike, reverse = True)[:2]

            if sorted_contracts:
                self.market_order(sorted_contracts[0].symbol, 1)
                self.market_order(sorted_contracts[1].symbol, -1)

    # set our strike/expiry filter for this option chain
    def universe_func(self, universe):
        return universe.include_weeklys().strikes(-2, 2).expiration(timedelta(0), timedelta(10))

    def on_order_event(self, order_event):
        self.log(str(order_event))

    def on_assignment_order_event(self, assignment_event):
        self.log(str(assignment_event))
        self._assigned_option = 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
: Algorithm asserting the correct values for the deployment target and algorithm mode.

Output:
```python

from AlgorithmImports import *

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

        #translate commented code from c# to python
        self.debug(f"Algorithm Mode: {self.algorithm_mode}. Is Live Mode: {self.live_mode}. Deployment Target: {self.deployment_target}.")

        if self.algorithm_mode != AlgorithmMode.BACKTESTING:
            raise AssertionError(f"Algorithm mode is not backtesting. Actual: {self.algorithm_mode}")

        if self.live_mode:
            raise AssertionError("Algorithm should not be live")

        if self.deployment_target != DeploymentTarget.LOCAL_PLATFORM:
            raise AssertionError(f"Algorithm deployment target is not local. Actual{self.deployment_target}")

        # For a live deployment these checks should pass:
        # if self.algorithm_mode != AlgorithmMode.LIVE: raise AssertionError("Algorithm mode is not live")
        # if not self.live_mode: raise AssertionError("Algorithm should be live")

        # For a cloud deployment these checks should pass:
        # if self.deployment_target != DeploymentTarget.CLOUD_PLATFORM: raise AssertionError("Algorithm deployment target is not cloud")

        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
: Basic template options framework algorithm uses framework components
to define an algorithm that trades options.

Output:
```python

from AlgorithmImports import *

from Alphas.ConstantAlphaModel import ConstantAlphaModel
from Selection.OptionUniverseSelectionModel import OptionUniverseSelectionModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from Risk.NullRiskManagementModel import NullRiskManagementModel

class BasicTemplateOptionsFrameworkAlgorithm(QCAlgorithm):

    def initialize(self):
        self.universe_settings.resolution = Resolution.MINUTE

        self.set_start_date(2014, 6, 5)
        self.set_end_date(2014, 6, 9)
        self.set_cash(100000)

        # set framework models
        self.set_universe_selection(EarliestExpiringWeeklyAtTheMoneyPutOptionUniverseSelectionModel(self.select_option_chain_symbols))
        self.set_alpha(ConstantOptionContractAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(hours = 0.5)))
        self.set_portfolio_construction(SingleSharePortfolioConstructionModel())
        self.set_execution(ImmediateExecutionModel())
        self.set_risk_management(NullRiskManagementModel())

    def select_option_chain_symbols(self, utc_time):
        new_york_time = Extensions.convert_from_utc(utc_time, TimeZones.NEW_YORK)
        ticker = "TWX" if new_york_time.date() < date(2014, 6, 6) else "AAPL"
        return [ Symbol.create(ticker, SecurityType.OPTION, Market.USA, f"?{ticker}") ]

class EarliestExpiringWeeklyAtTheMoneyPutOptionUniverseSelectionModel(OptionUniverseSelectionModel):
    '''Creates option chain universes that select only the earliest expiry ATM weekly put contract
    and runs a user defined option_chain_symbol_selector every day to enable choosing different option chains'''
    def __init__(self, select_option_chain_symbols):
        super().__init__(timedelta(1), select_option_chain_symbols)

    def filter(self, filter):
        '''Defines the option chain universe filter'''
        return (filter.strikes(+1, +1)
                      # Expiration method accepts timedelta objects or integer for days.
                      # The following statements yield the same filtering criteria
                      .expiration(0, 7)
                      # .expiration(timedelta(0), timedelta(7))
                      .weeklys_only()
                      .puts_only()
                      .only_apply_filter_at_market_open())

class ConstantOptionContractAlphaModel(ConstantAlphaModel):
    '''Implementation of a constant alpha model that only emits insights for option symbols'''
    def __init__(self, type, direction, period):
        super().__init__(type, direction, period)

    def should_emit_insight(self, utc_time, symbol):
        # only emit alpha for option symbols and not underlying equity symbols
        if symbol.security_type != SecurityType.OPTION:
            return False

        return super().should_emit_insight(utc_time, symbol)

class SingleSharePortfolioConstructionModel(PortfolioConstructionModel):
    '''Portfolio construction model that sets target quantities to 1 for up insights and -1 for down insights'''
    def create_targets(self, algorithm, insights):
        targets = []
        for insight in insights:
            targets.append(PortfolioTarget(insight.symbol, insight.direction))
        return targets
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Live Trading Functionality Demonstration algorithm including SMS, Email and Web hook notifications.

Output:
```python

from AlgorithmImports import *

class LiveTradingFeaturesAlgorithm(QCAlgorithm):

    ### Initialize the Algorithm and Prepare Required Data
    def initialize(self):

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

        ##Equity Data for US Markets
        self.add_security(SecurityType.EQUITY, 'IBM', Resolution.SECOND)

        ##FOREX Data for Weekends: 24/6
        self.add_security(SecurityType.FOREX, 'EURUSD', Resolution.MINUTE)

        ##Custom/Bitcoin Live Data: 24/7
        self.add_data(Bitcoin, 'BTC', Resolution.SECOND, TimeZones.UTC)

        ##if the algorithm is connected to the brokerage
        self.is_connected = True

    ### Raises the data event
    def on_data(self, data):
        if (not self.portfolio['IBM'].hold_stock) and data.contains_key('IBM'):
            quantity = int(np.floor(self.portfolio.margin_remaining / data['IBM'].close))
            self.market_order('IBM',quantity)
            self.debug('Purchased IBM on ' + str(self.time.strftime("%m/%d/%Y")))
            self.notify.email("myemail@gmail.com", "Test", "Test Body", "test attachment")

        if "BTC" in data:
            btcData = data['BTC']
            if self.live_mode:
                self.set_runtime_statistic('BTC', str(btcData.close))

            if not self.portfolio.hold_stock:
                self.market_order('BTC', 100)

                ##Send a notification email/SMS/web request on events:
                self.notify.email("myemail@gmail.com", "Test", "Test Body", "test attachment")
                self.notify.sms("+11233456789", str(btcData.time) + ">> Test message from live BTC server.")
                self.notify.web("http://api.quantconnect.com", str(btcData.time) + ">> Test data packet posted from live BTC server.")
                self.notify.ftp("ftp.quantconnect.com", "username", "password", "path/to/file.txt",
                                str(btcData.time) + ">> Test file from live BTC server.")
                self.notify.sftp("ftp.quantconnect.com", "username", "password", "path/to/file.txt",
                                 str(btcData.time) + ">> Test file from live BTC server.")
                self.notify.sftp("ftp.quantconnect.com", "username", "privatekey", "optionalprivatekeypassphrase", "path/to/file.txt",
                                 str(btcData.time) + ">> Test file from live BTC server.")

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

    # Brokerage disconnected event handler. This method is called when the brokerage connection is lost.
    def on_brokerage_disconnect(self):
        self.is_connected = False
        self.debug(f"Brokerage disconnected!")

    # Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.
    def on_brokerage_reconnect(self):
        self.is_connected = True
        self.debug(f"Brokerage reconnected!")

class Bitcoin(PythonData):

    def get_source(self, config, date, is_live_mode):
        if is_live_mode:
            return SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.REST)

        return SubscriptionDataSource("https://www.quandl.com/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc", SubscriptionTransportMedium.REMOTE_FILE)

    def reader(self, config, line, date, is_live_mode):
        coin = Bitcoin()
        coin.symbol = config.symbol

        if is_live_mode:
            # Example Line Format:
            # {"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}
            try:
                live_btc = json.loads(line)

                # If value is zero, return None
                value = live_btc["last"]
                if value == 0: return None

                coin.time = datetime.now()
                coin.value = value
                coin["Open"] = float(live_btc["open"])
                coin["High"] = float(live_btc["high"])
                coin["Low"] = float(live_btc["low"])
                coin["Close"] = float(live_btc["last"])
                coin["Ask"] = float(live_btc["ask"])
                coin["Bid"] = float(live_btc["bid"])
                coin["VolumeBTC"] = float(live_btc["volume"])
                coin["WeightedPrice"] = float(live_btc["vwap"])
                return coin
            except ValueError:
                # Do nothing, possible error in json decoding
                return None

        # Example Line Format:
        # Date      Open   High    Low     Close   Volume (BTC)    Volume (Currency)   Weighted Price
        # 2011-09-13 5.8    6.0     5.65    5.97    58.37138238,    346.0973893944      5.929230648356
        if not (line.strip() and line[0].isdigit()): return None

        try:
            data = line.split(',')
            coin.time = datetime.strptime(data[0], "%Y-%m-%d")
            coin.value = float(data[4])
            coin["Open"] = float(data[1])
            coin["High"] = float(data[2])
            coin["Low"] = float(data[3])
            coin["Close"] = float(data[4])
            coin["VolumeBTC"] = float(data[5])
            coin["VolumeUSD"] = float(data[6])
            coin["WeightedPrice"] = float(data[7])
            return coin

        except ValueError:
            # Do nothing, possible error in json decoding
            return None
```


Instruction: You are a quantive developer 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 a custom filter function when creating an ETF constituents universe for SPY

Output:
```python

from AlgorithmImports import *

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

        self.filtered = False
        self.securities_changed = False
        self.received_data = False
        self.etf_constituent_data = {}
        self.etf_rebalanced = False
        self.rebalance_count = 0
        self.rebalance_asset_count = 0

        self.universe_settings.resolution = Resolution.HOUR

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

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

    def filter_etfs(self, constituents):
        constituents_data = list(constituents)
        constituents_symbols = [i.symbol for i in constituents_data]
        self.etf_constituent_data = {i.symbol: i for i in constituents_data}

        if len(constituents_data) == 0:
            raise AssertionError(f"Constituents collection is empty on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')}")
        if self.aapl not in constituents_symbols:
            raise AssertionError("AAPL is not int he constituents data provided to the algorithm")

        aapl_data = [i for i in constituents_data if i.symbol == self.aapl][0]
        if aapl_data.weight == 0.0:
            raise AssertionError("AAPL weight is expected to be a non-zero value")

        self.filtered = True
        self.etf_rebalanced = True

        return constituents_symbols

    def on_data(self, data):
        if not self.filtered and len(data.bars) != 0 and self.aapl in data.bars:
            raise AssertionError("AAPL TradeBar data added to algorithm before constituent universe selection took place")

        if len(data.bars) == 1 and self.spy in data.bars:
            return

        if len(data.bars) != 0 and self.aapl not in data.bars:
            raise AssertionError(f"Expected AAPL TradeBar data on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')}")

        self.received_data = True

        if not self.etf_rebalanced:
            return

        for bar in data.bars.values():
            constituent_data = self.etf_constituent_data.get(bar.symbol)
            if constituent_data is not None and constituent_data.weight is not None and constituent_data.weight >= 0.0001:
                # If the weight of the constituent is less than 1%, then it will be set to 1%
                # If the weight of the constituent exceeds more than 5%, then it will be capped to 5%
                # Otherwise, if the weight falls in between, then we use that value.
                bounded_weight = max(0.01, min(constituent_data.weight, 0.05))

                self.set_holdings(bar.symbol, bounded_weight)

                if self.etf_rebalanced:
                    self.rebalance_count += 1

                self.etf_rebalanced = False
                self.rebalance_asset_count += 1

    def on_securities_changed(self, changes):
        if self.filtered and not self.securities_changed and len(changes.added_securities) < 500:
            raise AssertionError(f"Added SPY S&P 500 ETF to algorithm, but less than 500 equities were loaded (added {len(changes.added_securities)} securities)")

        self.securities_changed = True

    def on_end_of_algorithm(self):
        if self.rebalance_count != 2:
            raise AssertionError(f"Expected 2 rebalance, instead rebalanced: {self.rebalance_count}")

        if self.rebalance_asset_count != 8:
            raise AssertionError(f"Invested in {self.rebalance_asset_count} assets (expected 8)")

        if not self.filtered:
            raise AssertionError("Universe selection was never triggered")

        if not self.securities_changed:
            raise AssertionError("Security changes never propagated to the algorithm")

        if not self.received_data:
            raise AssertionError("Data was never loaded for the S&P 500 constituent AAPL")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Provides an example where WarmUpIndicator method is used to warm up indicators

Output:
```python

from AlgorithmImports import *

class SmaCrossUniverseSelectionAlgorithm(QCAlgorithm):
    '''Provides an example where WarmUpIndicator method is used to warm up indicators
    after their security is added and before (Universe Selection scenario)'''

    _count = 10
    _tolerance = 0.01
    _target_percent = 1 / _count
    _averages = dict()

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

        self.set_start_date(2018, 1, 1)
        self.set_end_date(2019, 1, 1)
        self.set_cash(1000000)

        self.settings.automatic_indicator_warm_up = True

        ibm = self.add_equity("IBM", Resolution.HOUR).symbol
        ibm_sma = self.sma(ibm, 40)
        self.log(f"{ibm_sma.name}: {ibm_sma.current.time} - {ibm_sma}. IsReady? {ibm_sma.is_ready}")

        spy = self.add_equity("SPY", Resolution.HOUR).symbol
        spy_sma = self.sma(spy, 10)     # Data point indicator
        spy_atr = self.atr(spy, 10,)    # Bar indicator
        spy_vwap = self.vwap(spy, 10)   # TradeBar indicator
        self.log(f"SPY    - Is ready? SMA: {spy_sma.is_ready}, ATR: {spy_atr.is_ready}, VWAP: {spy_vwap.is_ready}")

        eur = self.add_forex("EURUSD", Resolution.HOUR).symbol
        eur_sma = self.sma(eur, 20, Resolution.DAILY)
        eur_atr = self.atr(eur, 20, MovingAverageType.SIMPLE, Resolution.DAILY)
        self.log(f"EURUSD - Is ready? SMA: {eur_sma.is_ready}, ATR: {eur_atr.is_ready}")

        self.add_universe(self.coarse_sma_selector)

        # Since the indicators are ready, we will receive error messages
        # reporting that the algorithm manager is trying to add old information
        self.set_warm_up(10)

    def coarse_sma_selector(self, coarse: list[Fundamental]) -> list[Symbol]:
        score = dict()
        for cf in coarse:
            if not cf.has_fundamental_data:
               continue
            symbol = cf.symbol
            price = cf.adjusted_price
            # grab the SMA instance for this symbol
            avg = self._averages.setdefault(symbol, SimpleMovingAverage(100))
            self.warm_up_indicator(symbol, avg, Resolution.DAILY)
            # Update returns true when the indicators are ready, so don't accept until they are
            if avg.update(cf.end_time, price):
               value = avg.current.value
               # only pick symbols who have their price over their 100 day sma
               if value > price * self._tolerance:
                    score[symbol] = (value - price) / ((value + price) / 2)

        # prefer symbols with a larger delta by percentage between the two _averages
        sorted_score = sorted(score.items(), key=lambda kvp: kvp[1], reverse=True)
        return [x[0] for x in sorted_score[:self._count]]

    def on_securities_changed(self, changes: SecurityChanges) -> None:
        for security in changes.removed_securities:
            if security.invested:
                self.liquidate(security.symbol)

        for security in changes.added_securities:
            self.set_holdings(security.symbol, self._target_percent)
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting we can specify a custom security data filter

Output:
```python

from AlgorithmImports import *

class CustomSecurityDataFilterRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_cash(2500000)
        self.set_start_date(2013,10,7)
        self.set_end_date(2013,10,7)

        security = self.add_security(SecurityType.EQUITY, "SPY")
        security.set_data_filter(CustomDataFilter())
        self.data_points = 0

    def on_data(self, data):
        self.data_points += 1
        self.set_holdings("SPY", 0.2)
        if self.data_points > 5:
            raise AssertionError("There should not be more than 5 data points, but there were " + str(self.data_points))

class CustomDataFilter(SecurityDataFilter):
    def filter(self, vehicle: Security, data: BaseData) -> bool:
        """
        Skip data after 9:35am
        """
        if data.time >= datetime(2013,10,7,9,35,0):
            return False
        else:
            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
: This demonstration imports indian NSE index "NIFTY" as a tradable security in addition to the USDINR currency pair. We move into the
NSE market when the economy is performing well.

Output:
```python

from AlgorithmImports import *

class CustomDataNIFTYAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2008, 1, 8)
        self.set_end_date(2014, 7, 25)
        self.set_cash(100000)

        # Define the symbol and "type" of our generic data:
        rupee = self.add_data(DollarRupee, "USDINR", Resolution.DAILY).symbol
        nifty = self.add_data(Nifty, "NIFTY", Resolution.DAILY).symbol

        self.settings.automatic_indicator_warm_up = True
        rupee_sma = self.sma(rupee, 20)
        nifty_sma = self.sma(rupee, 20)
        self.log(f"SMA - Is ready? USDINR: {rupee_sma.is_ready} NIFTY: {nifty_sma.is_ready}")

        self.minimum_correlation_history = 50
        self.today = CorrelationPair()
        self.prices = []

    def on_data(self, data):
        if data.contains_key("USDINR"):
            self.today = CorrelationPair(self.time)
            self.today.currency_price = data["USDINR"].close

        if not data.contains_key("NIFTY"): return

        self.today.nifty_price = data["NIFTY"].close

        if self.today.date() == data["NIFTY"].time.date():
            self.prices.append(self.today)
            if len(self.prices) > self.minimum_correlation_history:
                self.prices.pop(0)

        # Strategy
        if self.time.weekday() != 2: return

        cur_qnty = self.portfolio["NIFTY"].quantity
        quantity = int(self.portfolio.margin_remaining * 0.9 / data["NIFTY"].close)
        hi_nifty = max(price.nifty_price for price in self.prices)
        lo_nifty = min(price.nifty_price for price in self.prices)

        if data["NIFTY"].open >= hi_nifty:
            code = self.order("NIFTY",  quantity - cur_qnty)
            self.debug("LONG  {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}".format(code, self.time, quantity, self.portfolio["NIFTY"].quantity, data["NIFTY"].close, self.portfolio.total_portfolio_value))
        elif data["NIFTY"].open <= lo_nifty:
            code = self.order("NIFTY", -quantity - cur_qnty)
            self.debug("SHORT {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}".format(code, self.time, quantity, self.portfolio["NIFTY"].quantity, data["NIFTY"].close, self.portfolio.total_portfolio_value))

class Nifty(PythonData):
    '''NIFTY Custom Data Class'''
    def get_source(self, config, date, is_live_mode):
        return SubscriptionDataSource("https://www.dropbox.com/s/rsmg44jr6wexn2h/CNXNIFTY.csv?dl=1", SubscriptionTransportMedium.REMOTE_FILE)

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

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

        try:
            # Example File Format:
            # Date,       Open       High        Low       Close     Volume      Turnover
            # 2011-09-13  7792.9    7799.9     7722.65    7748.7    116534670    6107.78
            data = line.split(',')
            index.time = datetime.strptime(data[0], "%Y-%m-%d")
            index.end_time = index.time + timedelta(days=1)
            index.value = data[4]
            index["Open"] = float(data[1])
            index["High"] = float(data[2])
            index["Low"] = float(data[3])
            index["Close"] = float(data[4])

        except ValueError:
                # Do nothing
                return None

        return index

class DollarRupee(PythonData):
    '''Dollar Rupe is a custom data type we create for this algorithm'''
    def get_source(self, config, date, is_live_mode):
        return SubscriptionDataSource("https://www.dropbox.com/s/m6ecmkg9aijwzy2/USDINR.csv?dl=1", SubscriptionTransportMedium.REMOTE_FILE)

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

        # New USDINR object
        currency = DollarRupee()
        currency.symbol = config.symbol

        try:
            data = line.split(',')
            currency.time = datetime.strptime(data[0], "%Y-%m-%d")
            currency.end_time = currency.time + timedelta(days=1)
            currency.value = data[1]
            currency["Close"] = float(data[1])

        except ValueError:
            # Do nothing
            return None

        return currency

class CorrelationPair:
    '''Correlation Pair is a helper class to combine two data points which we'll use to perform the correlation.'''
    def __init__(self, *args):
        self.nifty_price = 0        # Nifty price for this correlation pair
        self.currency_price = 0     # Currency price for this correlation pair
        self._date = datetime.min    # Date of the correlation pair
        if len(args) > 0: self._date = args[0]

    def date(self):
        return self._date.date()
```


Instruction: You are a quantive developer 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 ad asserting security to symbol implicit conversion

Output:
```python

from AlgorithmImports import *

class SecurityToSymbolRegressionAlgorithm(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)

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

        self.schedule.on(self.date_rules.every_day(asset), self.time_rules.after_market_open(asset, 1), lambda: None if self.portfolio.invested else self.set_holdings(asset, 1))
```


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

Input:
Generate a LEAN AlphaModel that can be described like this
:  Alpha Streams: Benchmark Alpha: Pick stocks according to Joel Greenblatt's Magic Formula

Output:
```python

from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel

from math import ceil
from itertools import chain

class GreenblattMagicFormulaAlpha(QCAlgorithm):
    ''' Alpha Streams: Benchmark Alpha: Pick stocks according to Joel Greenblatt's Magic Formula
    This alpha picks stocks according to Joel Greenblatt's Magic Formula.
    First, each stock is ranked depending on the relative value of the ratio EV/EBITDA. For example, a stock
    that has the lowest EV/EBITDA ratio in the security universe receives a score of one while a stock that has
    the tenth lowest EV/EBITDA score would be assigned 10 points.

    Then, each stock is ranked and given a score for the second valuation ratio, Return on Capital (ROC).
    Similarly, a stock that has the highest ROC value in the universe gets one score point.
    The stocks that receive the lowest combined score are chosen for insights.

    Source: Greenblatt, J. (2010) The Little Book That Beats the Market

    This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
    sourced so the community and client funds can see an example of an alpha.'''

    def initialize(self):

        self.set_start_date(2018, 1, 1)
        self.set_cash(100000)

        #Set zero transaction fees
        self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))

        # select stocks using MagicFormulaUniverseSelectionModel
        self.set_universe_selection(GreenBlattMagicFormulaUniverseSelectionModel())

        # Use MagicFormulaAlphaModel to establish insights
        self.set_alpha(RateOfChangeAlphaModel())

        # Equally weigh securities in portfolio, based on insights
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())

        ## Set Immediate Execution Model
        self.set_execution(ImmediateExecutionModel())

        ## Set Null Risk Management Model
        self.set_risk_management(NullRiskManagementModel())

class RateOfChangeAlphaModel(AlphaModel):
    '''Uses Rate of Change (ROC) to create magnitude prediction for insights.'''

    def __init__(self, *args, **kwargs):
        self.lookback = kwargs.get('lookback', 1)
        self.resolution = kwargs.get('resolution', Resolution.DAILY)
        self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), self.lookback)
        self._symbol_data_by_symbol = {}

    def update(self, algorithm, data):
        insights = []
        for symbol, symbol_data in self._symbol_data_by_symbol.items():
            if symbol_data.can_emit:
                insights.append(Insight.price(symbol, self.prediction_interval, InsightDirection.UP, symbol_data.returns, None))
        return insights

    def on_securities_changed(self, algorithm, changes):

        # clean up data for removed securities
        for removed in changes.removed_securities:
            symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)
            if symbol_data is not None:
                symbol_data.remove_consolidators(algorithm)

        # initialize data for added securities
        symbols = [ x.symbol for x in changes.added_securities
            if x.symbol not in self._symbol_data_by_symbol]

        history = algorithm.history(symbols, self.lookback, self.resolution)
        if history.empty: return

        for symbol in symbols:
            symbol_data = SymbolData(algorithm, symbol, self.lookback, self.resolution)
            self._symbol_data_by_symbol[symbol] = symbol_data
            symbol_data.warm_up_indicators(history.loc[symbol])

class SymbolData:
    '''Contains data specific to a symbol required by this model'''
    def __init__(self, algorithm, symbol, lookback, resolution):
        self.previous = 0
        self._symbol = symbol
        self.roc = RateOfChange(f'{symbol}.roc({lookback})', lookback)
        self.consolidator = algorithm.resolve_consolidator(symbol, resolution)
        algorithm.register_indicator(symbol, self.roc, self.consolidator)

    def remove_consolidators(self, algorithm):
        algorithm.subscription_manager.remove_consolidator(self._symbol, self.consolidator)

    def warm_up_indicators(self, history):
        for tuple in history.itertuples():
            self.roc.update(tuple.Index, tuple.close)

    @property
    def returns(self):
        return self.roc.current.value

    @property
    def can_emit(self):
        if self.previous == self.roc.samples:
            return False

        self.previous = self.roc.samples
        return self.roc.is_ready

    def __str__(self, **kwargs):
        return f'{self.roc.name}: {(1 + self.returns)**252 - 1:.2%}'

class GreenBlattMagicFormulaUniverseSelectionModel(FundamentalUniverseSelectionModel):
    '''Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm.
       From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on Assets (ROA).
    '''

    def __init__(self,
                 filter_fine_data = True,
                 universe_settings = None):
        '''Initializes a new default instance of the MagicFormulaUniverseSelectionModel'''
        super().__init__(filter_fine_data, universe_settings)

        # Number of stocks in Coarse Universe
        self.number_of_symbols_coarse = 500
        # Number of sorted stocks in the fine selection subset using the valuation ratio, EV to EBITDA (EV/EBITDA)
        self.number_of_symbols_fine = 20
        # Final number of stocks in security list, after sorted by the valuation ratio, Return on Assets (ROA)
        self.number_of_symbols_in_portfolio = 10

        self.last_month = -1
        self.dollar_volume_by_symbol = {}

    def select_coarse(self, algorithm, coarse):
        '''Performs coarse selection for constituents.
        The stocks must have fundamental data'''
        month = algorithm.time.month
        if month == self.last_month:
            return Universe.UNCHANGED
        self.last_month = month

        # sort the stocks by dollar volume and take the top 1000
        top = sorted([x for x in coarse if x.has_fundamental_data],
                    key=lambda x: x.dollar_volume, reverse=True)[:self.number_of_symbols_coarse]

        self.dollar_volume_by_symbol = { i.symbol: i.dollar_volume for i in top }

        return list(self.dollar_volume_by_symbol.keys())

    def select_fine(self, algorithm, fine):
        '''QC500: Performs fine selection for the coarse selection constituents
        The company's headquarter must in the U.S.
        The stock must be traded on either the NYSE or NASDAQ
        At least half a year since its initial public offering
        The stock's market cap must be greater than 500 million

        Magic Formula: Rank stocks by Enterprise Value to EBITDA (EV/EBITDA)
        Rank subset of previously ranked stocks (EV/EBITDA), using the valuation ratio Return on Assets (ROA)'''

        # QC500:
        ## The company's headquarter must in the U.S.
        ## The stock must be traded on either the NYSE or NASDAQ
        ## At least half a year since its initial public offering
        ## The stock's market cap must be greater than 500 million
        filtered_fine = [x for x in fine if x.company_reference.country_id == "USA"
                                        and (x.company_reference.primary_exchange_id == "NYS" or x.company_reference.primary_exchange_id == "NAS")
                                        and (algorithm.time - x.security_reference.ipo_date).days > 180
                                        and x.earning_reports.basic_average_shares.three_months * x.earning_reports.basic_eps.twelve_months * x.valuation_ratios.pe_ratio > 5e8]
        count = len(filtered_fine)
        if count == 0: return []

        my_dict = dict()
        percent = self.number_of_symbols_fine / count

        # select stocks with top dollar volume in every single sector
        for key in ["N", "M", "U", "T", "B", "I"]:
            value = [x for x in filtered_fine if x.company_reference.industry_template_code == key]
            value = sorted(value, key=lambda x: self.dollar_volume_by_symbol[x.symbol], reverse = True)
            my_dict[key] = value[:ceil(len(value) * percent)]

        # stocks in QC500 universe
        top_fine = chain.from_iterable(my_dict.values())

        #  Magic Formula:
        ## Rank stocks by Enterprise Value to EBITDA (EV/EBITDA)
        ## Rank subset of previously ranked stocks (EV/EBITDA), using the valuation ratio Return on Assets (ROA)

        # sort stocks in the security universe of QC500 based on Enterprise Value to EBITDA valuation ratio
        sorted_by_ev_to_ebitda = sorted(top_fine, key=lambda x: x.valuation_ratios.ev_to_ebitda , reverse=True)

        # sort subset of stocks that have been sorted by Enterprise Value to EBITDA, based on the valuation ratio Return on Assets (ROA)
        sorted_by_roa = sorted(sorted_by_ev_to_ebitda[:self.number_of_symbols_fine], key=lambda x: x.valuation_ratios.forward_roa, reverse=False)

        # retrieve list of securites in portfolio
        return [f.symbol for f in sorted_by_roa[:self.number_of_symbols_in_portfolio]]
```


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

Input:
Generate a LEAN AlphaModel that can be described like this
: The motivating idea for this Alpha Model is that a large price gap (here we use true outliers --

Output:
```python

from AlgorithmImports import *

class PriceGapMeanReversionAlpha(QCAlgorithm):
    '''The motivating idea for this Alpha Model is that a large price gap (here we use true outliers --
    price gaps that whose absolutely values are greater than 3 * Volatility) is due to rebound
    back to an appropriate price or at least retreat from its brief extreme. Using a Coarse Universe selection
    function, the algorithm selects the top x-companies by Dollar Volume (x can be any number you choose)
    to trade with, and then uses the Standard Deviation of the 100 most-recent closing prices to determine
    which price movements are outliers that warrant emitting insights.

    This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
    sourced so the community and client funds can see an example of an alpha.'''

    def initialize(self):

        self.set_start_date(2018, 1, 1)   #Set Start Date
        self.set_cash(100000)           #Set Strategy Cash

        ## Initialize variables to be used in controlling frequency of universe selection
        self.week = -1

        ## Manual Universe Selection
        self.universe_settings.resolution = Resolution.MINUTE
        self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selection_function))

        ## Set trading fees to $0
        self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))

        ## Set custom Alpha Model
        self.set_alpha(PriceGapMeanReversionAlphaModel())

        ## Set equal-weighting Portfolio Construction Model
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())

        ## Set Execution Model
        self.set_execution(ImmediateExecutionModel())

        ## Set Risk Management Model
        self.set_risk_management(NullRiskManagementModel())

    def coarse_selection_function(self, coarse):
        ## If it isn't a new week, return the same symbols
        current_week = self.time.isocalendar()[1]
        if current_week == self.week:
            return Universe.UNCHANGED
        self.week = current_week

        ## If its a new week, then re-filter stocks by Dollar Volume
        sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)

        return [ x.symbol for x in sorted_by_dollar_volume[:25] ]

class PriceGapMeanReversionAlphaModel(AlphaModel):

    def __init__(self, *args, **kwargs):
        ''' Initialize variables and dictionary for Symbol Data to support algorithm's function '''
        self.lookback = 100
        self.resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.MINUTE
        self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), 5) ## Arbitrary
        self._symbol_data_by_symbol = {}

    def update(self, algorithm, data):
        insights = []

        ## Loop through all Symbol Data objects
        for symbol, symbol_data in self._symbol_data_by_symbol.items():
            ## Evaluate whether or not the price jump is expected to rebound
            if not symbol_data.is_trend(data):
                continue

            ## Emit insights accordingly to the price jump sign
            direction = InsightDirection.DOWN if symbol_data.price_jump > 0 else InsightDirection.UP
            insights.append(Insight.price(symbol, self.prediction_interval, direction, symbol_data.price_jump, None))

        return insights

    def on_securities_changed(self, algorithm, changes):
        # Clean up data for removed securities
        for removed in changes.removed_securities:
            symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)
            if symbol_data is not None:
                symbol_data.remove_consolidators(algorithm)

        symbols = [x.symbol for x in changes.added_securities
            if x.symbol not in self._symbol_data_by_symbol]

        history = algorithm.history(symbols, self.lookback, self.resolution)
        if history.empty: return

        ## Create and initialize SymbolData objects
        for symbol in symbols:
            symbol_data = SymbolData(algorithm, symbol, self.lookback, self.resolution)
            symbol_data.warm_up_indicators(history.loc[symbol])
            self._symbol_data_by_symbol[symbol] = symbol_data

class SymbolData:
    def __init__(self, algorithm, symbol, lookback, resolution):
        self._symbol = symbol
        self.close = 0
        self.last_price = 0
        self.price_jump = 0
        self.consolidator = algorithm.resolve_consolidator(symbol, resolution)
        self.volatility = StandardDeviation(f'{symbol}.std({lookback})', lookback)
        algorithm.register_indicator(symbol, self.volatility, self.consolidator)

    def remove_consolidators(self, algorithm):
        algorithm.subscription_manager.remove_consolidator(self._symbol, self.consolidator)

    def warm_up_indicators(self, history):
        self.close = history.iloc[-1].close
        for tuple in history.itertuples():
            self.volatility.update(tuple.Index, tuple.close)

    def is_trend(self, data):

        ## Check for any data events that would return a NoneBar in the Alpha Model Update() method
        if not data.bars.contains_key(self._symbol):
            return False

        self.last_price = self.close
        self.close = data.bars[self._symbol].close
        self.price_jump = (self.close / self.last_price) - 1
        return abs(100*self.price_jump) > 3*self.volatility.current.value
```


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

Input:
Generate a LEAN AlphaModel that can be described like this
: Alpha Benchmark Strategy capitalizing on ETF rebalancing causing momentum during trending markets.

Output:
```python

from AlgorithmImports import *

class RebalancingLeveragedETFAlpha(QCAlgorithm):
    ''' Alpha Streams: Benchmark Alpha: Leveraged ETF Rebalancing
        Strategy by Prof. Shum, reposted by Ernie Chan.
        Source: http://epchan.blogspot.com/2012/10/a-leveraged-etfs-strategy.html'''

    def initialize(self):

        self.set_start_date(2017, 6, 1)
        self.set_end_date(2018, 8, 1)
        self.set_cash(100000)

        underlying = ["SPY","QLD","DIA","IJR","MDY","IWM","QQQ","IYE","EEM","IYW","EFA","GAZB","SLV","IEF","IYM","IYF","IYH","IYR","IYC","IBB","FEZ","USO","TLT"]
        ultra_long =  ["SSO","UGL","DDM","SAA","MZZ","UWM","QLD","DIG","EET","ROM","EFO","BOIL","AGQ","UST","UYM","UYG","RXL","URE","UCC","BIB","ULE","UCO","UBT"]
        ultra_short = ["SDS","GLL","DXD","SDD","MVV","TWM","QID","DUG","EEV","REW","EFU","KOLD","ZSL","PST","SMN","SKF","RXD","SRS","SCC","BIS","EPV","SCO","TBT"]

        groups = []
        for i in range(len(underlying)):
            group = ETFGroup(self.add_equity(underlying[i], Resolution.MINUTE).symbol,
                              self.add_equity(ultra_long[i], Resolution.MINUTE).symbol,
                              self.add_equity(ultra_short[i], Resolution.MINUTE).symbol)
            groups.append(group)

        # Manually curated universe
        self.set_universe_selection(ManualUniverseSelectionModel())
        # Select the demonstration alpha model
        self.set_alpha(RebalancingLeveragedETFAlphaModel(groups))

        # Equally weigh securities in portfolio, based on insights
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())

        # Set Immediate Execution Model
        self.set_execution(ImmediateExecutionModel())

        # Set Null Risk Management Model
        self.set_risk_management(NullRiskManagementModel())

class RebalancingLeveragedETFAlphaModel(AlphaModel):

    '''
        If the underlying ETF has experienced a return >= 1% since the previous day's close up to the current time at 14:15,
        then buy it's ultra ETF right away, and exit at the close. If the return is <= -1%, sell it's ultra-short ETF.
    '''

    def __init__(self, ETFgroups):

        self.etfgroups = ETFgroups
        self.date = datetime.min.date
        self.name = "RebalancingLeveragedETFAlphaModel"

    def update(self, algorithm, data):
        '''Scan to see if the returns are greater than 1% at 2.15pm to emit an insight.'''

        insights = []
        magnitude = 0.0005
        # Paper suggests leveraged ETF's rebalance from 2.15pm - to close
        # giving an insight period of 105 minutes.
        period = timedelta(minutes=105)

        # Get yesterday's close price at the market open
        if algorithm.time.date() != self.date:
            self.date = algorithm.time.date()
            # Save yesterday's price and reset the signal
            for group in self.etfgroups:
                history = algorithm.history([group.underlying], 1, Resolution.DAILY)
                group.yesterday_close = None if history.empty else history.loc[str(group.underlying)]['close'][0]

        # Check if the returns are > 1% at 14.15
        if algorithm.time.hour == 14 and algorithm.time.minute == 15:
            for group in self.etfgroups:
                if group.yesterday_close == 0 or group.yesterday_close is None: continue
                returns = round((algorithm.portfolio[group.underlying].price - group.yesterday_close) / group.yesterday_close, 10)
                if returns > 0.01:
                    insights.append(Insight.price(group.ultra_long, period, InsightDirection.UP, magnitude))
                elif returns < -0.01:
                    insights.append(Insight.price(group.ultra_short, period, InsightDirection.DOWN, magnitude))

        return insights

class ETFGroup:
    '''
    Group the underlying ETF and it's ultra ETFs
    Args:
        underlying: The underlying index ETF
        ultra_long: The long-leveraged version of underlying ETF
        ultra_short: The short-leveraged version of the underlying ETF
    '''
    def __init__(self,underlying, ultra_long, ultra_short):
        self.underlying = underlying
        self.ultra_long = ultra_long
        self.ultra_short = ultra_short
        self.yesterday_close = 0
```


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

Input:
Generate a LEAN AlphaModel that can be described like this
:  Contingent Claim Analysis is put forth by Robert Merton, recepient of the Noble Prize in Economics in 1997 for his work in contributing to

Output:
```python

from AlgorithmImports import *

import scipy.stats as sp
from Risk.NullRiskManagementModel import NullRiskManagementModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel

class ContingentClaimsAnalysisDefaultPredictionAlpha(QCAlgorithm):
    ''' Contingent Claim Analysis is put forth by Robert Merton, recepient of the Noble Prize in Economics in 1997 for his work in contributing to
    Black-Scholes option pricing theory, which says that the equity market value of stockholders’ equity is given by the Black-Scholes solution
    for a European call option. This equation takes into account Debt, which in CCA is the equivalent to a strike price in the BS solution. The probability
    of default on corporate debt can be calculated as the N(-d2) term, where d2 is a function of the interest rate on debt(µ), face value of the debt (B), value of the firm's assets (V),
    standard deviation of the change in a firm's asset value (σ), the dividend and interest payouts due (D), and the time to maturity of the firm's debt(τ). N(*) is the cumulative
    distribution function of a standard normal distribution, and calculating N(-d2) gives us the probability of the firm's assets being worth less
    than the debt of the company at the time that the debt reaches maturity -- that is, the firm doesn't have enough in assets to pay off its debt and defaults.

    We use a Fine/Coarse Universe Selection model to select small cap stocks, who we postulate are more likely to default
    on debt in general than blue-chip companies, and extract Fundamental data to plug into the CCA formula.
    This Alpha emits insights based on whether or not a company is likely to default given its probability of default vs a default probability threshold that we set arbitrarily.

    Prob. default (on principal B at maturity T) = Prob(VT < B) = 1 - N(d2) = N(-d2) where -d2(µ) = -{ln(V/B) + [(µ - D) - ½σ2]τ}/ σ √τ.
        N(d) = (univariate) cumulative standard normal distribution function (from -inf to d)
        B = face value (principal) of the debt
        D = dividend + interest payout
        V = value of firm’s assets
        σ (sigma) = standard deviation of firm value changes (returns in V)
        τ (tau)  = time to debt’s maturity
        µ (mu) = interest rate

    This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
    sourced so the community and client funds can see an example of an alpha.'''

    def initialize(self):

        ## Set requested data resolution and variables to help with Universe Selection control
        self.universe_settings.resolution = Resolution.DAILY
        self.month = -1

        ## Declare single variable to be passed in multiple places -- prevents issue with conflicting start dates declared in different places
        self.set_start_date(2018,1,1)
        self.set_cash(100000)

        ## SPDR Small Cap ETF is a better benchmark than the default SP500
        self.set_benchmark('IJR')

        ## Set Universe Selection Model
        self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.coarse_selection_function, self.fine_selection_function))
        self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
        ## Set CCA Alpha Model
        self.set_alpha(ContingentClaimsAnalysisAlphaModel())

        ## Set Portfolio Construction Model
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())

        ## Set Execution Model
        self.set_execution(ImmediateExecutionModel())

        ## Set Risk Management Model
        self.set_risk_management(NullRiskManagementModel())

    def coarse_selection_function(self, coarse):
        ## Boolean controls so that our symbol universe is only updated once per month
        if self.time.month == self.month:
            return Universe.UNCHANGED
        self.month = self.time.month

        ## Sort by dollar volume, lowest to highest
        sorted_by_dollar_volume = sorted([x for x in coarse if x.has_fundamental_data],
            key=lambda x: x.dollar_volume, reverse=True)

        ## Return smallest 750 -- idea is that smaller companies are most likely to go bankrupt than blue-chip companies
        ## Filter for assets with fundamental data
        return [x.symbol for x in sorted_by_dollar_volume[:750]]

    def fine_selection_function(self, fine):

            def is_valid(x):
                statement = x.financial_statements
                sheet = statement.balance_sheet
                total_assets = sheet.total_assets
                ratios = x.operation_ratios

                return total_assets.one_month > 0 and \
                        total_assets.three_months > 0 and \
                        total_assets.six_months  > 0 and \
                        total_assets.twelve_months > 0 and \
                        sheet.current_liabilities.twelve_months > 0 and \
                        sheet.interest_payable.twelve_months > 0 and \
                        ratios.total_assets_growth.one_year > 0 and \
                        statement.income_statement.gross_dividend_payment.twelve_months > 0 and \
                        ratios.roa.one_year > 0

            return [x.symbol for x in sorted(fine, key=lambda x: is_valid(x))]

class ContingentClaimsAnalysisAlphaModel(AlphaModel):

    def __init__(self, *args, **kwargs):
        self.probability_of_default_by_symbol = {}
        self.default_threshold = kwargs['default_threshold'] if 'default_threshold' in kwargs else 0.25

    def update(self, algorithm, data):
        '''Updates this alpha model with the latest data from the algorithm.
        This is called each time the algorithm receives data for subscribed securities
        Args:
            algorithm: The algorithm instance
            data: The new data available
        Returns:
            The new insights generated'''

        ## Build a list to hold our insights
        insights = []

        for symbol, pod in self.probability_of_default_by_symbol.items():

            ## If Prob. of Default is greater than our set threshold, then emit an insight indicating that this asset is trending downward
            if pod >= self.default_threshold and pod != 1.0:
                insights.append(Insight.price(symbol, timedelta(30), InsightDirection.DOWN, pod, None))

        return insights

    def on_securities_changed(self, algorithm, changes):

        for removed in changes.removed_securities:
            self.probability_of_default_by_symbol.pop(removed.symbol, None)

        # initialize data for added securities
        symbols = [ x.symbol for x in changes.added_securities ]

        for symbol in symbols:
            if symbol not in self.probability_of_default_by_symbol:
                ## CCA valuation
                pod = self.get_probability_of_default(algorithm, symbol)
                if pod is not None:
                    self.probability_of_default_by_symbol[symbol] = pod

    def get_probability_of_default(self, algorithm, symbol):
        '''This model applies options pricing theory, Black-Scholes specifically,
        to fundamental data to give the probability of a default'''
        security = algorithm.securities[symbol]
        if security.fundamentals is None or security.fundamentals.financial_statements is None or security.fundamentals.operation_ratios is None:
            return None

        statement = security.fundamentals.financial_statements
        sheet = statement.balance_sheet
        total_assets = sheet.total_assets

        tau = 360   ## Days
        mu = security.fundamentals.operation_ratios.roa.one_year
        V = total_assets.twelve_months
        B = sheet.current_liabilities.twelve_months
        D = statement.income_statement.gross_dividend_payment.twelve_months + sheet.interest_payable.twelve_months

        series = pd.Series(
            [
                total_assets.one_month,
                total_assets.three_months,
                total_assets.six_months,
                V
            ])
        sigma = series.iloc[series.nonzero()[0]]
        sigma = np.std(sigma.pct_change()[1:len(sigma)])

        d2 = ((np.log(V) - np.log(B)) + ((mu - D) - 0.5*sigma**2.0)*tau)/ (sigma*np.sqrt(tau))
        return sp.norm.cdf(-d2)
```


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

Input:
Generate a LEAN AlphaModel that can be described like this
:  Alpha Streams: Benchmark Alpha: Identify "pumped" penny stocks and predict that the price of a "pumped" penny stock reverts to mean

Output:
```python

from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel

class SykesShortMicroCapAlpha(QCAlgorithm):
    ''' Alpha Streams: Benchmark Alpha: Identify "pumped" penny stocks and predict that the price of a "pumped" penny stock reverts to mean

    This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
   sourced so the community and client funds can see an example of an alpha.'''

    def initialize(self):

        self.set_start_date(2018, 1, 1)
        self.set_cash(100000)

        # Set zero transaction fees
        self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))

        # select stocks using PennyStockUniverseSelectionModel
        self.universe_settings.resolution = Resolution.DAILY
        self.universe_settings.schedule.on(self.date_rules.month_start())
        self.set_universe_selection(PennyStockUniverseSelectionModel())

        # Use SykesShortMicroCapAlphaModel to establish insights
        self.set_alpha(SykesShortMicroCapAlphaModel())

        # Equally weigh securities in portfolio, based on insights
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())

        # Set Immediate Execution Model
        self.set_execution(ImmediateExecutionModel())

        # Set Null Risk Management Model
        self.set_risk_management(NullRiskManagementModel())

class SykesShortMicroCapAlphaModel(AlphaModel):
    '''Uses ranking of intraday percentage difference between open price and close price to create magnitude and direction prediction for insights'''

    def __init__(self, *args, **kwargs):
        lookback = kwargs['lookback'] if 'lookback' in kwargs else 1
        resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.DAILY
        self.prediction_interval = Time.multiply(Extensions.to_time_span(resolution), lookback)
        self.number_of_stocks = kwargs['number_of_stocks'] if 'number_of_stocks' in kwargs else 10

    def update(self, algorithm, data):
        insights = []
        symbols_ret = dict()

        for security in algorithm.active_securities.values:
            if security.has_data:
                open_ = security.open
                if open_ != 0:
                    # Intraday price change for penny stocks
                    symbols_ret[security.symbol] = security.close / open_ - 1

        # Rank penny stocks on one day price change and retrieve list of ten "pumped" penny stocks
        pumped_stocks = dict(sorted(symbols_ret.items(),
                                   key = lambda kv: (-round(kv[1], 6), kv[0]))[:self.number_of_stocks])

        # Emit "down" insight for "pumped" penny stocks
        for symbol, value in pumped_stocks.items():
            insights.append(Insight.price(symbol, self.prediction_interval, InsightDirection.DOWN, abs(value), None))

        return insights

class PennyStockUniverseSelectionModel(FundamentalUniverseSelectionModel):
    '''Defines a universe of penny stocks, as a universe selection model for the framework algorithm:
    The stocks must have fundamental data
    The stock must have positive previous-day close price
    The stock must have volume between $1000000 and $10000 on the previous trading day
    The stock must cost less than $5'''
    def __init__(self):
        super().__init__()

        # Number of stocks in Coarse Universe
        self.number_of_symbols_coarse = 500

    def select(self, algorithm, fundamental):
        # sort the stocks by dollar volume and take the top 500
        top = sorted([x for x in fundamental if x.has_fundamental_data
                                       and 5 > x.price > 0
                                       and 1000000 > x.volume > 10000],
                    key=lambda x: x.dollar_volume, reverse=True)[:self.number_of_symbols_coarse]

        return [x.symbol for x in top]
```


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

Input:
Generate a LEAN ExecutionModel that can be described like this
: Execution model that submits orders while the current market prices is at least the configured number of standard

Output:
```python

from AlgorithmImports import *

class StandardDeviationExecutionModel(ExecutionModel):
    '''Execution model that submits orders while the current market prices is at least the configured number of standard
     deviations away from the mean in the favorable direction (below/above for buy/sell respectively)'''

    def __init__(self,
                 period = 60,
                 deviations = 2,
                 resolution = Resolution.MINUTE,
                 asynchronous=True):
        '''Initializes a new instance of the StandardDeviationExecutionModel class
        Args:
            period: Period of the standard deviation indicator
            deviations: The number of deviations away from the mean before submitting an order
            resolution: The resolution of the STD and SMA indicators
            asynchronous: If True, orders will be submitted asynchronously.'''
        super().__init__(asynchronous)
        self.period = period
        self.deviations = deviations
        self.resolution = resolution
        self.targets_collection = PortfolioTargetCollection()
        self._symbol_data = {}

        # Gets or sets the maximum order value in units of the account currency.
        # This defaults to $20,000. For example, if purchasing a stock with a price
        # of $100, then the maximum order size would be 200 shares.
        self.maximum_order_value = 20000

    def execute(self, algorithm, targets):
        '''Executes market orders if the standard deviation of price is more
       than the configured number of deviations in the favorable direction.
       Args:
           algorithm: The algorithm instance
           targets: The portfolio targets'''
        self.targets_collection.add_range(targets)

        # for performance we check count value, OrderByMarginImpact and ClearFulfilled are expensive to call
        if not self.targets_collection.is_empty:
            for target in self.targets_collection.order_by_margin_impact(algorithm):
                symbol = target.symbol

                # calculate remaining quantity to be ordered
                unordered_quantity = OrderSizing.get_unordered_quantity(algorithm, target)

                # fetch our symbol data containing our STD/SMA indicators
                data = self._symbol_data.get(symbol, None)
                if data is None: return

                # check order entry conditions
                if data.std.is_ready and self.price_is_favorable(data, unordered_quantity):
                    # Adjust order size to respect the maximum total order value
                    order_size = OrderSizing.get_order_size_for_maximum_value(data.security, self.maximum_order_value, unordered_quantity)

                    if order_size != 0:
                        algorithm.market_order(symbol, order_size, self.asynchronous, target.tag)

            self.targets_collection.clear_fulfilled(algorithm)

    def on_securities_changed(self, algorithm, changes):
        '''Event fired each time the we add/remove securities from the data feed
        Args:
            algorithm: The algorithm instance that experienced the change in securities
            changes: The security additions and removals from the algorithm'''
        for added in changes.added_securities:
            if added.symbol not in self._symbol_data:
                self._symbol_data[added.symbol] = SymbolData(algorithm, added, self.period, self.resolution)

        for removed in changes.removed_securities:
            # clean up data from removed securities
            symbol = removed.symbol
            if symbol in self._symbol_data:
                if self.is_safe_to_remove(algorithm, symbol):
                    data = self._symbol_data.pop(symbol)
                    algorithm.subscription_manager.remove_consolidator(symbol, data.consolidator)

    def price_is_favorable(self, data, unordered_quantity):
        '''Determines if the current price is more than the configured
       number of standard deviations away from the mean in the favorable direction.'''
        sma = data.sma.current.value
        deviations = self.deviations * data.std.current.value
        if unordered_quantity > 0:
            return data.security.bid_price < sma - deviations
        else:
            return data.security.ask_price > sma + deviations

    def is_safe_to_remove(self, algorithm, symbol):
        '''Determines if it's safe to remove the associated symbol data'''
        # confirm the security isn't currently a member of any universe
        return not any([kvp.value.contains_member(symbol) for kvp in algorithm.universe_manager])

class SymbolData:
    def __init__(self, algorithm, security, period, resolution):
        symbol = security.symbol
        self.security = security
        self.consolidator = algorithm.resolve_consolidator(symbol, resolution)

        sma_name = algorithm.create_indicator_name(symbol, f"SMA{period}", resolution)
        self.sma = SimpleMovingAverage(sma_name, period)
        algorithm.register_indicator(symbol, self.sma, self.consolidator)

        std_name = algorithm.create_indicator_name(symbol, f"STD{period}", resolution)
        self.std = StandardDeviation(std_name, period)
        algorithm.register_indicator(symbol, self.std, self.consolidator)

        # warmup our indicators by pushing history through the indicators
        bars = algorithm.history[self.consolidator.input_type](symbol, period, resolution)
        for bar in bars:
            self.sma.update(bar.end_time, bar.close)
            self.std.update(bar.end_time, bar.close)
```