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 Black-Litterman portfolio optimization. The model adjusts equilibrium market
returns by incorporating views from multiple alpha models and therefore to get the optimal risky portfolio
reflecting those views. If insights of all alpha models have None magnitude or there are linearly dependent
vectors in link matrix of views, the expected return would be the implied excess equilibrium return.
The interval of weights in optimization method can be changed based on the long-short algorithm.
The default model uses the 0.0025 as weight-on-views scalar parameter tau and
MaximumSharpeRatioPortfolioOptimizer that accepts a 63-row matrix of 1-day returns.

Output:
```python

from AlgorithmImports import *
from Portfolio.MaximumSharpeRatioPortfolioOptimizer import MaximumSharpeRatioPortfolioOptimizer
from itertools import groupby
from numpy import dot, transpose
from numpy.linalg import inv

class BlackLittermanOptimizationPortfolioConstructionModel(PortfolioConstructionModel):
    def __init__(self,
                 rebalance = Resolution.DAILY,
                 portfolio_bias = PortfolioBias.LONG_SHORT,
                 lookback = 1,
                 period = 63,
                 resolution = Resolution.DAILY,
                 risk_free_rate = 0,
                 delta = 2.5,
                 tau = 0.05,
                 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
            risk_free_rate(float): The risk free rate
            delta(float): The risk aversion coeffficient of the market portfolio
            tau(float): The model parameter indicating the uncertainty of the CAPM prior"""
        super().__init__()
        self.lookback = lookback
        self.period = period
        self.resolution = resolution
        self.risk_free_rate = risk_free_rate
        self.delta = delta
        self.tau = tau
        self.portfolio_bias = portfolio_bias

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

        self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)
        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):
        return PortfolioConstructionModel.filter_invalid_insight_magnitude(self.algorithm, [ insight ])

    def determine_target_percent(self, last_active_insights):
        targets = {}

        # Get view vectors
        p, q = self.get_views(last_active_insights)
        if p is not None:
            returns = dict()
            # Updates the BlackLittermanSymbolData with insights
            # Create a dictionary keyed by the symbols in the insights with an pandas.Series as value to create a data frame
            for insight in last_active_insights:
                symbol = insight.symbol
                symbol_data = self.symbol_data_by_symbol.get(symbol, self.BlackLittermanSymbolData(symbol, self.lookback, self.period))
                if insight.magnitude is None:
                    self.algorithm.set_run_time_error(ArgumentNullException('BlackLittermanOptimizationPortfolioConstructionModel does not accept \'None\' as Insight.magnitude. Please make sure your Alpha Model is generating Insights with the Magnitude property set.'))
                    return targets
                symbol_data.add(insight.generated_time_utc, insight.magnitude)
                returns[symbol] = symbol_data.return_

            returns = pd.DataFrame(returns)

            # Calculate prior estimate of the mean and covariance
            pi, sigma = self.get_equilibrium_return(returns)

            # Calculate posterior estimate of the mean and covariance
            pi, sigma = self.apply_blacklitterman_master_formula(pi, sigma, p, q)

            # Create portfolio targets from the specified insights
            weights = self.optimizer.optimize(returns, pi, sigma)
            weights = pd.Series(weights, index = sigma.columns)

            for symbol, weight in weights.items():
                for insight in last_active_insights:
                    if str(insight.symbol) == str(symbol):
                        # don't trust the optimizer
                        if self.portfolio_bias != PortfolioBias.LONG_SHORT and self.sign(weight) != self.portfolio_bias:
                            weight = 0
                        targets[insight] = weight
                        break

        return targets

    def get_target_insights(self):
        # Get insight that haven't expired of each symbol that is still in the universe
        active_insights = filter(self.should_create_target_for_insight,
            self.algorithm.insights.get_active_insights(self.algorithm.utc_time))

        # Get the last generated active insight for each symbol
        last_active_insights = []
        for source_model, f in groupby(sorted(active_insights, key = lambda ff: ff.source_model), lambda fff: fff.source_model):
            for symbol, g in groupby(sorted(list(f), key = lambda gg: gg.symbol), lambda ggg: ggg.symbol):
                last_active_insights.append(sorted(g, key = lambda x: x.generated_time_utc)[-1])
        return last_active_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'''

        # Get removed symbol and invalidate them in the insight collection
        super().on_securities_changed(algorithm, changes)

        for security in changes.removed_securities:
            symbol = security.symbol
            symbol_data = self.symbol_data_by_symbol.pop(symbol, None)
            if symbol_data is not None:
                symbol_data.reset()

        # initialize data for added securities
        added_symbols = { x.symbol: x.exchange.time_zone for x in changes.added_securities }
        history = algorithm.history(list(added_symbols.keys()), self.lookback * self.period, self.resolution)

        if history.empty:
            return

        history = history.close.unstack(0)
        symbols = history.columns

        for symbol, timezone in added_symbols.items():
            if str(symbol) not in symbols:
                continue

            symbol_data = self.symbol_data_by_symbol.get(symbol, self.BlackLittermanSymbolData(symbol, self.lookback, self.period))
            for time, close in history[symbol].items():
                utc_time = Extensions.convert_to_utc(time, timezone)
                symbol_data.update(utc_time, close)

            self.symbol_data_by_symbol[symbol] = symbol_data

    def apply_blacklitterman_master_formula(self, Pi, Sigma, P, Q):
        '''Apply Black-Litterman master formula
        http://www.blacklitterman.org/cookbook.html
        Args:
            Pi: Prior/Posterior mean array
            Sigma: Prior/Posterior covariance matrix
            P: A matrix that identifies the assets involved in the views (size: K x N)
            Q: A view vector (size: K x 1)'''
        ts = self.tau * Sigma

        # Create the diagonal Sigma matrix of error terms from the expressed views
        omega = np.dot(np.dot(P, ts), P.T) * np.eye(Q.shape[0])
        if np.linalg.det(omega) == 0:
            return Pi, Sigma

        A = np.dot(np.dot(ts, P.T), inv(np.dot(np.dot(P, ts), P.T) + omega))

        Pi = np.squeeze(np.asarray((
            np.expand_dims(Pi, axis=0).T +
            np.dot(A, (Q - np.expand_dims(np.dot(P, Pi.T), axis=1))))
            ))

        M = ts - np.dot(np.dot(A, P), ts)
        Sigma = (Sigma + M) * self.delta

        return Pi, Sigma

    def get_equilibrium_return(self, returns):
        '''Calculate equilibrium returns and covariance
        Args:
            returns: Matrix of returns where each column represents a security and each row returns for the given date/time (size: K x N)
        Returns:
            equilibrium_return: Array of double of equilibrium returns
            cov: Multi-dimensional array of double with the portfolio covariance of returns (size: K x K)'''

        size = len(returns.columns)
        # equal weighting scheme
        W = np.array([1/size]*size)
        # the covariance matrix of excess returns (N x N matrix)
        cov = returns.cov()*252
        # annualized return
        annual_return = np.sum(((1 + returns.mean())**252 -1) * W)
        # annualized variance of return
        annual_variance = dot(W.T, dot(cov, W))
        # the risk aversion coefficient
        risk_aversion = (annual_return - self.risk_free_rate ) / annual_variance
        # the implied excess equilibrium return Vector (N x 1 column vector)
        equilibrium_return = dot(dot(risk_aversion, cov), W)

        return equilibrium_return, cov

    def get_views(self, insights):
        '''Generate views from multiple alpha models
        Args
            insights: Array of insight that represent the investors' views
        Returns
            P: A matrix that identifies the assets involved in the views (size: K x N)
            Q: A view vector (size: K x 1)'''
        try:
            P = {}
            Q = {}
            symbols = set(insight.symbol for insight in insights)

            for model, group in groupby(insights, lambda x: x.source_model):
                group = list(group)

                up_insights_sum = 0.0
                dn_insights_sum = 0.0
                for insight in group:
                    if insight.direction == InsightDirection.UP:
                        up_insights_sum = up_insights_sum + np.abs(insight.magnitude)
                    if insight.direction == InsightDirection.DOWN:
                        dn_insights_sum = dn_insights_sum + np.abs(insight.magnitude)

                q = up_insights_sum if up_insights_sum > dn_insights_sum else dn_insights_sum
                if q == 0:
                    continue

                Q[model] = q

                # generate the link matrix of views: P
                P[model] = dict()
                for insight in group:
                    value = insight.direction * np.abs(insight.magnitude)
                    P[model][insight.symbol] = value / q
                # Add zero for other symbols that are listed but active insight
                for symbol in symbols:
                    if symbol not in P[model]:
                        P[model][symbol] = 0

            Q = np.array([[x] for x in Q.values()])
            if len(Q) > 0:
                P = np.array([list(x.values()) for x in P.values()])
                return P, Q
        except:
            pass

        return None, None

    class BlackLittermanSymbolData:
        '''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, utc_time, close):
            self.roc.update(utc_time, close)

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

        def add(self, time, value):
            if self.window.samples > 0 and self.window[0].end_time == time:
                return

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

        @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 f'{self.roc.name}: {(1 + self.window[0])**252 - 1:.2%}'
```


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 IPortfolioConstructionModel that gives equal weighting to all securities.

