Skip to content

MeanVarianceOptimizationPortfolioConstructionModel

QuantConnect.Algorithm.Framework.Portfolio.MeanVarianceOptimizationPortfolioConstructionModel

MeanVarianceOptimizationPortfolioConstructionModel(
    rebalance: Any,
    portfolio_bias: PortfolioBias = ...,
    lookback: int = 1,
    period: int = 63,
    resolution: Resolution = ...,
    target_return: float = 0.02,
    optimizer: Any = None,
)
MeanVarianceOptimizationPortfolioConstructionModel(
    rebalancing_date_rules: IDateRule,
    portfolio_bias: PortfolioBias = ...,
    lookback: int = 1,
    period: int = 63,
    resolution: Resolution = ...,
    target_return: float = 0.02,
    optimizer: IPortfolioOptimizer = None,
)
MeanVarianceOptimizationPortfolioConstructionModel(
    rebalance_resolution: Resolution = ...,
    portfolio_bias: PortfolioBias = ...,
    lookback: int = 1,
    period: int = 63,
    resolution: Resolution = ...,
    target_return: float = 0.02,
    optimizer: IPortfolioOptimizer = None,
)
MeanVarianceOptimizationPortfolioConstructionModel(
    time_span: timedelta,
    portfolio_bias: PortfolioBias = ...,
    lookback: int = 1,
    period: int = 63,
    resolution: Resolution = ...,
    target_return: float = 0.02,
    optimizer: IPortfolioOptimizer = None,
)
MeanVarianceOptimizationPortfolioConstructionModel(
    rebalancing_func: Callable[[datetime], datetime],
    portfolio_bias: PortfolioBias = ...,
    lookback: int = 1,
    period: int = 63,
    resolution: Resolution = ...,
    target_return: float = 0.02,
    optimizer: IPortfolioOptimizer = None,
)
MeanVarianceOptimizationPortfolioConstructionModel(
    rebalancing_func: Callable[
        [datetime], Optional[datetime]
    ],
    portfolio_bias: PortfolioBias = ...,
    lookback: int = 1,
    period: int = 63,
    resolution: Resolution = ...,
    target_return: float = 0.02,
    optimizer: IPortfolioOptimizer = None,
)

Bases: PortfolioConstructionModel

Provides an implementation of Mean-Variance portfolio optimization based on modern portfolio theory. The interval of weights in optimization method can be changed based on the long-short algorithm. The default model uses the last three months daily price to calculate the optimal weight with the weight range from -1 to 1 and minimize the portfolio variance with a target return of 2%

Initialize the model

Parameters:

Name Type Description Default
rebalance Optional[Any]

Rebalancing func or if a date rule, timedelta will be converted into func.

None
portfolio_bias PortfolioBias

Specifies the bias of the portfolio (Short, Long/Short, Long)

...
lookback int

Historical return lookback period

1
period int

The time interval of history price to calculate the weight

63
resolution Resolution

The resolution of the history price

...
target_return float

The target portfolio return

0.02
optimizer Any | IPortfolioOptimizer

The portfolio optimization algorithm. If the algorithm is not provided then the default will be mean-variance optimization.

None
rebalancing_date_rules Optional[IDateRule]

The date rules used to define the next expected rebalance time

None
rebalance_resolution Optional[Resolution]

Rebalancing frequency

...
time_span Optional[timedelta]

Rebalancing frequency

None
rebalancing_func Optional[Callable[[datetime], datetime] | Callable[[datetime], Optional[datetime]]]

For a given algorithm UTC DateTime returns the next expected rebalance UTC time.

None

rebalance_on_security_changes

rebalance_on_security_changes: bool

True if should rebalance portfolio on security changes. True by default

rebalance_on_insight_changes

rebalance_on_insight_changes: bool

True if should rebalance portfolio on new insights or expiration of insights. True by default

algorithm

algorithm: IAlgorithm

The algorithm instance

This codeEntityType is protected.

python_wrapper

This is required due to a limitation in PythonNet to resolved overriden methods. When Python calls a C# method that calls a method that's overriden in python it won't run the python implementation unless the call is performed through python too.

