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 price is more favorable that the current volume weighted average price.

Output:
```python

from AlgorithmImports import *

class VolumeWeightedAveragePriceExecutionModel(ExecutionModel):
    '''Execution model that submits orders while the current market price is more favorable that the current volume weighted average price.'''

    def __init__(self, asynchronous=True):
        '''Initializes a new instance of the VolumeWeightedAveragePriceExecutionModel class'''
        super().__init__(asynchronous)
        self.targets_collection = PortfolioTargetCollection()
        self.symbol_data = {}

        # Gets or sets the maximum order quantity as a percentage of the current bar's volume.
        # This defaults to 0.01m = 1%. For example, if the current bar's volume is 100,
        # then the maximum order size would equal 1 share.
        self.maximum_order_quantity_percent_volume = 0.01

    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'''
        # update the complete set of portfolio targets with the new 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 VWAP indicator
                data = self.symbol_data.get(symbol, None)
                if data is None: return

                # check order entry conditions
                if self.price_is_favorable(data, unordered_quantity):
                    # adjust order size to respect maximum order size based on a percentage of current volume
                    order_size = OrderSizing.get_order_size_for_percent_volume(data.security, self.maximum_order_quantity_percent_volume, 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 removed in changes.removed_securities:
            # clean up removed security data
            if removed.symbol in self.symbol_data:
                if self.is_safe_to_remove(algorithm, removed.symbol):
                    data = self.symbol_data.pop(removed.symbol)
                    algorithm.subscription_manager.remove_consolidator(removed.symbol, data.consolidator)

        for added in changes.added_securities:
            if added.symbol not in self.symbol_data:
                self.symbol_data[added.symbol] = SymbolData(algorithm, added)

    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.'''
        if unordered_quantity > 0:
            if data.security.bid_price < data.vwap:
                return True
        else:
            if data.security.ask_price > data.vwap:
                return True

        return False

    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):
        self.security = security
        self.consolidator = algorithm.resolve_consolidator(security.symbol, security.resolution)
        name = algorithm.create_indicator_name(security.symbol, "VWAP", security.resolution)
        self._vwap = IntradayVwap(name)
        algorithm.register_indicator(security.symbol, self._vwap, self.consolidator)

    @property
    def vwap(self):
       return self._vwap.value

class IntradayVwap:
    '''Defines the canonical intraday VWAP indicator'''
    def __init__(self, name):
        self.name = name
        self.value = 0.0
        self.last_date = datetime.min
        self.sum_of_volume = 0.0
        self.sum_of_price_times_volume = 0.0

    @property
    def is_ready(self):
        return self.sum_of_volume > 0.0

    def update(self, input):
        '''Computes the new VWAP'''
        success, volume, average_price = self.get_volume_and_average_price(input)
        if not success:
            return self.is_ready

        # reset vwap on daily boundaries
        if self.last_date != input.end_time.date():
            self.sum_of_volume = 0.0
            self.sum_of_price_times_volume = 0.0
            self.last_date = input.end_time.date()

        # running totals for Σ PiVi / Σ Vi
        self.sum_of_volume += volume
        self.sum_of_price_times_volume += average_price * volume

        if self.sum_of_volume == 0.0:
           # if we have no trade volume then use the current price as VWAP
           self.value = input.value
           return self.is_ready

        self.value = self.sum_of_price_times_volume / self.sum_of_volume
        return self.is_ready

    def get_volume_and_average_price(self, input):
        '''Determines the volume and price to be used for the current input in the VWAP computation'''

        if type(input) is Tick:
            if input.tick_type == TickType.TRADE:
                return True, float(input.quantity), float(input.last_price)

        if type(input) is TradeBar:
            if not input.is_fill_forward:
                average_price = float(input.high + input.low + input.close) / 3
                return True, float(input.volume), average_price

        return False, 0.0, 0.0
```


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 spread is tight.

Output:
```python

from AlgorithmImports import *

class SpreadExecutionModel(ExecutionModel):
    '''Execution model that submits orders while the current spread is tight.
       Note this execution model will not work using Resolution.DAILY since Exchange.exchange_open will be false, suggested resolution is Minute
    '''

    def __init__(self, accepting_spread_percent=0.005, asynchronous=True):
        '''Initializes a new instance of the SpreadExecutionModel class'''
        super().__init__(asynchronous)
        self.targets_collection = PortfolioTargetCollection()

        # Gets or sets the maximum spread compare to current price in percentage.
        self.accepting_spread_percent = Math.abs(accepting_spread_percent)

    def execute(self, algorithm, targets):
        '''Executes market orders if the spread percentage to price is in desirable range.
       Args:
           algorithm: The algorithm instance
           targets: The portfolio targets'''
        # update the complete set of portfolio targets with the new 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)

                # check order entry conditions
                if unordered_quantity != 0:
                    # get security information
                    security = algorithm.securities[symbol]
                    if self.spread_is_favorable(security):
                        algorithm.market_order(symbol, unordered_quantity, self.asynchronous, target.tag)

            self.targets_collection.clear_fulfilled(algorithm)

    def spread_is_favorable(self, security):
        '''Determines if the spread is in desirable range.'''
        # Price has to be larger than zero to avoid zero division error, or negative price causing the spread percentage < 0 by error
        # Has to be in opening hours of exchange to avoid extreme spread in OTC period
        return security.exchange.exchange_open \
            and security.price > 0 and security.ask_price > 0 and security.bid_price > 0 \
            and (security.ask_price - security.bid_price) / security.price <= self.accepting_spread_percent
```


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
: This alpha model is designed to accept every possible pair combination