Output:
```python

from AlgorithmImports import *

class EqualWeightingPortfolioConstructionModel(PortfolioConstructionModel):
    '''Provides an implementation of IPortfolioConstructionModel that gives equal weighting to all securities.
    The target percent holdings of each security is 1/N where N is the number of securities.
    For insights of direction InsightDirection.UP, long targets are returned and
    for insights of direction InsightDirection.DOWN, short targets are returned.'''

    def __init__(self, rebalance = Resolution.DAILY, portfolio_bias = PortfolioBias.LONG_SHORT):
        '''Initialize a new instance of EqualWeightingPortfolioConstructionModel
        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)'''
        super().__init__()
        self.portfolio_bias = portfolio_bias

        # 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 determine_target_percent(self, active_insights):
        '''Will determine the target percent for each insight
        Args:
            active_insights: The active insights to generate a target for'''
        result = {}

        # give equal weighting to each security
        count = sum(x.direction != InsightDirection.FLAT and self.respect_portfolio_bias(x) for x in active_insights)
        percent = 0 if count == 0 else 1.0 / count
        for insight in active_insights:
            result[insight] = (insight.direction if self.respect_portfolio_bias(insight) else InsightDirection.FLAT) * percent
        return result

    def respect_portfolio_bias(self, insight):
        '''Method that will determine if a given insight respects the portfolio bias
        Args:
            insight: The insight to create a target for
        '''
        return self.portfolio_bias == PortfolioBias.LONG_SHORT or insight.direction == self.portfolio_bias
```


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 IPortfolioConstructionModel that allocates percent of account

