skfolio.population.Population#
- class skfolio.population.Population(iterable)[source]#
Population Class.
A
Population
is a list ofPortfolio
orMultiPeriodPortfolio
or both.- Parameters:
- iterablelist[BasePortfolio]
The list of portfolios. Each item can be of type
Portfolio
and/orMultiPeriodPortfolio
. Empty list are accepted.
Methods
append
(item)Append portfolio to the end of the population list.
boxplot_measure
(measure[, tag_list, points])Plot a box plot of a measure's distribution, optionally split by tags.
clear
(/)Remove all items from list.
composition
([display_sub_ptf_name])Composition of each portfolio in the population.
contribution
(measure[, spacing, ...])Contribution of each asset to a given measure of each portfolio in the population.
copy
(/)Return a shallow copy of the list.
count
(value, /)Return number of occurrences of value.
cumulative_returns_df
([use_tag_in_column_name])DataFrame of cumulative returns for each portfolio in the population.
drawdowns_df
([use_tag_in_column_name])DataFrame of drawdowns for each portfolio in the population.
extend
(other)Extend population list by appending elements from the iterable.
filter
([names, tags])Filter the Population of portfolios by names and tags.
index
(value[, start, stop])Return first index of value.
insert
(index, item)Insert portfolio before index.
max_measure
(measure)Return the portfolio with the maximum measure.
measures
(measure)Vector of portfolios measures for each portfolio from the population.
measures_mean
(measure)Mean of portfolios measures for each portfolio from the population.
measures_std
(measure)Standard-deviation of portfolios measures for each portfolio from the population.
min_measure
(measure)Return the portfolio with the minimum measure.
non_denominated_sort
([first_front_only])Fast non-dominated sorting.
plot_composition
([display_sub_ptf_name])Plot the compositions of the portfolios in the population.
plot_contribution
(measure[, spacing, ...])Plot the contribution of each asset to a given measure of the portfolios in the population.
plot_cumulative_returns
([log_scale, idx, ...])Plot the cumulative returns of the population's portfolios.
plot_distribution
(measure_list[, tag_list, ...])Plot the population's distribution for each measure provided in the measure list.
plot_drawdowns
([idx, use_tag_in_legend])Plot the drawdowns of the population's portfolios.
plot_measures
(x, y[, z, to_surface, ...])Plot the 2D (or 3D) scatter points (or surface) of a given set of measures for each portfolio in the population.
plot_returns_distribution
([percentile_cutoff])Plot the Portfolios returns distribution using Gaussian KDE.
plot_rolling_measure
([measure, window])Plot the measure over a rolling window for each portfolio in the population.
pop
([index])Remove and return item at index (default last).
quantile
(measure, q)Return the portfolio corresponding to the
q
quantile for a given portfolio measure.remove
(value, /)Remove first occurrence of value.
reverse
(/)Reverse IN PLACE.
rolling_measure
([measure, window])Compute the measure over a rolling window for each portfolio in the
set_portfolio_params
(**params)Set the parameters of all the portfolios.
sort
(*[, key, reverse])Sort the list in ascending order and return None.
sort_measure
(measure[, reverse])Sort the population by a given portfolio measure.
summary
([formatted])Summary of the portfolios in the population.
- boxplot_measure(measure, tag_list=None, points='all')[source]#
Plot a box plot of a measure’s distribution, optionally split by tags.
If no tags are provided, the function draws a single box showing the population distribution of
measure
. Iftag_list
is provided, it draws one box per tag using values from the portfolio filtered by each tag.- Parameters:
- measureMeasure
The measure to plot.
- tag_listlist[str], optional
For each tag in this list, filter the portfolio by that tag and plot a separate box. If None or empty, plot a single overall distribution.
- points{‘all’, ‘outliers’, ‘suspectedoutliers’, False}, default ‘all’
Passed to
plotly.express.box(..., points=...)
to control which points are shown.
- Returns:
- go.Figure
The Plotly figure.
Examples
>>> fig = population.boxplot_measure(measure=RiskMeasure.STANDARD_DEVIATION) >>> fig = population.plot_measure_box( ... measure=RatioMeasure.SHARPE_RATIO, ... tag_list=["Benchmark", "Risk Parity Model"] ... )
- clear(/)#
Remove all items from list.
- composition(display_sub_ptf_name=True)[source]#
Composition of each portfolio in the population.
- Parameters:
- display_sub_ptf_namebool, default=True
If this is set to True, each sub-portfolio name composing a multi-period portfolio is displayed.
- Returns:
- dfDataFrame
Composition of the portfolios in the population.
- contribution(measure, spacing=None, display_sub_ptf_name=True)[source]#
Contribution of each asset to a given measure of each portfolio in the population.
- Parameters:
- measureMeasure
The measure used for the contribution computation.
- spacingfloat, optional
Spacing “h” of the finite difference: \(contribution(wi)= \frac{measure(wi-h) - measure(wi+h)}{2h}\).
- display_sub_ptf_namebool, default=True
If this is set to True, each sub-portfolio name composing a multi-period portfolio is displayed.
- Returns:
- dfDataFrame
Contribution of each asset to a given measure of each portfolio in the population.
- copy(/)#
Return a shallow copy of the list.
- count(value, /)#
Return number of occurrences of value.
- cumulative_returns_df(use_tag_in_column_name=True)[source]#
DataFrame of cumulative returns for each portfolio in the population. Non-compounded (arithmetic) cumulative returns start at 0. Compounded (geometric) cumulative returns are expressed as a wealth index, starting at 1.0 (i.e., the value of $1 invested).
- Parameters:
- use_tag_in_column_namebool, default=True
Whether to include the portfolio tag in the DataFrame column names. If True, each column name will use the portfolio name followed by its tag; if False, only the portfolio name will be used.
- Returns:
- cumulative_returnsDataFrame
Cumulative returns DataFrame.
- drawdowns_df(use_tag_in_column_name=True)[source]#
DataFrame of drawdowns for each portfolio in the population.
- Parameters:
- use_tag_in_column_namebool, default=True
Whether to include the portfolio tag in the DataFrame column names. If True, each column name will use the portfolio name followed by its tag; if False, only the portfolio name will be used.
- Returns:
- drawdownsDataFrame
Drawdowns DataFrame.
- filter(names=None, tags=None)[source]#
Filter the Population of portfolios by names and tags. If both names and tags are provided, the intersection is returned.
- Parameters:
- namesstr | list[str], optional
If provided, the population is filtered by portfolio names.
- tagsstr | list[str], optional
If provided, the population is filtered by portfolio tags.
- Returns:
- populationPopulation
A new population of portfolios filtered by names and tags.
- index(value, start=0, stop=sys.maxsize, /)#
Return first index of value.
Raises ValueError if the value is not present.
- max_measure(measure)[source]#
Return the portfolio with the maximum measure.
- Parameters:
- measure: Measure
The portfolio measure.
- Returns:
- valuesBasePortfolio
The portfolio with maximum measure.
- measures(measure)[source]#
Vector of portfolios measures for each portfolio from the population.
- Parameters:
- measureMeasure
The portfolio measure.
- Returns:
- valuesndarray
The vector of portfolios measures.
- measures_mean(measure)[source]#
Mean of portfolios measures for each portfolio from the population.
- Parameters:
- measureMeasure
The portfolio measure.
- Returns:
- valuefloat
The mean of portfolios measures.
- measures_std(measure)[source]#
Standard-deviation of portfolios measures for each portfolio from the population.
- Parameters:
- measureMeasure
The portfolio measure.
- Returns:
- valuefloat
The standard-deviation of portfolios measures.
- min_measure(measure)[source]#
Return the portfolio with the minimum measure.
- Parameters:
- measureMeasure
The portfolio measure.
- Returns:
- valuesBasePortfolio
The portfolio with minimum measure.
- non_denominated_sort(first_front_only=False)[source]#
Fast non-dominated sorting. Sort the portfolios into different non-domination levels. Complexity O(MN^2) where M is the number of objectives and N the number of portfolios.
- Parameters:
- first_front_onlybool, default=False
If this is set to True, only the first front is sorted and returned. The default is
False
.
- Returns:
- frontslist[list[int]]
A list of Pareto fronts (lists), the first list includes non-dominated portfolios.
- plot_composition(display_sub_ptf_name=True)[source]#
Plot the compositions of the portfolios in the population.
- Parameters:
- display_sub_ptf_namebool, default=True
If this is set to True, each sub-portfolio name composing a multi-period portfolio is displayed.
- Returns:
- plotFigure
Returns the plotly Figure object.
- plot_contribution(measure, spacing=None, display_sub_ptf_name=True)[source]#
Plot the contribution of each asset to a given measure of the portfolios in the population.
- Parameters:
- measureMeasure
The measure used for the contribution computation.
- spacingfloat, optional
Spacing “h” of the finite difference: \(contribution(wi)= \frac{measure(wi-h) - measure(wi+h)}{2h}\)
- display_sub_ptf_namebool, default=True
If this is set to True, each sub-portfolio name composing a multi-period portfolio is displayed.
- Returns:
- plotFigure
Returns the plotly Figure object.
- plot_cumulative_returns(log_scale=False, idx=None, use_tag_in_legend=True)[source]#
Plot the cumulative returns of the population’s portfolios. Non-compounded (arithmetic) cumulative returns start at 0. Compounded (geometric) cumulative returns are expressed as a wealth index, starting at 1.0 (i.e., the value of $1 invested).
- Parameters:
- log_scalebool, default=False
If set to True, the cumulative returns are displayed with a logarithm scale on the y-axis. The cumulative returns must be compounded otherwise an exception is raise.
- idxslice | array, optional
Indexes or slice of the observations to plot. The default (
None
) is to take all observations.- use_tag_in_legendbool, default=True
Whether to include the portfolio tag in legend entries. If True, each legend label will show the portfolio name followed by its tag; if False, only the portfolio name will be displayed.
- Returns:
- plotFigure
Returns the plot Figure object.
- plot_distribution(measure_list, tag_list=None, n_bins=None, **kwargs)[source]#
Plot the population’s distribution for each measure provided in the measure list.
- Parameters:
- measure_listlist[Measure]
The list of portfolio measures. A different distribution is plotted per measure.
- tag_listlist[str], optional
If this is provided, an additional distribution is plotted per measure for each tag provided.
- n_binsint, optional
Sets the number of bins.
- Returns:
- plotFigure
Returns the plotly Figure object.
- plot_drawdowns(idx=None, use_tag_in_legend=True)[source]#
Plot the drawdowns of the population’s portfolios.
- Parameters:
- idxslice | array, optional
Indexes or slice of the observations to plot. The default (
None
) is to take all observations.- use_tag_in_legendbool, default=True
Whether to include the portfolio tag in legend entries. If True, each legend label will show the portfolio name followed by its tag; if False, only the portfolio name will be displayed.
- Returns:
- plotFigure
Returns the plot Figure object.
- plot_measures(x, y, z=None, to_surface=False, hover_measures=None, show_fronts=False, color_scale=None, title='Portfolios')[source]#
Plot the 2D (or 3D) scatter points (or surface) of a given set of measures for each portfolio in the population.
- Parameters:
- xMeasure
The x-axis measure.
- yMeasure
The y-axis measure.
- zMeasure, optional
The z-axis measure.
- to_surfacebool, default=False
If this is set to True, a surface is estimated.
- hover_measureslist[Measure], optional
The list of measure to show on point hover.
- show_frontsbool, default=False
If this is set to True, the pareto fronts are highlighted. The default is
False
.- color_scaleMeasure | str, optional
If this is provided, a color scale is displayed.
- titlestr, default=”Portfolios”
The graph title. The default value is “Portfolios”.
- Returns:
- plotFigure
Returns the plotly Figure object.
- plot_returns_distribution(percentile_cutoff=None)[source]#
Plot the Portfolios returns distribution using Gaussian KDE.
- Parameters:
- percentile_cutofffloat, default=None
Percentile cutoff for tail truncation (percentile), in percent. If a float p is provided, the distribution support is truncated at the p-th and (100 - p)-th percentiles. If None, no truncation is applied (uses full min/max of returns).
- Returns:
- plotFigure
Returns the plot Figure object
- plot_rolling_measure(measure=Sharpe Ratio, window=30)[source]#
Plot the measure over a rolling window for each portfolio in the population.
- Parameters:
- measurect.Measure, default = RatioMeasure.SHARPE_RATIO
The measure.
- windowint, default=30
The window size.
- Returns:
- plotFigure
Returns the plot Figure object
- pop(index=-1, /)#
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
- quantile(measure, q)[source]#
Return the portfolio corresponding to the
q
quantile for a given portfolio measure.- Parameters:
- measureMeasure
The portfolio measure.
- qfloat
The quantile value.
- Returns:
- valuesBasePortfolio
Portfolio corresponding to the
q
quantile for the measure.
- remove(value, /)#
Remove first occurrence of value.
Raises ValueError if the value is not present.
- reverse(/)#
Reverse IN PLACE.
- rolling_measure(measure=Sharpe Ratio, window=30)[source]#
- Compute the measure over a rolling window for each portfolio in the
population.
- Parameters:
- measurect.Measure, default=RatioMeasure.SHARPE_RATIO
The measure. The default measure is the Sharpe Ratio.
- windowint, default=30
The window size. The default value is
30
observations.
- Returns:
- dataframepandas DataFrame
The rolling measures.
- set_portfolio_params(**params)[source]#
Set the parameters of all the portfolios.
- Parameters:
- **paramsAny
Portfolio parameters.
- Returns:
- selfPopulation
The Population instance.
- sort(*, key=None, reverse=False)#
Sort the list in ascending order and return None.
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
- sort_measure(measure, reverse=False)[source]#
Sort the population by a given portfolio measure.
- Parameters:
- measureMeasure
The portfolio measure.
- reversebool, default=False
If this is set to True, the order is reversed.
- Returns:
- valuesPopulations
The sorted population.
- summary(formatted=True)[source]#
Summary of the portfolios in the population.
- Parameters:
- formattedbool, default=True
If this is set to True, the measures are formatted into rounded string with units. The default is
True
.
- Returns:
- summarypandas DataFrame
The population’s portfolios summary
Notes
This method returns a static pandas DataFrame. For interactive exploration (e.g., sortable/filterable/clickable tables or visual summaries), you may want to use libraries such as
ipydatagrid
,D-Tale
, orLux
in a Jupyter environment, ordash_table
/streamlit.dataframe
when building dashboards. For example, you can explore the summary with D-Tale:dtale.show(population.summary().T)