This codeEntityType is protected.

determine_target_percent

determine_target_percent(
    active_insights: List[Insight],
) -> Dictionary[Insight, float]

Will determine the target percent for each insight

This codeEntityType is protected.

Parameters:

Name Type Description Default
active_insights List[Insight]

The active insights to generate a target for

required

Returns:

Type Description
Dictionary[Insight, float]

A target percent for each insight.

on_securities_changed

on_securities_changed(
    algorithm: QCAlgorithm, changes: SecurityChanges
) -> None

Event fired each time the we add/remove securities from the data feed

Parameters:

Name Type Description Default
algorithm QCAlgorithm

The algorithm instance that experienced the change in securities

required
changes SecurityChanges

The security additions and removals from the algorithm

required

should_create_target_for_insight

should_create_target_for_insight(insight: Insight) -> bool

Method that will determine if the portfolio construction model should create a target for this insight

This codeEntityType is protected.

Parameters:

Name Type Description Default
insight Insight

The insight to create a target for

required

Returns:

Type Description
bool

True if the portfolio should create a target for the insight.

create_targets

create_targets(
    algorithm: QCAlgorithm, insights: List[Insight]
) -> Iterable[IPortfolioTarget]

Create portfolio targets from the specified insights

Parameters:

Name Type Description Default
algorithm QCAlgorithm

The algorithm instance

required
insights List[Insight]

The insights to create portfolio targets from

required

Returns:

Type Description
Iterable[IPortfolioTarget]

An enumerable of portfolio targets to be sent to the execution model.

filter_invalid_insight_magnitude

filter_invalid_insight_magnitude(
    algorithm: IAlgorithm, insights: List[Insight]
) -> List[Insight]

Helper class that can be used by the different IPortfolioConstructionModel implementations to filter Insight instances with an invalid Insight.magnitude value based on the IAlgorithmSettings

This codeEntityType is protected.

Parameters:

Name Type Description Default
algorithm IAlgorithm

The algorithm instance

required
insights List[Insight]

The insight collection to filter

required

Returns:

Type Description
List[Insight]

Returns a new array of insights removing invalid ones.

get_target_insights

get_target_insights() -> List[Insight]

Gets the target insights to calculate a portfolio target percent for

This codeEntityType is protected.

Returns:

Type Description
List[Insight]

An enumerable of the target insights.

is_rebalance_due

is_rebalance_due(
    insights: List[Insight],
    algorithm_utc: Union[datetime, date],
) -> bool

Determines if the portfolio should be rebalanced base on the provided rebalancing func, if any security change have been taken place or if an insight has expired or a new insight arrived If the rebalancing function has not been provided will return true.

This codeEntityType is protected.

Parameters:

Name Type Description Default
insights List[Insight]

The insights to create portfolio targets from

required
algorithm_utc Union[datetime, date]

The current algorithm UTC time

required

Returns:

Type Description
bool

True if should rebalance.

refresh_rebalance

refresh_rebalance(
    algorithm_utc: Union[datetime, date],
) -> None

Refresh the next rebalance time and clears the security changes flag

This codeEntityType is protected.

set_python_wrapper

set_python_wrapper(
    python_wrapper: PortfolioConstructionModelPythonWrapper,
) -> None

Used to set the PortfolioConstructionModelPythonWrapper instance if any

This codeEntityType is protected.

set_rebalancing_func

set_rebalancing_func(rebalance: Any) -> None

Python helper method to set the rebalancing function. This is required due to a python net limitation not being able to use the base type constructor, and also because when python algorithms use C# portfolio construction models, it can't convert python methods into func nor resolve the correct constructor for the date rules, timespan parameter. For performance we prefer python algorithms using the C# implementation

This codeEntityType is protected.

Parameters:

Name Type Description Default
rebalance Any

Rebalancing func or if a date rule, timedelta will be converted into func. For a given algorithm UTC DateTime the func returns the next expected rebalance time or null if unknown, in which case the function will be called again in the next loop. Returning current time will trigger rebalance. If null will be ignored

required