Output:
```python

from AlgorithmImports import *
from EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel

class AccumulativeInsightPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):
    '''Provides an implementation of IPortfolioConstructionModel that allocates percent of account
    to each insight, defaulting to 3%.
    For insights of direction InsightDirection.UP, long targets are returned and
    for insights of direction InsightDirection.DOWN, short targets are returned.
    By default, no rebalancing shall be done.
    Rules:
        1. On active Up insight, increase position size by percent
        2. On active Down insight, decrease position size by percent
        3. On active Flat insight, move by percent towards 0
        4. On expired insight, and no other active insight, emits a 0 target'''

    def __init__(self,  rebalance = None, portfolio_bias = PortfolioBias.LONG_SHORT, percent = 0.03):
        '''Initialize a new instance of AccumulativeInsightPortfolioConstructionModel
        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)
            percent: percent of portfolio to allocate to each position'''
        super().__init__(rebalance)
        self.portfolio_bias = portfolio_bias
        self.percent = abs(percent)
        self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)

    def determine_target_percent(self, active_insights):
        '''Will determine the target percent for each insight
        Args:
            active_insights: The active insights to generate a target for'''
        percent_per_symbol = {}

        insights = sorted(self.algorithm.insights.get_active_insights(self.current_utc_time), key=lambda insight: insight.generated_time_utc)

        for insight in insights:
            target_percent = 0
            if insight.symbol in percent_per_symbol:
                target_percent = percent_per_symbol[insight.symbol]
                if insight.direction == InsightDirection.FLAT:
                    # We received a Flat
                    # if adding or subtracting will push past 0, then make it 0
                    if abs(target_percent) < self.percent:
                        target_percent = 0
                    else:
                        # otherwise, we flatten by percent
                        target_percent += (-self.percent if target_percent > 0 else self.percent)
            target_percent += self.percent * insight.direction

            # adjust to respect portfolio bias
            if self.portfolio_bias != PortfolioBias.LONG_SHORT and self.sign(target_percent) != self.portfolio_bias:
                target_percent = 0

            percent_per_symbol[insight.symbol] = target_percent

        return dict((insight, percent_per_symbol[insight.symbol]) for insight in active_insights)

    def create_targets(self, algorithm, insights):
        '''Create portfolio targets from the specified insights
        Args:
            algorithm: The algorithm instance
            insights: The insights to create portfolio targets from
        Returns:
            An enumerable of portfolio targets to be sent to the execution model'''
        self.current_utc_time = algorithm.utc_time
        return super().create_targets(algorithm, insights)
```


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 IPortfolioConstructionModel that generates percent targets based on the

