The source files can be found in examples/.
Plotting and reporting
PortfolioOptimisers.jl has plotting functions for each stage of an optimisation. They load when you load StatsPlots with the package, and plot_network also needs GraphRecipes. They plot the inputs, the allocation, the risk of each asset, the performance over the sample, and the portfolios on axes of risk and return. Two dashboards put several of these plots into one figure. This page draws them for one pair of portfolios.
Reach for these plots to check the inputs before you optimise, to show an allocation to someone else, and to compare candidate portfolios on the same axes. Each plot shows one view. The dashboards, plot_portfolio_dashboard and plot_performance_summary, put several views in one call.
using PortfolioOptimisers, CSV, TimeSeries, Clarabel, StatsPlots1. The portfolios
We compute an empirical prior, a minimum-risk portfolio and a maximum-ratio portfolio to compare, and an efficient frontier for the plots of risk and return.
X = TimeArray(CSV.File(joinpath(@__DIR__, "..", "SP500.csv.gz")); timestamp = :Date)[(end - 252):end]rd = prices_to_returns(X)pr = prior(EmpiricalPrior(), rd)slv = Solver(; name = :clarabel, solver = Clarabel.Optimizer, settings = Dict("verbose" => false), check_sol = (; allow_local = true, allow_almost = true))rf = 4.2 / 100 / 252res_min = optimise(MeanRisk(; obj = MinimumRisk(), opt = JuMPOptimiser(; pe = pr, slv = slv)))res_ratio = optimise(MeanRisk(; obj = MaximumRatio(; rf = rf), opt = JuMPOptimiser(; pe = pr, slv = slv)))frontier = optimise(MeanRisk(; obj = MinimumRisk(), opt = JuMPOptimiser(; pe = pr, slv = slv, ret = ArithmeticReturn(; settings = JuMPReturnsSettings(; lb = Frontier(; N = 15))))))MeanRiskResult
jr ┼ JuMPOptimisationResult
│ jor ┼ ResolvedJuMPOptimiser
│ │ pr ┼ LowOrderPrior
│ │ │ X ┼ 252×20 Matrix{Float64}
│ │ │ o_X ┼ nothing
│ │ │ mu ┼ 20-element Vector{Float64}
│ │ │ sigma ┼ 20×20 Matrix{Float64}
│ │ │ chol ┼ nothing
│ │ │ w ┼ nothing
│ │ │ ens ┼ nothing
│ │ │ eoc ┼ Tuple{Nothing, Nothing}: (nothing, nothing)
│ │ │ kld ┼ nothing
│ │ │ ow ┼ nothing
│ │ │ rr ┼ nothing
│ │ │ fpr ┼ nothing
│ │ │ x_src ┼ nothing
│ │ │ ss_gaps ┼ nothing
│ │ │ pc ┴ nothing
│ │ fees ┼ nothing
│ │ ret ┼ ArithmeticReturn
│ │ │ settings ┼ JuMPReturnsSettings
│ │ │ │ scale ┼ Float64: 1.0
│ │ │ │ lb ┼ Frontier
│ │ │ │ │ N ┼ Int64: 15
│ │ │ │ │ factor ┼ Int64: 1
│ │ │ │ │ bound ┴ LinearBound()
│ │ │ │ rte ┼ Bool: true
│ │ │ │ fee ┼ Bool: true
│ │ │ │ mic ┴ Bool: true
│ │ │ ucs ┼ nothing
│ │ │ mu ┼ 20-element Vector{Float64}
│ │ │ mtx_sqrt ┴ EigenFallbackSquareRoot()
│ │ sca ┼ nothing
│ │ imsk ┼ nothing
│ │ cbr ┼ ResolvedConstraintBlock
│ │ │ pr ┼ LowOrderPrior
│ │ │ │ X ┼ 252×20 Matrix{Float64}
│ │ │ │ o_X ┼ nothing
│ │ │ │ mu ┼ 20-element Vector{Float64}
│ │ │ │ sigma ┼ 20×20 Matrix{Float64}
│ │ │ │ chol ┼ nothing
│ │ │ │ w ┼ nothing
│ │ │ │ ens ┼ nothing
│ │ │ │ eoc ┼ Tuple{Nothing, Nothing}: (nothing, nothing)
│ │ │ │ kld ┼ nothing
│ │ │ │ ow ┼ nothing
│ │ │ │ rr ┼ nothing
│ │ │ │ fpr ┼ nothing
│ │ │ │ x_src ┼ nothing
│ │ │ │ ss_gaps ┼ nothing
│ │ │ │ pc ┴ nothing
│ │ │ rd ┼ ReturnsResult
│ │ │ │ nx ┼ nothing
│ │ │ │ X ┼ nothing
│ │ │ │ nf ┼ nothing
│ │ │ │ F ┼ nothing
│ │ │ │ nb ┼ nothing
│ │ │ │ B ┼ nothing
│ │ │ │ ne ┼ nothing
│ │ │ │ E ┼ nothing
│ │ │ │ ts ┼ nothing
│ │ │ │ iv ┼ nothing
│ │ │ │ ivpa ┼ nothing
│ │ │ │ pnl ┴ nothing
│ │ │ wb ┼ WeightBounds
│ │ │ │ lb ┼ 20-element StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}
│ │ │ │ ub ┴ 20-element StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}
│ │ │ lt ┼ nothing
│ │ │ st ┼ nothing
│ │ │ lcsr ┼ nothing
│ │ │ ctr ┼ nothing
│ │ │ gcardr ┼ nothing
│ │ │ sgcardr ┼ nothing
│ │ │ smtx ┼ nothing
│ │ │ sgmtx ┼ nothing
│ │ │ slt ┼ nothing
│ │ │ sst ┼ nothing
│ │ │ sglt ┼ nothing
│ │ │ sgst ┼ nothing
│ │ │ tn ┼ nothing
│ │ │ plr ┼ nothing
│ │ │ l2c ┼ nothing
│ │ │ lpc ┼ nothing
│ │ │ linfc ┼ nothing
│ │ │ l1 ┼ nothing
│ │ │ l2 ┼ nothing
│ │ │ lp ┼ nothing
│ │ │ linf ┼ nothing
│ │ │ card ┼ nothing
│ │ │ scard ┼ nothing
│ │ │ ss ┼ nothing
│ │ │ xbgt ┼ Bool: false
│ │ │ sbgt ┼ nothing
│ │ │ gbgt ┼ nothing
│ │ │ ccnt ┼ nothing
│ │ │ cobj ┴ nothing
│ retcode ┼ 15-element Vector{OptimisationSuccess}
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ │ OptimisationSuccess ⋯
│ sol ┼ 15-element Vector{JuMPOptimisationSolution}
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ │ JuMPOptimisationSolution ⋯
│ model ┼ A JuMP Model
│ │ ├ solver: Clarabel
│ │ ├ objective_sense: MIN_SENSE
│ │ │ └ objective_function_type: QuadExpr
│ │ ├ num_variables: 22
│ │ ├ num_constraints: 6
│ │ │ ├ AffExpr in MOI.EqualTo{Float64}: 1
│ │ │ ├ AffExpr in MOI.GreaterThan{Float64}: 1
│ │ │ ├ Vector{AffExpr} in MOI.Nonnegatives: 1
│ │ │ ├ Vector{AffExpr} in MOI.Nonpositives: 1
│ │ │ ├ Vector{AffExpr} in MOI.SecondOrderCone: 1
│ │ │ └ VariableRef in MOI.Parameter{Float64}: 1
│ │ └ Names registered in the model
│ │ └ :G, :T, :bgt, :cdev_soc_1, :dev_1, :k, :lw, :obj_expr, :ret, :ret_1, :ret_frontier, :ret_lb_1, :ret_lb_var_1, :ret_vec, :risk, :risk_minimised, :risk_vec, :sc, :so, :variance_flag, :variance_risk_1, :w, :w_gross_ub, :w_lb, :w_ub
r ┼ Variance
│ settings ┼ RiskMeasureSettings
│ │ scale ┼ Float64: 1.0
│ │ ub ┼ nothing
│ │ rke ┴ Bool: true
│ sigma ┼ 20×20 Matrix{Float64}
│ chol ┼ nothing
│ rc ┼ nothing
│ alg ┼ SquaredSOCRiskExpr()
│ mtx_sqrt ┼ EigenFallbackSquareRoot()
│ ratio_alg ┼ SquareRootRatio()
│ corner ┴ nothing
fb ┴ nothing
2. The inputs
Look at the inputs before you trust an optimisation. plot_prior plots the prior in one figure. plot_correlation plots the correlation matrix alone, and plot_mu plots the expected returns alone.
plot_prior(pr, rd)We also plot the correlation matrix on its own.
plot_correlation(pr)3. The allocation
plot_stacked_bar_composition puts the weights of several portfolios side by side. Here it compares the minimum-risk and the maximum-ratio portfolios, and you can see which of the two puts more weight on fewer assets.
plot_stacked_bar_composition([res_min, res_ratio], rd; xticks = (1:2, ["Min risk", "Max ratio"]))4. The risk of each asset
A portfolio can spread its weights over many assets and still take most of its risk from a few. plot_risk_contribution splits the risk of the portfolio by asset. It takes the risk measure as its first argument. A quadratic risk measure needs the covariance of the data, so pass factory(Variance(), pr), not a bare Variance(), which holds no covariance. A measure computed from returns, such as ConditionalValueatRisk, needs no factory.
plot_risk_contribution(factory(Variance(), pr), res_min, rd)5. Performance over the sample
plot_portfolio_cumulative_returns plots the cumulative return of the maximum-ratio portfolio over the sample.
plot_portfolio_cumulative_returns(res_ratio.w, rd)plot_drawdowns plots the drawdowns of the same portfolio.
plot_drawdowns(res_ratio.w, rd)plot_performance_summary puts the main performance plots into one figure. It plots a PerformanceSummaryResult, which performance_summary computes. Call performance_summary when you want the numbers and not the plot, for example to put them in a table, to compare two portfolios, or to test them. It needs no plotting package.
The keyword ppy is the number of periods in one year. Its default of 1 states each figure per period, which is right at any data frequency. Our returns are daily, so ppy = 252 annualises them.
performance_summary(res_ratio, rd; ppy = 252)PerformanceSummaryResult
names ┼ nothing
paths ┼ nothing
members ┼ nothing
date0 ┼ Date: Date("2021-12-29")
date1 ┼ Date: Date("2022-12-28")
n_periods ┼ Int64: 252
ppy ┼ Int64: 252
alpha ┼ Float64: 0.05
compound ┼ Bool: false
rf ┼ Int64: 0
ann_return ┼ Float64: 0.503520291265981
ann_volatility ┼ Float64: 0.19310978475964483
sharpe ┼ Float64: 2.6074302340126905
sharpe_stderr ┼ Float64: 0.9985451245993174
sortino ┼ Float64: 4.290026176056378
calmar ┼ Float64: 5.078472493282909
max_drawdown ┼ Float64: -0.09914798040788189
cvar ┼ Float64: -0.023244045086572587
excess_ret ┼ Float64: NaN
tracking_error ┼ Float64: NaN
information_ratio ┼ Float64: NaN
turnover ┼ Float64: NaN
n_eff ┼ Float64: 1.8147733475775671
long_exposure ┼ Float64: 0.9999999999999998
short_exposure ┼ Float64: 0.0
gross_exposure ┼ Float64: 0.9999999999999998
net_exposure ┼ Float64: 0.9999999999999998
measures ┼ @NamedTuple{}: NamedTuple()
risk ┴ @NamedTuple{}: NamedTuple()
We draw the same summary as a figure.
plot_performance_summary(res_ratio, rd; ppy = 252)Many portfolios in one table
performance_summary also takes a vector of candidates. It gives one entry for each series, and names names the candidates. The keyword rf is the risk-free rate for each period, and it enters the Sharpe ratio, its standard error and the Sortino ratio. The keyword measures adds risk measures of your choice by name. Each one is evaluated on the same net series as the headline figures, and it keeps the sign of its measure. DataFrame(ps) writes the summary as a table, with one row for each entry.
using DataFramesps = performance_summary([res_min, res_ratio], rd; names = ["min risk", "max ratio"], ppy = 252, rf = rf, measures = [:cvar_99 => ConditionalValueatRisk(; alpha = 0.01), :ulcer => UlcerIndex()])DataFrame(ps)| Row | name | path | member | date0 | date1 | n_periods | ann_return | ann_volatility | sharpe | sharpe_stderr | sortino | calmar | max_drawdown | cvar | excess_ret | tracking_error | information_ratio | turnover | n_eff | long_exposure | short_exposure | gross_exposure | net_exposure | cvar_99 | ulcer |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| String | Nothing | Nothing | Date | Date | Int64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | Float64 | |
| 1 | min risk | 2021-12-29 | 2022-12-28 | 252 | 0.194562 | 0.148339 | 1.02847 | 1.00095 | 1.53561 | 2.1172 | -0.0918958 | -0.0187291 | NaN | NaN | NaN | NaN | 4.88008 | 1.0 | 0.0 | 1.0 | 1.0 | 0.0270688 | 0.0347171 | ||
| 2 | max ratio | 2021-12-29 | 2022-12-28 | 252 | 0.50352 | 0.19311 | 2.38994 | 0.998128 | 3.88625 | 5.07847 | -0.099148 | -0.023244 | NaN | NaN | NaN | NaN | 1.81477 | 1.0 | 0.0 | 1.0 | 1.0 | 0.0314078 | 0.0293691 |
A result that holds many portfolios, such as the frontier, gives one entry for each member. The column member keys each entry, and n_eff, the effective number of assets, shows how the concentration changes along the frontier. The columns long_exposure, short_exposure, gross_exposure and net_exposure give the size of each side of the book. A long-only book with a budget of one gives 1, 0, 1 and 1, and a long-short book shows its leverage there.
DataFrame(performance_summary(frontier, rd; ppy = 252, rf = rf))[:, [:member, :ann_return, :ann_volatility, :sharpe, :n_eff]]| Row | member | ann_return | ann_volatility | sharpe | n_eff |
|---|---|---|---|---|---|
| Int64 | Float64 | Float64 | Float64 | Float64 | |
| 1 | 1 | 0.19485 | 0.148339 | 1.0304 | 4.88518 |
| 2 | 2 | 0.228127 | 0.148761 | 1.25119 | 4.93017 |
| 3 | 3 | 0.261691 | 0.150206 | 1.4626 | 4.94323 |
| 4 | 4 | 0.295255 | 0.152764 | 1.65782 | 4.53748 |
| 5 | 5 | 0.328819 | 0.156381 | 1.8341 | 3.88791 |
| 6 | 6 | 0.362383 | 0.161 | 1.98996 | 3.23731 |
| 7 | 7 | 0.395948 | 0.166573 | 2.12488 | 2.64816 |
| 8 | 8 | 0.429512 | 0.173116 | 2.23846 | 2.25263 |
| 9 | 9 | 0.463076 | 0.181014 | 2.32621 | 1.96077 |
| 10 | 10 | 0.49664 | 0.190483 | 2.38678 | 1.75221 |
| 11 | 11 | 0.530205 | 0.207966 | 2.34752 | 1.97986 |
| 12 | 12 | 0.563769 | 0.235332 | 2.21716 | 1.94099 |
| 13 | 13 | 0.597333 | 0.269586 | 2.05995 | 1.66373 |
| 14 | 14 | 0.630897 | 0.308442 | 1.90927 | 1.3112 |
| 15 | 15 | 0.664462 | 0.350372 | 1.77657 | 1.0 |
The paths of a population
A combinatorial cross-validation gives many paths, and the summary of the population gives one entry for each path. Each figure of a path is one estimate, and the column of a figure is its distribution over the paths. The summary does not reduce the paths, because the mean of a ratio is not the ratio of the means. Reduce them yourself, for example with describe.
ppred = cross_val_predict(MeanRisk(; obj = MinimumRisk(), opt = JuMPOptimiser(; slv = slv)), rd, CombinatorialCrossValidation(; n_folds = 5, n_test_folds = 2))pps = performance_summary(ppred; ppy = 252, rf = rf)describe(DataFrame(pps)[:, [:sharpe, :max_drawdown, :n_eff]], :mean, :median, :min, :max)| Row | variable | mean | median | min | max |
|---|---|---|---|---|---|
| Symbol | Float64 | Float64 | Float64 | Float64 | |
| 1 | sharpe | 0.957936 | 0.967103 | 0.861798 | 1.03574 |
| 2 | max_drawdown | -0.110686 | -0.107142 | -0.123293 | -0.105167 |
| 3 | n_eff | 4.86686 | 5.12133 | 3.6613 | 5.56348 |
The plot of a summary of many entries draws one panel for each figure, with one bar for each entry.
plot_performance_summary(ps; size = (1000, 900))6. Risk and return
plot_measures plots portfolios on any pair of risk and return axes. plot_efficient_frontier plots the efficient frontier, the portfolios with the least risk for each level of return.
plot_efficient_frontier(frontier.w, pr; rt = frontier.ret)7. The dashboard
plot_portfolio_dashboard puts the composition, the risk and the performance of one portfolio into one figure.
plot_portfolio_dashboard(res_ratio, rd; r = factory(Variance(), pr))This page shows some of the plots, not all. The library also plots networks and clusters (plot_network, plot_dendrogram, plot_clusters, plot_centrality), cross-validation (plot_cv_scores, plot_cv_dashboard), turnover (plot_turnover), and the higher moments (plot_coskewness, plot_cokurtosis).
This page was generated using Literate.jl.