Output:
```python

from AlgorithmImports import *
from enum import Enum

class BasePairsTradingAlphaModel(AlphaModel):
    '''This alpha model is designed to accept every possible pair combination
    from securities selected by the universe selection model
    This model generates alternating long ratio/short ratio insights emitted as a group'''

    def __init__(self, lookback = 1,
            resolution = Resolution.DAILY,
            threshold = 1):
        ''' Initializes a new instance of the PairsTradingAlphaModel class
        Args:
            lookback: Lookback period of the analysis
            resolution: Analysis resolution
            threshold: The percent [0, 100] deviation of the ratio from the mean before emitting an insight'''
        self.lookback = lookback
        self.resolution = resolution
        self.threshold = threshold
        self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), self.lookback)

        self.pairs = dict()
        self.securities = set()

        self.name = f'{self.__class__.__name__}({self.lookback},{resolution},{Extensions.normalize_to_str(threshold)})'

    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'''
        insights = []

        for key, pair in self.pairs.items():
            insights.extend(pair.get_insight_group())

        return insights

    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 security in changes.added_securities:
            self.securities.add(security)

        for security in changes.removed_securities:
            if security in self.securities:
                self.securities.remove(security)

        self.update_pairs(algorithm)

        for security in changes.removed_securities:
            keys = [k for k in self.pairs.keys() if security.symbol in k]
            for key in keys:
                self.pairs.pop(key).dispose()

    def update_pairs(self, algorithm):

        symbols = sorted([x.symbol for x in self.securities])

        for i in range(0, len(symbols)):
            asset_i = symbols[i]

            for j in range(1 + i, len(symbols)):
                asset_j = symbols[j]

                pair_symbol = (asset_i, asset_j)
                invert = (asset_j, asset_i)

                if pair_symbol in self.pairs or invert in self.pairs:
                    continue

                if not self.has_passed_test(algorithm, asset_i, asset_j):
                    continue

                pair = self.Pair(algorithm, asset_i, asset_j, self.prediction_interval, self.threshold)
                self.pairs[pair_symbol] = pair

    def has_passed_test(self, algorithm, asset1, asset2):
        '''Check whether the assets pass a pairs trading test
        Args:
            algorithm: The algorithm instance that experienced the change in securities
            asset1: The first asset's symbol in the pair
            asset2: The second asset's symbol in the pair
        Returns:
            True if the statistical test for the pair is successful'''
        return True

    class Pair:

        class State(Enum):
            SHORT_RATIO = -1
            FLAT_RATIO = 0
            LONG_RATIO = 1

        def __init__(self, algorithm, asset1, asset2, prediction_interval, threshold):
            '''Create a new pair
            Args:
                algorithm: The algorithm instance that experienced the change in securities
                asset1: The first asset's symbol in the pair
                asset2: The second asset's symbol in the pair
                prediction_interval: Period over which this insight is expected to come to fruition
                threshold: The percent [0, 100] deviation of the ratio from the mean before emitting an insight'''
            self.state = self.State.FLAT_RATIO

            self.algorithm = algorithm
            self.asset1 = asset1
            self.asset2 = asset2

            # Created the Identity indicator for a given Symbol and
            # the consolidator it is registered to. The consolidator reference
            # will be used to remove it from SubscriptionManager
            def create_identity_indicator(symbol: Symbol):
                resolution = min([x.resolution for x in algorithm.subscription_manager.subscription_data_config_service.get_subscription_data_configs(symbol)])

                name = algorithm.create_indicator_name(symbol, "close", resolution)
                identity = Identity(name)

                consolidator = algorithm.resolve_consolidator(symbol, resolution)
                algorithm.register_indicator(symbol, identity, consolidator)

                return identity, consolidator

            self.asset1_price, self.identity_consolidator1 = create_identity_indicator(asset1);
            self.asset2_price, self.identity_consolidator2 = create_identity_indicator(asset2);

            self.ratio = IndicatorExtensions.over(self.asset1_price, self.asset2_price)
            self.mean = IndicatorExtensions.of(ExponentialMovingAverage(500), self.ratio)

            upper = ConstantIndicator[IndicatorDataPoint]("ct", 1 + threshold / 100)
            self.upper_threshold = IndicatorExtensions.times(self.mean, upper)

            lower = ConstantIndicator[IndicatorDataPoint]("ct", 1 - threshold / 100)
            self.lower_threshold = IndicatorExtensions.times(self.mean, lower)

            self.prediction_interval = prediction_interval

        def dispose(self):
            '''
            On disposal, remove the consolidators from the subscription manager
            '''
            self.algorithm.subscription_manager.remove_consolidator(self.asset1, self.identity_consolidator1)
            self.algorithm.subscription_manager.remove_consolidator(self.asset2, self.identity_consolidator2)

        def get_insight_group(self):
            '''Gets the insights group for the pair
            Returns:
                Insights grouped by an unique group id'''

            if not self.mean.is_ready:
                return []

            # don't re-emit the same direction
            if self.state is not self.State.LONG_RATIO and self.ratio > self.upper_threshold:
                self.state = self.State.LONG_RATIO

                # asset1/asset2 is more than 2 std away from mean, short asset1, long asset2
                short_asset_1 = Insight.price(self.asset1, self.prediction_interval, InsightDirection.DOWN)
                long_asset_2 = Insight.price(self.asset2, self.prediction_interval, InsightDirection.UP)

                # creates a group id and set the GroupId property on each insight object
                return Insight.group(short_asset_1, long_asset_2)

            # don't re-emit the same direction
            if self.state is not self.State.SHORT_RATIO and self.ratio < self.lower_threshold:
                self.state = self.State.SHORT_RATIO

                # asset1/asset2 is less than 2 std away from mean, long asset1, short asset2
                long_asset_1 = Insight.price(self.asset1, self.prediction_interval, InsightDirection.UP)
                short_asset_2 = Insight.price(self.asset2, self.prediction_interval, InsightDirection.DOWN)

                # creates a group id and set the GroupId property on each insight object
                return Insight.group(long_asset_1, short_asset_2)

            return []
```


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
: Defines a custom alpha model that uses MACD crossovers. The MACD signal line

Output:
```python

from AlgorithmImports import *

class MacdAlphaModel(AlphaModel):
    '''Defines a custom alpha model that uses MACD crossovers. The MACD signal line
    is used to generate up/down insights if it's stronger than the bounce threshold.
    If the MACD signal is within the bounce threshold then a flat price insight is returned.'''

    def __init__(self,
                 fastPeriod = 12,
                 slowPeriod = 26,
                 signalPeriod = 9,
                 movingAverageType = MovingAverageType.Exponential,
                 resolution = Resolution.Daily):
        ''' Initializes a new instance of the MacdAlphaModel class
        Args:
            fastPeriod: The MACD fast period
            slowPeriod: The MACD slow period</param>
            signalPeriod: The smoothing period for the MACD signal
            movingAverageType: The type of moving average to use in the MACD'''
        self.fastPeriod = fastPeriod
        self.slowPeriod = slowPeriod
        self.signalPeriod = signalPeriod
        self.movingAverageType = movingAverageType
        self.resolution = resolution
        self.insightPeriod = Time.Multiply(Extensions.ToTimeSpan(resolution), fastPeriod)
        self.bounceThresholdPercent = 0.01
        self.insightCollection = InsightCollection()
        self.symbolData = {}

        self.Name = '{}({},{},{},{},{})'.format(self.__class__.__name__, fastPeriod, slowPeriod, signalPeriod, movingAverageType, resolution)

    def Update(self, algorithm, data):
        ''' Determines an insight for each security based on it's current MACD signal
        Args:
            algorithm: The algorithm instance
            data: The new data available
        Returns:
            The new insights generated'''
        insights = []

        for key, sd in self.symbolData.items():
            if sd.Security.Price == 0:
                continue

            direction = InsightDirection.Flat
            normalized_signal = sd.MACD.Signal.Current.Value / sd.Security.Price

            if normalized_signal > self.bounceThresholdPercent:
                direction = InsightDirection.Up
            elif normalized_signal < -self.bounceThresholdPercent:
                direction = InsightDirection.Down

            # ignore signal for same direction as previous signal
            if direction == sd.PreviousDirection:
                continue

            sd.PreviousDirection = direction

            if direction == InsightDirection.Flat:
                self.CancelInsights(algorithm, sd.Security.Symbol)
                continue

            insight = Insight.Price(sd.Security.Symbol, self.insightPeriod, direction)
            insights.append(insight)
            self.insightCollection.Add(insight)

        return insights

    def OnSecuritiesChanged(self, algorithm, changes):
        '''Event fired each time the we add/remove securities from the data feed.
        This initializes the MACD for each added security and cleans up the indicator for each removed security.
        Args:
            algorithm: The algorithm instance that experienced the change in securities
            changes: The security additions and removals from the algorithm'''
        for added in changes.AddedSecurities:
            self.symbolData[added.Symbol] = SymbolData(algorithm, added, self.fastPeriod, self.slowPeriod, self.signalPeriod, self.movingAverageType, self.resolution)

        for removed in changes.RemovedSecurities:
            symbol = removed.Symbol

            data = self.symbolData.pop(symbol, None)
            if data is not None:
                # clean up our consolidator
                algorithm.SubscriptionManager.RemoveConsolidator(symbol, data.Consolidator)

            # remove from insight collection manager
            self.CancelInsights(algorithm, symbol)

    def CancelInsights(self, algorithm, symbol):
        if not self.insightCollection.ContainsKey(symbol):
            return
        insights = self.insightCollection[symbol]
        algorithm.Insights.Cancel(insights)
        self.insightCollection.Clear([ symbol ]);

class SymbolData:
    def __init__(self, algorithm, security, fastPeriod, slowPeriod, signalPeriod, movingAverageType, resolution):
        self.Security = security
        self.MACD = MovingAverageConvergenceDivergence(fastPeriod, slowPeriod, signalPeriod, movingAverageType)

        self.Consolidator = algorithm.ResolveConsolidator(security.Symbol, resolution)
        algorithm.RegisterIndicator(security.Symbol, self.MACD, self.Consolidator)
        algorithm.WarmUpIndicator(security.Symbol, self.MACD, resolution)

        self.PreviousDirection = None
```


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
: Uses Wilder's RSI to create insights.