Output:
```python

from AlgorithmImports import *
from EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel

class InsightWeightingPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):
    '''Provides an implementation of IPortfolioConstructionModel that generates percent targets based on the
    Insight.WEIGHT. The target percent holdings of each Symbol is given by the Insight.WEIGHT from the last
    active Insight for that symbol.
    For insights of direction InsightDirection.UP, long targets are returned and for insights of direction
    InsightDirection.DOWN, short targets are returned.
    If the sum of all the last active Insight per symbol is bigger than 1, it will factor down each target
    percent holdings proportionally so the sum is 1.
    It will ignore Insight that have no Insight.WEIGHT value.'''

    def __init__(self, rebalance = Resolution.DAILY, portfolio_bias = PortfolioBias.LONG_SHORT):
        '''Initialize a new instance of InsightWeightingPortfolioConstructionModel
        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)'''
        super().__init__(rebalance, portfolio_bias)

    def should_create_target_for_insight(self, insight):
        '''Method that will determine if the portfolio construction model should create a
        target for this insight
        Args:
            insight: The insight to create a target for'''
        # Ignore insights that don't have Weight value
        return insight.weight is not None

    def determine_target_percent(self, active_insights):
        '''Will determine the target percent for each insight
        Args:
            active_insights: The active insights to generate a target for'''
        result = {}

        # We will adjust weights proportionally in case the sum is > 1 so it sums to 1.
        weight_sums = sum(self.get_value(insight) for insight in active_insights if self.respect_portfolio_bias(insight))
        weight_factor = 1.0
        if weight_sums > 1:
            weight_factor = 1 / weight_sums
        for insight in active_insights:
            result[insight] = (insight.direction if self.respect_portfolio_bias(insight) else InsightDirection.FLAT) * self.get_value(insight) * weight_factor
        return result

    def get_value(self, insight):
        '''Method that will determine which member will be used to compute the weights and gets its value
        Args:
            insight: The insight to create a target for
        Returns:
            The value of the selected insight member'''
        return abs(insight.weight)
```


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 IPortfolioConstructionModel that

