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.

When to reach for this

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, StatsPlots

1. 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)
Example block output

We also plot the correlation matrix on its own.

plot_correlation(pr)
Example block output

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"]))
Example block output

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)
Example block output

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)
Example block output

plot_drawdowns plots the drawdowns of the same portfolio.

plot_drawdowns(res_ratio.w, rd)
Example block output

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)
Example block output

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)
2×25 DataFrame
Rownamepathmemberdate0date1n_periodsann_returnann_volatilitysharpesharpe_stderrsortinocalmarmax_drawdowncvarexcess_rettracking_errorinformation_ratioturnovern_efflong_exposureshort_exposuregross_exposurenet_exposurecvar_99ulcer
StringNothingNothingDateDateInt64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64
1min risk2021-12-292022-12-282520.1945620.1483391.028471.000951.535612.1172-0.0918958-0.0187291NaNNaNNaNNaN4.880081.00.01.01.00.02706880.0347171
2max ratio2021-12-292022-12-282520.503520.193112.389940.9981283.886255.07847-0.099148-0.023244NaNNaNNaNNaN1.814771.00.01.01.00.03140780.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]]
15×5 DataFrame
Rowmemberann_returnann_volatilitysharpen_eff
Int64Float64Float64Float64Float64
110.194850.1483391.03044.88518
220.2281270.1487611.251194.93017
330.2616910.1502061.46264.94323
440.2952550.1527641.657824.53748
550.3288190.1563811.83413.88791
660.3623830.1611.989963.23731
770.3959480.1665732.124882.64816
880.4295120.1731162.238462.25263
990.4630760.1810142.326211.96077
10100.496640.1904832.386781.75221
11110.5302050.2079662.347521.97986
12120.5637690.2353322.217161.94099
13130.5973330.2695862.059951.66373
14140.6308970.3084421.909271.3112
15150.6644620.3503721.776571.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)
3×5 DataFrame
Rowvariablemeanmedianminmax
SymbolFloat64Float64Float64Float64
1sharpe0.9579360.9671030.8617981.03574
2max_drawdown-0.110686-0.107142-0.123293-0.105167
3n_eff4.866865.121333.66135.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))
Example block output

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)
Example block output

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))
Example block output

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.