Output:
```python

from AlgorithmImports import *
from QuantConnect.Logging import *
from enum import Enum

class RsiAlphaModel(AlphaModel):
    '''Uses Wilder's RSI to create insights.
    Using default settings, a cross over below 30 or above 70 will trigger a new insight.'''

    def __init__(self,
                 period = 14,
                 resolution = Resolution.DAILY):
        '''Initializes a new instance of the RsiAlphaModel class
        Args:
            period: The RSI indicator period'''
        self.period = period
        self.resolution = resolution
        self.insight_period = Time.multiply(Extensions.to_time_span(resolution), period)
        self.symbol_data_by_symbol ={}

        self.name = '{}({},{})'.format(self.__class__.__name__, period, resolution)

    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'''
        insights = []
        for symbol, symbol_data in self.symbol_data_by_symbol.items():
            rsi = symbol_data.rsi
            previous_state = symbol_data.state
            state = self.get_state(rsi, previous_state)

            if state != previous_state and rsi.is_ready:
                if state == State.TRIPPED_LOW:
                    insights.append(Insight.price(symbol, self.insight_period, InsightDirection.UP))
                if state == State.TRIPPED_HIGH:
                    insights.append(Insight.price(symbol, self.insight_period, InsightDirection.DOWN))

            symbol_data.state = state

        return insights

    def on_securities_changed(self, algorithm, changes):
        '''Cleans out old security data and initializes the RSI for any newly added securities.
        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'''
        # clean up data for removed securities
        for security in changes.removed_securities:
            symbol_data = self.symbol_data_by_symbol.pop(security.symbol, None)
            if symbol_data:
                symbol_data.dispose()

        # initialize data for added securities
        added_symbols = []
        for security in changes.added_securities:
            symbol = security.symbol
            if symbol not in self.symbol_data_by_symbol:
                symbol_data = SymbolData(algorithm, symbol, self.period, self.resolution)
                self.symbol_data_by_symbol[symbol] = symbol_data
                added_symbols.append(symbol)

        if added_symbols:
            history = algorithm.history[TradeBar](added_symbols, self.period, self.resolution)
            for trade_bars in history:
                for bar in trade_bars.values():
                    self.symbol_data_by_symbol[bar.symbol].update(bar)

    def get_state(self, rsi, previous):
        ''' Determines the new state. This is basically cross-over detection logic that
        includes considerations for bouncing using the configured bounce tolerance.'''
        if rsi.current.value > 70:
            return State.TRIPPED_HIGH
        if rsi.current.value < 30:
            return State.TRIPPED_LOW
        if previous == State.TRIPPED_LOW:
            if rsi.current.value > 35:
                return State.MIDDLE
        if previous == State.TRIPPED_HIGH:
            if rsi.current.value < 65:
                return State.MIDDLE

        return previous

class SymbolData:
    '''Contains data specific to a symbol required by this model'''
    def __init__(self, algorithm, symbol, period, resolution):
        self.algorithm = algorithm
        self.symbol = symbol
        self.state = State.MIDDLE

        self.rsi = RelativeStrengthIndex(period, MovingAverageType.WILDERS)
        self.consolidator = algorithm.resolve_consolidator(symbol, resolution)
        algorithm.register_indicator(symbol, self.rsi, self.consolidator)

    def update(self, bar):
        self.consolidator.update(bar)

    def dispose(self):
        self.algorithm.subscription_manager.remove_consolidator(self.symbol, self.consolidator)

class State(Enum):
    '''Defines the state. This is used to prevent signal spamming and aid in bounce detection.'''
    TRIPPED_LOW = 0
    MIDDLE = 1
    TRIPPED_HIGH = 2
```


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
:  This alpha model is designed to rank every pair combination by its pearson correlation

Output:
```python

from AlgorithmImports import *
from Alphas.BasePairsTradingAlphaModel import BasePairsTradingAlphaModel
from scipy.stats import pearsonr

class PearsonCorrelationPairsTradingAlphaModel(BasePairsTradingAlphaModel):
    ''' This alpha model is designed to rank every pair combination by its pearson correlation
    and trade the pair with the hightest correlation
    This model generates alternating long ratio/short ratio insights emitted as a group'''

    def __init__(self, lookback = 15,
            resolution = Resolution.MINUTE,
            threshold = 1,
            minimum_correlation = .5):
        '''Initializes a new instance of the PearsonCorrelationPairsTradingAlphaModel class
        Args:
            lookback: lookback period of the analysis
            resolution: analysis resolution
            threshold: The percent [0, 100] deviation of the ratio from the mean before emitting an insight
            minimum_correlation: The minimum correlation to consider a tradable pair'''
        super().__init__(lookback, resolution, threshold)
        self.lookback = lookback
        self.resolution = resolution
        self.minimum_correlation = minimum_correlation
        self.best_pair = ()

    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 security in changes.added_securities:
            self.securities.add(security)

        for security in changes.removed_securities:
            if security in self.securities:
                self.securities.remove(security)

        symbols = sorted([ x.symbol for x in self.securities ])

        history = algorithm.history(symbols, self.lookback, self.resolution)

        if not history.empty:
            history = history.close.unstack(level=0)

            df = self.get_price_dataframe(history)
            stop = len(df.columns)

            corr = dict()

            for i in range(0, stop):
                for j in range(i+1, stop):
                    if (j, i) not in corr:
                        corr[(i, j)] = pearsonr(df.iloc[:,i], df.iloc[:,j])[0]

            corr = sorted(corr.items(), key = lambda kv: kv[1])
            if corr[-1][1] >= self.minimum_correlation:
                self.best_pair = (symbols[corr[-1][0][0]], symbols[corr[-1][0][1]])

        super().on_securities_changed(algorithm, changes)

    def has_passed_test(self, algorithm, asset1, asset2):
        '''Check whether the assets pass a pairs trading test
        Args:
            algorithm: The algorithm instance that experienced the change in securities
            asset1: The first asset's symbol in the pair
            asset2: The second asset's symbol in the pair
        Returns:
            True if the statistical test for the pair is successful'''
        return self.best_pair is not None and self.best_pair[0] == asset1 and self.best_pair[1] == asset2

    def get_price_dataframe(self, df):
        timezones = { x.symbol.value: x.exchange.time_zone for x in self.securities }

        # Use log prices
        df = np.log(df)

        is_single_timeZone = len(set(timezones.values())) == 1

        if not is_single_timeZone:
            series_dict = dict()

            for column in df:
                # Change the dataframe index from data time to UTC time
                to_utc = lambda x: Extensions.convert_to_utc(x, timezones[column])
                if self.resolution == Resolution.DAILY:
                    to_utc = lambda x: Extensions.convert_to_utc(x, timezones[column]).date()

                data = df[[column]]
                data.index = data.index.map(to_utc)
                series_dict[column] = data[column]

            df = pd.DataFrame(series_dict).dropna()

        return (df - df.shift(1)).dropna()
```


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
: Uses Historical returns to create insights.

Output:
```python

from AlgorithmImports import *

class HistoricalReturnsAlphaModel(AlphaModel):
    '''Uses Historical returns to create insights.'''

    def __init__(self, *args, **kwargs):
        '''Initializes a new default instance of the HistoricalReturnsAlphaModel class.
        Args:
            lookback(int): Historical return lookback period
            resolution: The resolution of historical data'''
        self.lookback = kwargs['lookback'] if 'lookback' in kwargs else 1
        self.resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.DAILY
        self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), self.lookback)
        self._symbol_data_by_symbol = {}
        self.insight_collection = InsightCollection()

    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'''
        insights = []

        for symbol, symbol_data in self._symbol_data_by_symbol.items():
            if symbol_data.can_emit:

                direction = InsightDirection.FLAT
                magnitude = symbol_data.return_
                if magnitude > 0: direction = InsightDirection.UP
                if magnitude < 0: direction = InsightDirection.DOWN

                if direction == InsightDirection.FLAT:
                    self.cancel_insights(algorithm, symbol)
                    continue

                insights.append(Insight.price(symbol, self.prediction_interval, direction, magnitude, None))

        self.insight_collection.add_range(insights)
        return insights

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

        # 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)
            self.cancel_insights(algorithm, removed.symbol)

        # initialize data for added securities
        symbols = [ x.symbol for x in changes.added_securities ]
        history = algorithm.history(symbols, self.lookback, self.resolution)
        if history.empty: return

        tickers = history.index.levels[0]
        for ticker in tickers:
            symbol = SymbolCache.get_symbol(ticker)

            if symbol not in self._symbol_data_by_symbol:
                symbol_data = SymbolData(symbol, self.lookback)
                self._symbol_data_by_symbol[symbol] = symbol_data
                symbol_data.register_indicators(algorithm, self.resolution)
                symbol_data.warm_up_indicators(history.loc[ticker])

    def cancel_insights(self, algorithm, symbol):
        if not self.insight_collection.contains_key(symbol):
            return
        insights = self.insight_collection[symbol]
        algorithm.insights.cancel(insights)
        self.insight_collection.clear([ symbol ]);

class SymbolData:
    '''Contains data specific to a symbol required by this model'''
    def __init__(self, symbol, lookback):
        self.symbol = symbol
        self.roc = RateOfChange('{}.roc({})'.format(symbol, lookback), lookback)
        self.consolidator = None
        self.previous = 0

    def register_indicators(self, algorithm, resolution):
        self.consolidator = algorithm.resolve_consolidator(self.symbol, resolution)
        algorithm.register_indicator(self.symbol, self.roc, self.consolidator)

    def remove_consolidators(self, algorithm):
        if self.consolidator is not None:
            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 return_(self):
        return float(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 '{}: {:.2%}'.format(self.roc.name, (1 + self.return_)**252 - 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 model that uses an EMA cross to create insights

Output:
```python