Output:
```python

from AlgorithmImports import *
from EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel

class SectorWeightingPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):
    '''Provides an implementation of IPortfolioConstructionModel that
   generates percent targets based on the CompanyReference.industry_template_code.
   The target percent holdings of each sector is 1/S where S is the number of sectors and
   the target percent holdings of each security is 1/N where N is the number of securities of each sector.
   For insights of direction InsightDirection.UP, long targets are returned and for insights of direction
   InsightDirection.DOWN, short targets are returned.
   It will ignore Insight for symbols that have no CompanyReference.industry_template_code'''

    def __init__(self, rebalance = Resolution.DAILY):
        '''Initialize a new instance of InsightWeightingPortfolioConstructionModel
        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.'''
        super().__init__(rebalance)
        self.sector_code_by_symbol = dict()

    def should_create_target_for_insight(self, insight):
        '''Method that will determine if the portfolio construction model should create a
        target for this insight
        Args:
            insight: The insight to create a target for'''
        return insight.symbol in self.sector_code_by_symbol

    def determine_target_percent(self, active_insights):
        '''Will determine the target percent for each insight
        Args:
            active_insights: The active insights to generate a target for'''
        result = dict()

        insight_by_sector_code = dict()

        for insight in active_insights:
            if insight.direction == InsightDirection.FLAT:
                result[insight] = 0
                continue

            sector_code = self.sector_code_by_symbol.get(insight.symbol)
            insights = insight_by_sector_code.pop(sector_code, list())

            insights.append(insight)
            insight_by_sector_code[sector_code] = insights

        # give equal weighting to each sector
        sector_percent = 0 if len(insight_by_sector_code) == 0 else 1.0 / len(insight_by_sector_code)

        for _, insights in insight_by_sector_code.items():
            # give equal weighting to each security
            count = len(insights)
            percent = 0 if count == 0 else sector_percent / count
            for insight in insights:
                result[insight] = insight.direction * percent

        return result

    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.removed_securities:
            # Removes the symbol from the self.sector_code_by_symbol dictionary
            # since we cannot emit PortfolioTarget for removed securities
            self.sector_code_by_symbol.pop(security.symbol, None)

        for security in changes.added_securities:
            sector_code = self.get_sector_code(security)
            if sector_code:
                self.sector_code_by_symbol[security.symbol] = sector_code

        super().on_securities_changed(algorithm, changes)

    def get_sector_code(self, security):
        '''Gets the sector code
        Args:
            security: The security to create a sector code for
        Returns:
            The value of the sector code for the security
        Remarks:
            Other sectors can be defined using AssetClassification'''
        fundamentals = security.fundamentals
        company_reference = security.fundamentals.company_reference if fundamentals else None
        return company_reference.industry_template_code if company_reference else None
```


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
: Implementation of On-Line Moving Average Reversion (OLMAR)

Output:
```python

from AlgorithmImports import *

class MeanReversionPortfolioConstructionModel(PortfolioConstructionModel):

    def __init__(self,
                 rebalance = Resolution.Daily,
                 portfolioBias = PortfolioBias.LongShort,
                 reversion_threshold = 1,
                 window_size = 20,
                 resolution = Resolution.Daily):
        """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.
            portfolioBias: Specifies the bias of the portfolio (Short, Long/Short, Long)
            reversion_threshold: Reversion threshold
            window_size: Window size of mean price calculation
            resolution: The resolution of the history price and rebalancing
        """
        super().__init__()
        if portfolioBias == PortfolioBias.Short:
            raise ArgumentException("Long position must be allowed in MeanReversionPortfolioConstructionModel.")

        self.reversion_threshold = reversion_threshold
        self.window_size = window_size
        self.resolution = resolution

        self.num_of_assets = 0
        # Initialize a dictionary to store stock data
        self.symbol_data = {}

        # If the argument is an instance of Resolution or Timedelta
        # Redefine rebalancingFunc
        rebalancingFunc = rebalance
        if isinstance(rebalance, int):
            rebalance = Extensions.ToTimeSpan(rebalance)
        if isinstance(rebalance, timedelta):
            rebalancingFunc = lambda dt: dt + rebalance
        if rebalancingFunc:
            self.SetRebalancingFunc(rebalancingFunc)

    def DetermineTargetPercent(self, activeInsights):
        """Will determine the target percent for each insight
        Args:
            activeInsights: list of active insights
        Returns:
            dictionary of insight and respective target weight
        """
        targets = {}

        # If we have no insights or non-ready just return an empty target list
        if len(activeInsights) == 0 or not all([self.symbol_data[x.Symbol].IsReady for x in activeInsights]):
            return targets

        num_of_assets = len(activeInsights)
        if self.num_of_assets != num_of_assets:
            self.num_of_assets = num_of_assets
            # Initialize portfolio weightings vector
            self.weight_vector = np.ones(num_of_assets) * (1/num_of_assets)

        ### Get price relatives vs expected price (SMA)
        price_relatives = self.GetPriceRelatives(activeInsights)     # \tilde{x}_{t+1}

        ### Get step size of next portfolio
        # \bar{x}_{t+1} = 1^T * \tilde{x}_{t+1} / m
        # \lambda_{t+1} = max( 0, ( b_t * \tilde{x}_{t+1} - \epsilon ) / ||\tilde{x}_{t+1}  - \bar{x}_{t+1} * 1|| ^ 2 )
        next_prediction = price_relatives.mean()        # \bar{x}_{t+1}
        assets_mean_dev = price_relatives - next_prediction
        second_norm = (np.linalg.norm(assets_mean_dev)) ** 2

        if second_norm == 0.0:
            step_size = 0
        else:
            step_size = (np.dot(self.weight_vector, price_relatives) - self.reversion_threshold) / second_norm
            step_size = max(0, step_size)       # \lambda_{t+1}

        ### Get next portfolio weightings
        # b_{t+1} = b_t - step_size * ( \tilde{x}_{t+1}  - \bar{x}_{t+1} * 1 )
        next_portfolio = self.weight_vector - step_size * assets_mean_dev
        # Normalize
        normalized_portfolio_weight_vector = self.SimplexProjection(next_portfolio)
        # Save normalized result for the next portfolio step
        self.weight_vector = normalized_portfolio_weight_vector

        # Update portfolio state
        for i, insight in enumerate(activeInsights):
            targets[insight] = normalized_portfolio_weight_vector[i]

        return targets

    def GetPriceRelatives(self, activeInsights):
        """Get price relatives with reference level of SMA
        Args:
            activeInsights: list of active insights
        Returns:
            array of price relatives vector
        """
        # Initialize a price vector of the next prices relatives' projection
        next_price_relatives = np.zeros(len(activeInsights))

        ### Get next price relative predictions
        # Using the previous price to simulate assumption of instant reversion
        for i, insight in enumerate(activeInsights):
            symbol_data = self.symbol_data[insight.Symbol]
            next_price_relatives[i] = 1 + insight.Magnitude * insight.Direction \
                if insight.Magnitude is not None \
                else symbol_data.Identity.Current.Value / symbol_data.Sma.Current.Value

        return next_price_relatives

    def OnSecuritiesChanged(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().OnSecuritiesChanged(algorithm, changes)
        for removed in changes.RemovedSecurities:
            symbol_data = self.symbol_data.pop(removed.Symbol, None)
            symbol_data.Reset()

        # initialize data for added securities
        symbols = [ x.Symbol for x in changes.AddedSecurities ]

        for symbol in symbols:
            if symbol not in self.symbol_data:
                self.symbol_data[symbol] = self.MeanReversionSymbolData(algorithm, symbol, self.window_size, self.resolution)

    def SimplexProjection(self, vector, total=1):
        """Normalize the updated portfolio into weight vector:
        v_{t+1} = arg min || v - v_{t+1} || ^ 2
        Implementation from:
        Duchi, J., Shalev-Shwartz, S., Singer, Y., & Chandra, T. (2008, July).
            Efficient projections onto the l 1-ball for learning in high dimensions.
            In Proceedings of the 25th international conference on Machine learning
            (pp. 272-279).
        Args:
            vector: unnormalized weight vector
            total: total weight of output, default to be 1, making it a probabilistic simplex
        """
        if total <= 0:
            raise ArgumentException("Total must be > 0 for Euclidean Projection onto the Simplex.")

        vector = np.asarray(vector)

        # Sort v into u in descending order
        mu = np.sort(vector)[::-1]
        sv = np.cumsum(mu)

        rho = np.where(mu > (sv - total) / np.arange(1, len(vector) + 1))[0][-1]
        theta = (sv[rho] - total) / (rho + 1)
        w = (vector - theta)
        w[w < 0] = 0
        return w

    class MeanReversionSymbolData:
        def __init__(self, algo, symbol, window_size, resolution):
            # Indicator of price
            self.Identity = algo.Identity(symbol, resolution)
            # Moving average indicator for mean reversion level
            self.Sma = algo.SMA(symbol, window_size, resolution)

            # Warmup indicator
            algo.WarmUpIndicator(symbol, self.Identity, resolution)
            algo.WarmUpIndicator(symbol, self.Sma, resolution)

        def Reset(self):
            self.Identity.Reset()
            self.Sma.Reset()

        @property
        def IsReady(self):
            return self.Identity.IsReady and self.Sma.IsReady
```


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
: Risk Parity Portfolio Construction Model