from AlgorithmImports import *

class EmaCrossAlphaModel(AlphaModel):
    '''Alpha model that uses an EMA cross to create insights'''

    def __init__(self,
                 fast_period = 12,
                 slow_period = 26,
                 resolution = Resolution.DAILY):
        '''Initializes a new instance of the EmaCrossAlphaModel class
        Args:
            fast_period: The fast EMA period
            slow_period: The slow EMA period'''
        self.fast_period = fast_period
        self.slow_period = slow_period
        self.resolution = resolution
        self.prediction_interval = Time.multiply(Extensions.to_time_span(resolution), fast_period)
        self.symbol_data_by_symbol = {}

        self.name = '{}({},{},{})'.format(self.__class__.__name__, fast_period, slow_period, resolution)

    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'''
        insights = []
        for symbol, symbol_data in self.symbol_data_by_symbol.items():
            if symbol_data.fast.is_ready and symbol_data.slow.is_ready:

                if symbol_data.fast_is_over_slow:
                    if symbol_data.slow > symbol_data.fast:
                        insights.append(Insight.price(symbol_data.symbol, self.prediction_interval, InsightDirection.DOWN))

                elif symbol_data.slow_is_over_fast:
                    if symbol_data.fast > symbol_data.slow:
                        insights.append(Insight.price(symbol_data.symbol, self.prediction_interval, InsightDirection.UP))

            symbol_data.fast_is_over_slow = symbol_data.fast > symbol_data.slow

        return insights

    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:
            symbol_data = self.symbol_data_by_symbol.get(added.symbol)
            if symbol_data is None:
                symbol_data = SymbolData(added, self.fast_period, self.slow_period, algorithm, self.resolution)
                self.symbol_data_by_symbol[added.symbol] = symbol_data
            else:
                # a security that was already initialized was re-added, reset the indicators
                symbol_data.fast.reset()
                symbol_data.slow.reset()

        for removed in changes.removed_securities:
            data = self.symbol_data_by_symbol.pop(removed.symbol, None)
            if data is not None:
                # clean up our consolidators
                data.remove_consolidators()

class SymbolData:
    '''Contains data specific to a symbol required by this model'''
    def __init__(self, security, fast_period, slow_period, algorithm, resolution):
        self.security = security
        self.symbol = security.symbol
        self.algorithm = algorithm

        self.fast_consolidator = algorithm.resolve_consolidator(security.symbol, resolution)
        self.slow_consolidator = algorithm.resolve_consolidator(security.symbol, resolution)

        algorithm.subscription_manager.add_consolidator(security.symbol, self.fast_consolidator)
        algorithm.subscription_manager.add_consolidator(security.symbol, self.slow_consolidator)

        # create fast/slow EMAs
        self.fast = ExponentialMovingAverage(security.symbol, fast_period, ExponentialMovingAverage.smoothing_factor_default(fast_period))
        self.slow = ExponentialMovingAverage(security.symbol, slow_period, ExponentialMovingAverage.smoothing_factor_default(slow_period))

        algorithm.register_indicator(security.symbol, self.fast, self.fast_consolidator);
        algorithm.register_indicator(security.symbol, self.slow, self.slow_consolidator);

        algorithm.warm_up_indicator(security.symbol, self.fast, resolution);
        algorithm.warm_up_indicator(security.symbol, self.slow, resolution);

        # True if the fast is above the slow, otherwise false.
        # This is used to prevent emitting the same signal repeatedly
        self.fast_is_over_slow = False

    def remove_consolidators(self):
        self.algorithm.subscription_manager.remove_consolidator(self.security.symbol, self.fast_consolidator)
        self.algorithm.subscription_manager.remove_consolidator(self.security.symbol, self.slow_consolidator)

    @property
    def slow_is_over_fast(self):
        return not self.fast_is_over_slow
```


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
:  Provides an implementation of IAlphaModel that always returns the same insight for each security

Output:
```python

from AlgorithmImports import *

class ConstantAlphaModel(AlphaModel):
    ''' Provides an implementation of IAlphaModel that always returns the same insight for each security'''

    def __init__(self, type, direction, period, magnitude = None, confidence = None, weight = None):
        '''Initializes a new instance of the ConstantAlphaModel class
        Args:
            type: The type of insight
            direction: The direction of the insight
            period: The period over which the insight with come to fruition
            magnitude: The predicted change in magnitude as a +- percentage
            confidence: The confidence in the insight
            weight: The portfolio weight of the insights'''
        self.type = type
        self.direction = direction
        self.period = period
        self.magnitude = magnitude
        self.confidence = confidence
        self.weight = weight
        self.securities = []
        self.insights_time_by_symbol = {}

        self.Name = '{}({},{},{}'.format(self.__class__.__name__, type, direction, strfdelta(period))
        if magnitude is not None:
            self.Name += ',{}'.format(magnitude)
        if confidence is not None:
            self.Name += ',{}'.format(confidence)

        self.Name += ')'

    def update(self, algorithm, data):
        ''' Creates a constant insight for each security as specified via the constructor
        Args:
            algorithm: The algorithm instance
            data: The new data available
        Returns:
            The new insights generated'''
        insights = []

        for security in self.securities:
            # security price could be zero until we get the first data point. e.g. this could happen
            # when adding both forex and equities, we will first get a forex data point
            if security.price != 0 and self.should_emit_insight(algorithm.utc_time, security.symbol):
                insights.append(Insight(security.symbol, self.period, self.type, self.direction, self.magnitude, self.confidence, weight = self.weight))

        return insights

    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:
            self.securities.append(added)

        # this will allow the insight to be re-sent when the security re-joins the universe
        for removed in changes.removed_securities:
            if removed in self.securities:
                self.securities.remove(removed)
            if removed.symbol in self.insights_time_by_symbol:
                self.insights_time_by_symbol.pop(removed.symbol)

    def should_emit_insight(self, utc_time, symbol):
        if symbol.is_canonical():
            # canonical futures & options are none tradable
            return False

        generated_time_utc = self.insights_time_by_symbol.get(symbol)

        if generated_time_utc is not None:
            # we previously emitted a insight for this symbol, check it's period to see
            # if we should emit another insight
            if utc_time - generated_time_utc < self.period:
                return False

        # we either haven't emitted a insight for this symbol or the previous
        # insight's period has expired, so emit a new insight now for this symbol
        self.insights_time_by_symbol[symbol] = utc_time
        return True

def strfdelta(tdelta):
    d = tdelta.days
    h, rem = divmod(tdelta.seconds, 3600)
    m, s = divmod(rem, 60)
    return "{}.{:02d}:{:02d}:{:02d}".format(d,h,m,s)
```


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

Input:
Generate a LEAN RiskManagementModel that can be described like this
: Provides an implementation of IRiskManagementModel that limits the unrealized profit per holding to the specified percentage

Output:
```python

from AlgorithmImports import *

class MaximumUnrealizedProfitPercentPerSecurity(RiskManagementModel):
    '''Provides an implementation of IRiskManagementModel that limits the unrealized profit per holding to the specified percentage'''

    def __init__(self, maximum_unrealized_profit_percent = 0.05):
        '''Initializes a new instance of the MaximumUnrealizedProfitPercentPerSecurity class
        Args:
            maximum_unrealized_profit_percent: The maximum percentage unrealized profit allowed for any single security holding, defaults to 5% drawdown per security'''
        self.maximum_unrealized_profit_percent = abs(maximum_unrealized_profit_percent)

    def manage_risk(self, algorithm, targets):
        '''Manages the algorithm's risk at each time step
        Args:
            algorithm: The algorithm instance
            targets: The current portfolio targets to be assessed for risk'''
        targets = []
        for kvp in algorithm.securities:
            security = kvp.value

            if not security.invested:
                continue

            pnl = security.holdings.unrealized_profit_percent
            if pnl > self.maximum_unrealized_profit_percent:
                symbol = security.symbol

                # Cancel insights
                algorithm.insights.cancel([ symbol ]);

                # liquidate
                targets.append(PortfolioTarget(symbol, 0))

        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 RiskManagementModel that can be described like this
: Provides an implementation of IRiskManagementModel that limits the drawdown per holding to the specified percentage

Output:
```python

from AlgorithmImports import *

class MaximumDrawdownPercentPerSecurity(RiskManagementModel):
    '''Provides an implementation of IRiskManagementModel that limits the drawdown per holding to the specified percentage'''

    def __init__(self, maximum_drawdown_percent = 0.05):
        '''Initializes a new instance of the MaximumDrawdownPercentPerSecurity class
        Args:
            maximum_drawdown_percent: The maximum percentage drawdown allowed for any single security holding'''
        self.maximum_drawdown_percent = -abs(maximum_drawdown_percent)

    def manage_risk(self, algorithm, targets):
        '''Manages the algorithm's risk at each time step
        Args:
            algorithm: The algorithm instance
            targets: The current portfolio targets to be assessed for risk'''
        targets = []
        for kvp in algorithm.securities:
            security = kvp.value

            if not security.invested:
                continue

            pnl = security.holdings.unrealized_profit_percent
            if pnl < self.maximum_drawdown_percent:
                symbol = security.symbol

                # Cancel insights
                algorithm.insights.cancel([symbol])

                # liquidate
                targets.append(PortfolioTarget(symbol, 0))

        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 RiskManagementModel that can be described like this
: Provides an implementation of IRiskManagementModel that that limits the sector exposure to the specified percentage

Output:
```python

from AlgorithmImports import *
from itertools import groupby

class MaximumSectorExposureRiskManagementModel(RiskManagementModel):
    '''Provides an implementation of IRiskManagementModel that that limits the sector exposure to the specified percentage'''

    def __init__(self, maximum_sector_exposure = 0.20):
        '''Initializes a new instance of the MaximumSectorExposureRiskManagementModel class
        Args:
            maximum_drawdown_percent: The maximum exposure for any sector, defaults to 20% sector exposure.'''
        if maximum_sector_exposure <= 0:
            raise ValueError('MaximumSectorExposureRiskManagementModel: the maximum sector exposure cannot be a non-positive value.')

        self.maximum_sector_exposure = maximum_sector_exposure
        self.targets_collection = PortfolioTargetCollection()

    def manage_risk(self, algorithm, targets):
        '''Manages the algorithm's risk at each time step
        Args:
            algorithm: The algorithm instance'''
        maximum_sector_exposure_value = float(algorithm.portfolio.total_portfolio_value) * self.maximum_sector_exposure

        self.targets_collection.add_range(targets)

        risk_targets = list()

        # Group the securities by their sector
        filtered = list(filter(lambda x: x.value.fundamentals is not None and x.value.fundamentals.has_fundamental_data, algorithm.universe_manager.active_securities))
        filtered.sort(key = lambda x: x.value.fundamentals.company_reference.industry_template_code)
        group_by_sector = groupby(filtered, lambda x: x.value.fundamentals.company_reference.industry_template_code)

        for code, securities in group_by_sector:
            # Compute the sector absolute holdings value
            # If the construction model has created a target, we consider that
            # value to calculate the security absolute holding value
            quantities = {}
            sector_absolute_holdings_value = 0

            for security in securities:
                symbol = security.value.symbol
                quantities[symbol] = security.value.holdings.quantity
                absolute_holdings_value = security.value.holdings.absolute_holdings_value

                if self.targets_collection.contains_key(symbol):
                    quantities[symbol] = self.targets_collection[symbol].quantity

                    absolute_holdings_value = (security.value.price * abs(quantities[symbol]) *
                        security.value.symbol_properties.contract_multiplier *
                        security.value.quote_currency.conversion_rate)

                sector_absolute_holdings_value += absolute_holdings_value

            # If the ratio between the sector absolute holdings value and the maximum sector exposure value
            # exceeds the unity, it means we need to reduce each security of that sector by that ratio
            # Otherwise, it means that the sector exposure is below the maximum and there is nothing to do.
            ratio = float(sector_absolute_holdings_value) / maximum_sector_exposure_value

            if ratio > 1:
                for symbol, quantity in quantities.items():
                    if quantity != 0:
                        risk_targets.append(PortfolioTarget(symbol, float(quantity) / ratio))

        return risk_targets

    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'''
        any_fundamental_data = any([
            kvp.value.fundamentals is not None and
            kvp.value.fundamentals.has_fundamental_data for kvp in algorithm.active_securities
            ])

        if not any_fundamental_data:
            raise Exception("MaximumSectorExposureRiskManagementModel.on_securities_changed: Please select a portfolio selection model that selects securities with fundamental data.")
```


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

Input:
Generate a LEAN RiskManagementModel that can be described like this
: Provides an implementation of IRiskManagementModel that limits the maximum possible loss

Output:
```python

from AlgorithmImports import *

class TrailingStopRiskManagementModel(RiskManagementModel):
    '''Provides an implementation of IRiskManagementModel that limits the maximum possible loss
    measured from the highest unrealized profit'''
    def __init__(self, maximum_drawdown_percent = 0.05):
        '''Initializes a new instance of the TrailingStopRiskManagementModel class
        Args:
            maximum_drawdown_percent: The maximum percentage drawdown allowed for algorithm portfolio compared with the highest unrealized profit, defaults to 5% drawdown'''
        self.maximum_drawdown_percent = abs(maximum_drawdown_percent)
        self.trailing_absolute_holdings_state = dict()

    def manage_risk(self, algorithm, targets):
        '''Manages the algorithm's risk at each time step
        Args:
            algorithm: The algorithm instance
            targets: The current portfolio targets to be assessed for risk'''
        risk_adjusted_targets = list()

        for kvp in algorithm.securities:
            symbol = kvp.key
            security = kvp.value

            # Remove if not invested
            if not security.invested:
                self.trailing_absolute_holdings_state.pop(symbol, None)
                continue

            position = PositionSide.LONG if security.holdings.is_long else PositionSide.SHORT
            absolute_holdings_value = security.holdings.absolute_holdings_value
            trailing_absolute_holdings_state = self.trailing_absolute_holdings_state.get(symbol)

            # Add newly invested security (if doesn't exist) or reset holdings state (if position changed)
            if trailing_absolute_holdings_state == None or position != trailing_absolute_holdings_state.position:
                self.trailing_absolute_holdings_state[symbol] = trailing_absolute_holdings_state = self.HoldingsState(position, security.holdings.absolute_holdings_cost)

            trailing_absolute_holdings_value = trailing_absolute_holdings_state.absolute_holdings_value

            # Check for new max (for long position) or min (for short position) absolute holdings value
            if ((position == PositionSide.LONG and trailing_absolute_holdings_value < absolute_holdings_value) or
                (position == PositionSide.SHORT and trailing_absolute_holdings_value > absolute_holdings_value)):
                self.trailing_absolute_holdings_state[symbol].absolute_holdings_value = absolute_holdings_value
                continue

            drawdown = abs((trailing_absolute_holdings_value - absolute_holdings_value) / trailing_absolute_holdings_value)

            if self.maximum_drawdown_percent < drawdown:
                # Cancel insights
                algorithm.insights.cancel([ symbol ]);

                self.trailing_absolute_holdings_state.pop(symbol, None)
                # liquidate
                risk_adjusted_targets.append(PortfolioTarget(symbol, 0))

        return risk_adjusted_targets

    class HoldingsState:
        def __init__(self, position, absolute_holdings_value):
            self.position = position
            self.absolute_holdings_value = absolute_holdings_value