Output:
```python

from AlgorithmImports import *
from Portfolio.RiskParityPortfolioOptimizer import RiskParityPortfolioOptimizer

class RiskParityPortfolioConstructionModel(PortfolioConstructionModel):
    def __init__(self,
                 rebalance = Resolution.DAILY,
                 portfolio_bias = PortfolioBias.LONG_SHORT,
                 lookback = 1,
                 period = 252,
                 resolution = Resolution.DAILY,
                 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__()
        if portfolio_bias == PortfolioBias.SHORT:
            raise ArgumentException("Long position must be allowed in RiskParityPortfolioConstructionModel.")

        self.lookback = lookback
        self.period = period
        self.resolution = resolution
        self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)

        self.optimizer = RiskParityPortfolioOptimizer() 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, int):
            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 determine_target_percent(self, active_insights):
        """Will determine the target percent for each insight
        Args:
            active_insights: list of active insights
        Returns:
            dictionary of insight and respective target weight
        """
        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) : 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:
            targets[insight] = weights[str(insight.symbol)]

        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()
            algorithm.unregister_indicator(symbol_data.roc)

        # initialize data for added securities
        symbols = [ x.symbol for x in changes.added_securities ]
        history = algorithm.history(symbols, self.lookback * self.period, 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 = self.RiskParitySymbolData(symbol, self.lookback, self.period)
                symbol_data.warm_up_indicators(history.loc[ticker])
                self._symbol_data_by_symbol[symbol] = symbol_data
                algorithm.register_indicator(symbol, symbol_data.roc, self.resolution)

    class RiskParitySymbolData:
        '''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 warm_up_indicators(self, history):
            for tuple in history.itertuples():
                self.roc.update(tuple.Index, tuple.close)

        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)

        @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])
```


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 IPortfolioConstructionModel that generates percent targets based on the

Output:
```python

from AlgorithmImports import *
from InsightWeightingPortfolioConstructionModel import InsightWeightingPortfolioConstructionModel

class ConfidenceWeightedPortfolioConstructionModel(InsightWeightingPortfolioConstructionModel):
    '''Provides an implementation of IPortfolioConstructionModel that generates percent targets based on the
    Insight.CONFIDENCE. The target percent holdings of each Symbol is given by the Insight.CONFIDENCE from the last
    active Insight for that symbol.
    For insights of direction InsightDirection.UP, long targets are returned and for insights of direction
    InsightDirection.DOWN, short targets are returned.
    If the sum of all the last active Insight per symbol is bigger than 1, it will factor down each target
    percent holdings proportionally so the sum is 1.
    It will ignore Insight that have no Insight.CONFIDENCE value.'''

    def __init__(self, rebalance = Resolution.DAILY, portfolio_bias = PortfolioBias.LONG_SHORT):
        '''Initialize a new instance of ConfidenceWeightedPortfolioConstructionModel
        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)'''
        super().__init__(rebalance, portfolio_bias)

    def should_create_target_for_insight(self, insight):
        '''Method that will determine if the portfolio construction model should create a
        target for this insight
        Args:
            insight: The insight to create a target for'''
        # Ignore insights that don't have Confidence value
        return insight.confidence is not None

    def get_value(self, insight):
        '''Method that will determine which member will be used to compute the weights and gets its value
        Args:
            insight: The insight to create a target for
        Returns:
            The value of the selected insight member'''
        return insight.confidence
```