```


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

Input:
Generate a LEAN RiskManagementModel that can be described like this
: Provides an implementation of IRiskManagementModel that limits the drawdown of the portfolio to the specified percentage.

Output:
```python

from AlgorithmImports import *

class MaximumDrawdownPercentPortfolio(RiskManagementModel):
    '''Provides an implementation of IRiskManagementModel that limits the drawdown of the portfolio to the specified percentage.'''

    def __init__(self, maximum_drawdown_percent = 0.05, is_trailing = False):
        '''Initializes a new instance of the MaximumDrawdownPercentPortfolio class
        Args:
            maximum_drawdown_percent: The maximum percentage drawdown allowed for algorithm portfolio compared with starting value, defaults to 5% drawdown</param>
            is_trailing: If "false", the drawdown will be relative to the starting value of the portfolio.
                        If "true", the drawdown will be relative the last maximum portfolio value'''
        self.maximum_drawdown_percent = -abs(maximum_drawdown_percent)
        self.is_trailing = is_trailing
        self.initialised = False
        self.portfolio_high = 0

    def manage_risk(self, algorithm, targets):
        '''Manages the algorithm's risk at each time step
        Args:
            algorithm: The algorithm instance
            targets: The current portfolio targets to be assessed for risk'''
        current_value = algorithm.portfolio.total_portfolio_value

        if not self.initialised:
            self.portfolio_high = current_value   # Set initial portfolio value
            self.initialised = True

        # Update trailing high value if in trailing mode
        if self.is_trailing and self.portfolio_high < current_value:
            self.portfolio_high = current_value
            return []   # return if new high reached

        pnl = self.get_total_drawdown_percent(current_value)
        if pnl < self.maximum_drawdown_percent and len(targets) != 0:
            self.initialised = False # reset the trailing high value for restart investing on next rebalcing period

            risk_adjusted_targets = []
            for target in targets:
                symbol = target.symbol

                # Cancel insights
                algorithm.insights.cancel([symbol])

                # liquidate
                risk_adjusted_targets.append(PortfolioTarget(symbol, 0))
            return risk_adjusted_targets

        return []

    def get_total_drawdown_percent(self, current_value):
        return (float(current_value) / float(self.portfolio_high)) - 1.0
```


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

Input:
Generate a LEAN UniverseSelectionModel that can be described like this
: Provides a base class for defining equity coarse/fine fundamental selection models

Output:
```python

from AlgorithmImports import *

class FundamentalUniverseSelectionModel:
    '''Provides a base class for defining equity coarse/fine fundamental selection models'''

    def __init__(self,
                 filterFineData = None,
                 universeSettings = None):
        '''Initializes a new instance of the FundamentalUniverseSelectionModel class
        Args:
            filterFineData: [Obsolete] Fine and Coarse selection are merged
            universeSettings: The settings used when adding symbols to the algorithm, specify null to use algorithm.UniverseSettings'''
        self.filter_fine_data = filterFineData
        if self.filter_fine_data == None:
            self.fundamental_data = True
        else:
            self.fundamental_data = False
        self.market = Market.USA
        self.universe_settings = universeSettings

    def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:
        '''Creates a new fundamental universe using this class's selection functions
        Args:
            algorithm: The algorithm instance to create universes for
        Returns:
            The universe defined by this model'''
        if self.fundamental_data:
            universe_settings = algorithm.universe_settings if self.universe_settings is None else self.universe_settings
            # handle both 'Select' and 'select' for backwards compatibility
            selection = lambda fundamental: self.select(algorithm, fundamental)
            if hasattr(self, "Select") and callable(self.Select):
                selection = lambda fundamental: self.Select(algorithm, fundamental)
            universe = FundamentalUniverseFactory(self.market, universe_settings, selection)
            return [universe]
        else:
            universe = self.create_coarse_fundamental_universe(algorithm)
            if self.filter_fine_data:
                if universe.universe_settings.asynchronous:
                    raise ValueError("Asynchronous universe setting is not supported for coarse & fine selections, please use the new Fundamental single pass selection")
                selection = lambda fine: self.select_fine(algorithm, fine)
                if hasattr(self, "SelectFine") and callable(self.SelectFine):
                    selection = lambda fine: self.SelectFine(algorithm, fine)
                universe = FineFundamentalFilteredUniverse(universe, selection)
            return [universe]

    def create_coarse_fundamental_universe(self, algorithm: QCAlgorithm) -> Universe:
        '''Creates the coarse fundamental universe object.
        This is provided to allow more flexibility when creating coarse universe.
        Args:
            algorithm: The algorithm instance
        Returns:
            The coarse fundamental universe'''
        universe_settings = algorithm.universe_settings if self.universe_settings is None else self.universe_settings
        return CoarseFundamentalUniverse(universe_settings, lambda coarse: self.filtered_select_coarse(algorithm, coarse))

    def filtered_select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:
        '''Defines the coarse fundamental selection function.
        If we're using fine fundamental selection than exclude symbols without fine data
        Args:
            algorithm: The algorithm instance
            coarse: The coarse fundamental data used to perform filtering
        Returns:
            An enumerable of symbols passing the filter'''
        if self.filter_fine_data:
            fundamental = filter(lambda c: c.has_fundamental_data, fundamental)
        if hasattr(self, "SelectCoarse") and callable(self.SelectCoarse):
            # handle both 'select_coarse' and 'SelectCoarse' for backwards compatibility
            return self.SelectCoarse(algorithm, fundamental)
        return self.select_coarse(algorithm, fundamental)

    def select(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:
        '''Defines the fundamental selection function.
        Args:
            algorithm: The algorithm instance
            fundamental: The fundamental data used to perform filtering
        Returns:
            An enumerable of symbols passing the filter'''
        raise NotImplementedError("Please overrride the 'select' fundamental function")

    def select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:
        '''Defines the coarse fundamental selection function.
        Args:
            algorithm: The algorithm instance
            coarse: The coarse fundamental data used to perform filtering
        Returns:
            An enumerable of symbols passing the filter'''
        raise NotImplementedError("Please overrride the 'select' fundamental function")

    def select_fine(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:
        '''Defines the fine fundamental selection function.
        Args:
            algorithm: The algorithm instance
            fine: The fine fundamental data used to perform filtering
        Returns:
            An enumerable of symbols passing the filter'''
        return [f.symbol for f in fundamental]
```


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

Input:
Generate a LEAN UniverseSelectionModel that can be described like this
: Provides an implementation of IUniverseSelectionMode that subscribes to option chains

Output:
```python

from AlgorithmImports import *
from Selection.UniverseSelectionModel import UniverseSelectionModel

class OptionUniverseSelectionModel(UniverseSelectionModel):
    '''Provides an implementation of IUniverseSelectionMode that subscribes to option chains'''
    def __init__(self,
                 refreshInterval,
                 optionChainSymbolSelector,
                 universeSettings = None):
        '''Creates a new instance of OptionUniverseSelectionModel
        Args:
            refreshInterval: Time interval between universe refreshes</param>
            optionChainSymbolSelector: Selects symbols from the provided option chain
            universeSettings: Universe settings define attributes of created subscriptions, such as their resolution and the minimum time in universe before they can be removed'''
        self.next_refresh_time_utc = datetime.min

        self.refresh_interval = refreshInterval
        self.option_chain_symbol_selector = optionChainSymbolSelector
        self.universe_settings = universeSettings

    def get_next_refresh_time_utc(self):
        '''Gets the next time the framework should invoke the `CreateUniverses` method to refresh the set of universes.'''
        return self.next_refresh_time_utc

    def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:
        '''Creates a new fundamental universe using this class's selection functions
        Args:
            algorithm: The algorithm instance to create universes for
        Returns:
            The universe defined by this model'''
        self.next_refresh_time_utc = (algorithm.utc_time + self.refresh_interval).date()

        uniqueUnderlyingSymbols = set()
        for option_symbol in self.option_chain_symbol_selector(algorithm.utc_time):
            if not Extensions.is_option(option_symbol.security_type):
                raise ValueError("optionChainSymbolSelector must return option, index options, or futures options symbols.")

            # prevent creating duplicate option chains -- one per underlying
            if option_symbol.underlying not in uniqueUnderlyingSymbols:
                uniqueUnderlyingSymbols.add(option_symbol.underlying)
                selection = self.filter
                if hasattr(self, "Filter") and callable(self.Filter):
                    selection = self.Filter
                yield Extensions.create_option_chain(algorithm, option_symbol, selection, self.universe_settings)

    def filter(self, filter):
        '''Defines the option chain universe filter'''
        # NOP
        return filter
```


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

Input:
Generate a LEAN UniverseSelectionModel that can be described like this
: Universe selection model that selects the constituents of an ETF.

Output:
```python

from AlgorithmImports import *
from Selection.UniverseSelectionModel import UniverseSelectionModel

class ETFConstituentsUniverseSelectionModel(UniverseSelectionModel):
    '''Universe selection model that selects the constituents of an ETF.'''

    def __init__(self,
                 etf_symbol,
                 universe_settings = None,
                 universe_filter_func = None):
        '''Initializes a new instance of the ETFConstituentsUniverseSelectionModel class
        Args:
            etfSymbol: Symbol of the ETF to get constituents for
            universeSettings: Universe settings
            universeFilterFunc: Function to filter universe results'''
        if type(etf_symbol) is str:
            symbol = SymbolCache.try_get_symbol(etf_symbol, None)
            if symbol[0] and symbol[1].security_type == SecurityType.EQUITY:
                self.etf_symbol = symbol[1]
            else:
                self.etf_symbol = Symbol.create(etf_symbol, SecurityType.EQUITY, Market.USA)
        else:
            self.etf_symbol = etf_symbol
        self.universe_settings = universe_settings
        self.universe_filter_function = universe_filter_func

        self.universe = None

    def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:
        '''Creates a new ETF constituents universe using this class's selection function
        Args:
            algorithm: The algorithm instance to create universes for
        Returns:
            The universe defined by this model'''
        if self.universe is None:
            self.universe = algorithm.universe.etf(self.etf_symbol, self.universe_settings, self.universe_filter_function)
        return [self.universe]
```


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

Input:
Generate a LEAN UniverseSelectionModel that can be described like this
: Defines the QC500 universe as a universe selection model for framework algorithm

Output:
```python

from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
from itertools import groupby
from math import ceil

class QC500UniverseSelectionModel(FundamentalUniverseSelectionModel):
    '''Defines the QC500 universe as a universe selection model for framework algorithm
    For details: https://github.com/QuantConnect/Lean/pull/1663'''

    def __init__(self, filterFineData = True, universeSettings = None):
        '''Initializes a new default instance of the QC500UniverseSelectionModel'''
        super().__init__(filterFineData, universeSettings)
        self.number_of_symbols_coarse = 1000
        self.number_of_symbols_fine = 500
        self.dollar_volume_by_symbol = {}
        self.last_month = -1

    def select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]):
        '''Performs coarse selection for the QC500 constituents.
        The stocks must have fundamental data
        The stock must have positive previous-day close price
        The stock must have positive volume on the previous trading day'''
        if algorithm.time.month == self.last_month:
            return Universe.UNCHANGED

        sorted_by_dollar_volume = sorted([x for x in fundamental if x.has_fundamental_data and x.volume > 0 and x.price > 0],
                                     key = lambda x: x.dollar_volume, reverse=True)[:self.number_of_symbols_coarse]

        self.dollar_volume_by_symbol = {x.Symbol:x.dollar_volume for x in sorted_by_dollar_volume}

        # If no security has met the QC500 criteria, the universe is unchanged.
        # A new selection will be attempted on the next trading day as self.lastMonth is not updated
        if len(self.dollar_volume_by_symbol) == 0:
            return Universe.UNCHANGED

        # return the symbol objects our sorted collection
        return list(self.dollar_volume_by_symbol.keys())

    def select_fine(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]):
        '''Performs fine selection for the QC500 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'''

        sorted_by_sector = sorted([x for x in fundamental if x.company_reference.country_id == "USA"
                                        and x.company_reference.primary_exchange_id in ["NYS","NAS"]
                                        and (algorithm.time - x.security_reference.ipo_date).days > 180
                                        and x.market_cap > 5e8],
                               key = lambda x: x.company_reference.industry_template_code)

        count = len(sorted_by_sector)

        # If no security has met the QC500 criteria, the universe is unchanged.
        # A new selection will be attempted on the next trading day as self.lastMonth is not updated
        if count == 0:
            return Universe.UNCHANGED

        # Update self.lastMonth after all QC500 criteria checks passed
        self.last_month = algorithm.time.month

        percent = self.number_of_symbols_fine / count
        sorted_by_dollar_volume = []

        # select stocks with top dollar volume in every single sector
        for code, g in groupby(sorted_by_sector, lambda x: x.company_reference.industry_template_code):
            y = sorted(g, key = lambda x: self.dollar_volume_by_symbol[x.Symbol], reverse = True)
            c = ceil(len(y) * percent)
            sorted_by_dollar_volume.extend(y[:c])

        sorted_by_dollar_volume = sorted(sorted_by_dollar_volume, key = lambda x: self.dollar_volume_by_symbol[x.Symbol], reverse=True)
        return [x.Symbol for x in sorted_by_dollar_volume[:self.number_of_symbols_fine]]
```


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

Input:
Generate a LEAN UniverseSelectionModel that can be described like this
: Provides an implementation of IUniverseSelectionMode that subscribes to future chains

Output:
```python

from AlgorithmImports import *

from Selection.UniverseSelectionModel import UniverseSelectionModel

class FutureUniverseSelectionModel(UniverseSelectionModel):
    '''Provides an implementation of IUniverseSelectionMode that subscribes to future chains'''
    def __init__(self,
                 refreshInterval,
                 futureChainSymbolSelector,
                 universeSettings = None):
        '''Creates a new instance of FutureUniverseSelectionModel
        Args:
            refreshInterval: Time interval between universe refreshes</param>
            futureChainSymbolSelector: Selects symbols from the provided future chain
            universeSettings: Universe settings define attributes of created subscriptions, such as their resolution and the minimum time in universe before they can be removed'''
        self.next_refresh_time_utc = datetime.min

        self.refresh_interval = refreshInterval
        self.future_chain_symbol_selector = futureChainSymbolSelector
        self.universe_settings = universeSettings

    def get_next_refresh_time_utc(self):
        '''Gets the next time the framework should invoke the `CreateUniverses` method to refresh the set of universes.'''
        return self.next_refresh_time_utc

    def create_universes(self, algorithm: QCAlgorithm) -> list[Universe]:
        '''Creates a new fundamental universe using this class's selection functions
        Args:
            algorithm: The algorithm instance to create universes for
        Returns:
            The universe defined by this model'''
        self.next_refresh_time_utc = algorithm.utc_time + self.refresh_interval

        unique_symbols = set()
        for future_symbol in self.future_chain_symbol_selector(algorithm.utc_time):
            if future_symbol.SecurityType != SecurityType.FUTURE:
                raise ValueError("futureChainSymbolSelector must return future symbols.")

            # prevent creating duplicate future chains -- one per symbol
            if future_symbol not in unique_symbols:
                unique_symbols.add(future_symbol)
                selection = self.filter
                if hasattr(self, "Filter") and callable(self.Filter):
                    selection = self.Filter
                for universe in Extensions.create_future_chain(algorithm, future_symbol, selection, self.universe_settings):
                    yield universe

    def filter(self, filter):
        '''Defines the future chain universe filter'''
        # NOP
        return filter
```


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

Input:
Generate a LEAN UniverseSelectionModel that can be described like this
: Provides an implementation of FundamentalUniverseSelectionModel that subscribes to

Output:
```python

from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel

class EmaCrossUniverseSelectionModel(FundamentalUniverseSelectionModel):
    '''Provides an implementation of FundamentalUniverseSelectionModel that subscribes to
    symbols with the larger delta by percentage between the two exponential moving average'''

    def __init__(self,
                 fastPeriod = 100,
                 slowPeriod = 300,
                 universeCount = 500,
                 universeSettings = None):
        '''Initializes a new instance of the EmaCrossUniverseSelectionModel class
        Args:
            fastPeriod: Fast EMA period
            slowPeriod: Slow EMA period
            universeCount: Maximum number of members of this universe selection
            universeSettings: The settings used when adding symbols to the algorithm, specify null to use algorithm.UniverseSettings'''
        super().__init__(False, universeSettings)
        self.fast_period = fastPeriod
        self.slow_period = slowPeriod
        self.universe_count = universeCount
        self.tolerance = 0.01
        # holds our coarse fundamental indicators by symbol
        self.averages = {}

    def select_coarse(self, algorithm: QCAlgorithm, fundamental: list[Fundamental]) -> list[Symbol]:
        '''Defines the coarse fundamental selection function.
        Args:
            algorithm: The algorithm instance
            fundamental: The coarse fundamental data used to perform filtering</param>
        Returns:
            An enumerable of symbols passing the filter'''
        filtered = []

        for cf in fundamental:
            if cf.symbol not in self.averages:
                self.averages[cf.symbol] = self.SelectionData(cf.symbol, self.fast_period, self.slow_period)

            # grab th SelectionData instance for this symbol
            avg = self.averages.get(cf.symbol)

            # Update returns true when the indicators are ready, so don't accept until they are
            # and only pick symbols who have their fastPeriod-day ema over their slowPeriod-day ema
            if avg.update(cf.end_time, cf.adjusted_price) and avg.fast > avg.slow * (1 + self.tolerance):
                filtered.append(avg)

        # prefer symbols with a larger delta by percentage between the two averages
        filtered = sorted(filtered, key=lambda avg: avg.scaled_delta, reverse = True)

        # we only need to return the symbol and return 'universeCount' symbols
        return [x.symbol for x in filtered[:self.universe_count]]

    # class used to improve readability of the coarse selection function
    class SelectionData:
        def __init__(self, symbol, fast_period, slow_period):
            self.symbol = symbol
            self.fast_ema = ExponentialMovingAverage(fast_period)
            self.slow_ema = ExponentialMovingAverage(slow_period)

        @property
        def fast(self):
            return float(self.fast_ema.current.value)

        @property
        def slow(self):
            return float(self.slow_ema.current.value)

        # computes an object score of how much large the fast is than the slow
        @property
        def scaled_delta(self):
            return (self.fast - self.slow) / ((self.fast + self.slow) / 2)

        # updates the EMAFast and EMASlow indicators, returning true when they're both ready
        def update(self, time, value):
            return self.slow_ema.update(time, value) & self.fast_ema.update(time, value)
```


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

Input:
Generate a LEAN PortfolioConstructionModel that can be described like this
: Provides an implementation of Mean-Variance portfolio optimization based on modern portfolio theory.
The default model uses the MinimumVariancePortfolioOptimizer that accepts a 63-row matrix of 1-day returns.

Output:
```python

from AlgorithmImports import *
from Portfolio.MinimumVariancePortfolioOptimizer import MinimumVariancePortfolioOptimizer

class MeanVarianceOptimizationPortfolioConstructionModel(PortfolioConstructionModel):
    def __init__(self,
                 rebalance = Resolution.DAILY,
                 portfolio_bias = PortfolioBias.LONG_SHORT,
                 lookback = 1,
                 period = 63,
                 resolution = Resolution.DAILY,
                 target_return = 0.02,
                 optimizer = None):
        """Initialize the model
        Args:
            rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.
                              If None will be ignored.
                              The function returns the next expected rebalance time for a given algorithm UTC DateTime.
                              The function returns null if unknown, in which case the function will be called again in the
                              next loop. Returning current time will trigger rebalance.
            portfolio_bias: Specifies the bias of the portfolio (Short, Long/Short, Long)
            lookback(int): Historical return lookback period
            period(int): The time interval of history price to calculate the weight
            resolution: The resolution of the history price
            optimizer(class): Method used to compute the portfolio weights"""
        super().__init__()
        self.lookback = lookback
        self.period = period
        self.resolution = resolution
        self.portfolio_bias = portfolio_bias
        self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)

        lower = 0 if portfolio_bias == PortfolioBias.LONG else -1
        upper = 0 if portfolio_bias == PortfolioBias.SHORT else 1
        self.optimizer = MinimumVariancePortfolioOptimizer(lower, upper, target_return) if optimizer is None else optimizer

        self.symbol_data_by_symbol = {}

        # If the argument is an instance of Resolution or Timedelta
        # Redefine rebalancing_func
        rebalancing_func = rebalance
        if isinstance(rebalance, Resolution):
            rebalance = Extensions.to_time_span(rebalance)
        if isinstance(rebalance, timedelta):
            rebalancing_func = lambda dt: dt + rebalance
        if rebalancing_func:
            self.set_rebalancing_func(rebalancing_func)

    def should_create_target_for_insight(self, insight):
        if len(PortfolioConstructionModel.filter_invalid_insight_magnitude(self.algorithm, [insight])) == 0:
            return False

        symbol_data = self.symbol_data_by_symbol.get(insight.symbol)
        if insight.magnitude is None:
            self.algorithm.set_run_time_error(ArgumentNullException('MeanVarianceOptimizationPortfolioConstructionModel does not accept \'None\' as Insight.magnitude. Please checkout the selected Alpha Model specifications.'))
            return False
        symbol_data.add(self.algorithm.time, insight.magnitude)

        return True

    def determine_target_percent(self, active_insights):
        """
         Will determine the target percent for each insight
        Args:
        Returns:
        """
        targets = {}

        # If we have no insights just return an empty target list
        if len(active_insights) == 0:
            return targets

        symbols = [insight.symbol for insight in active_insights]

        # Create a dictionary keyed by the symbols in the insights with an pandas.series as value to create a data frame
        returns = { str(symbol.id) : data.return_ for symbol, data in self.symbol_data_by_symbol.items() if symbol in symbols }
        returns = pd.DataFrame(returns)

        # The portfolio optimizer finds the optional weights for the given data
        weights = self.optimizer.optimize(returns)
        weights = pd.Series(weights, index = returns.columns)

        # Create portfolio targets from the specified insights
        for insight in active_insights:
            weight = weights[str(insight.symbol.id)]

            # don't trust the optimizer
            if self.portfolio_bias != PortfolioBias.LONG_SHORT and self.sign(weight) != self.portfolio_bias:
                weight = 0
            targets[insight] = weight

        return targets

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

        # clean up data for removed securities
        super().on_securities_changed(algorithm, changes)
        for removed in changes.removed_securities:
            symbol_data = self.symbol_data_by_symbol.pop(removed.symbol, None)
            symbol_data.reset()

        # initialize data for added securities
        symbols = [x.symbol for x in changes.added_securities]
        for symbol in [x for x in symbols if x not in self.symbol_data_by_symbol]:
            self.symbol_data_by_symbol[symbol] = self.MeanVarianceSymbolData(symbol, self.lookback, self.period)

        history = algorithm.history[TradeBar](symbols, self.lookback * self.period, self.resolution)
        for bars in history:
            for symbol, bar in bars.items():
                symbol_data = self.symbol_data_by_symbol.get(symbol).update(bar.end_time, bar.value)

    class MeanVarianceSymbolData:
        '''Contains data specific to a symbol required by this model'''
        def __init__(self, symbol, lookback, period):
            self._symbol = symbol
            self.roc = RateOfChange(f'{symbol}.roc({lookback})', lookback)
            self.roc.updated += self.on_rate_of_change_updated
            self.window = RollingWindow(period)

        def reset(self):
            self.roc.updated -= self.on_rate_of_change_updated
            self.roc.reset()
            self.window.reset()

        def update(self, time, value):
            return self.roc.update(time, value)

        def on_rate_of_change_updated(self, roc, value):
            if roc.is_ready:
                self.window.add(value)

        def add(self, time, value):
            item = IndicatorDataPoint(self._symbol, time, value)
            self.window.add(item)

        # Get symbols' returns, we use simple return according to
        # Meucci, Attilio, Quant Nugget 2: Linear vs. Compounded Returns – Common Pitfalls in Portfolio Management (May 1, 2010).
        # GARP Risk Professional, pp. 49-51, April 2010 , Available at SSRN: https://ssrn.com/abstract=1586656
        @property
        def return_(self):
            return pd.Series(
                data = [x.value for x in self.window],
                index = [x.end_time for x in self.window])

        @property
        def is_ready(self):
            return self.window.is_ready

        def __str__(self, **kwargs):
            return '{}: {:.2%}'.format(self.roc.name, self.window[0])
```