dcelisgarza
PortfolioOptimisers.jl
Julia

Portfolio Optimisation library built in Julia.

Last updated Jul 9, 2026
15
Stars
1
Forks
14
Issues
+1
Stars/day
Attention Score
53
Language breakdown
No language data available.
Files click to expand
README

PortfolioOptimisers.jl

| Category | Badge | | :--------- | :---- | | Docs | Stable Documentation Development documentation | | CI | Test workflow status Docs workflow Status Aqua | | Coverage | Coverage | | Contribute | Contributor Covenant | | Misc | BestieTemplate |

[!CAUTION]
Investing conveys real risk, the entire point of portfolio optimisation is to minimise it to tolerable levels. The examples use outdated data and a variety of stocks (including what I consider to be meme stocks) for demonstration purposes only. None of the information in this documentation should be taken as financial advice. Any advice is limited to improving portfolio construction, most of which is common investment and statistical knowledge.

Portfolio optimisation is the science of either:

  • Minimising risk whilst keeping returns to acceptable levels.
  • Maximising returns whilst keeping risk to acceptable levels.
To some definition of acceptable, and with any number of additional constraints available to the optimisation type.

There exist myriad statistical, pre- and post-processing, optimisations, and constraints that allow one to explore an extensive landscape of "optimal" portfolios.

PortfolioOptimisers.jl is an attempt at providing as many of these as possible under a single banner. We make extensive use of Julia's type system, module extensions, and multiple dispatch to simplify development and maintenance.

Please visit the documentation for details on the vast feature list.

Installation

PortfolioOptimisers.jl is a registered package, so installation is as simple as:

julia> using Pkg

julia> Pkg.add(PackageSpec(; name = "PortfolioOptimisers"))

Roadmap

  • For a roadmap of planned and desired features in no particular order please refer to Issue #37.
  • Some docstrings are incomplete and/or outdated, please refer to Issue #58 for details on what docstrings have been completed in the dev branch.

Quick-start

The library is quite powerful and extremely flexible. Here is what a very basic end-to-end workflow can look like. The examples contain more thorough explanations and demos. The API docs contain toy examples of the many, many features.

First we import the packages we will need for the example.

  • StatsPlots and GraphRecipes is needed to load the plotting extension.
  • Clarabel and HiGHS are the optimisers we will use.
  • YFinance and TimeSeries for downloading and preprocessing price data.
  • PrettyTables and DataFrames for displaying the results.
# Import module and plotting extension.
using PortfolioOptimisers, StatsPlots, GraphRecipes

Import optimisers.

using Clarabel, HiGHS

Download data.

using YFinance, TimeSeries

Pretty printing.

using PrettyTables, DataFrames

Format for pretty tables.

fmt1 = (v, i, j) -> begin if j == 1 return Date(v) else return v end end; fmt2 = (v, i, j) -> begin if j ∈ (1, 2, 3) return v else return isa(v, Number) ? "$(round(v*100, digits=3)) %" : v end end

Function to convert prices to time array.

function stockpricetotimearray(x) # Only get the keys that are not ticker or datetime. coln = collect(keys(x))[3:end] # Convert the dictionary into a matrix. m = hcat([x[k] for k in coln]...) return TimeArray(x["timestamp"], m, Symbol.(coln), x["ticker"]) end

Tickers to download. These are popular meme stocks, use something better.

assets = sort!(["SOUN", "RIVN", "GME", "AMC", "SOFI", "ENVX", "ANVS", "LUNR", "EOSE", "SMR", "NVAX", "UPST", "ACHR", "RKLB", "MARA", "LGVN", "LCID", "CHPT", "MAXN", "BB"])

Prices date range.

Date_0 = "2024-01-01" Date_1 = "2025-10-05"

Download the price data using YFinance.

prices = getprices.(assets; startdt = Date0, enddt = Date_1) prices = stockpricetotimearray.(prices) prices = hcat(prices...) cidx = colnames(prices)[occursin.(r"adj", string.(colnames(prices)))] prices = prices[cidx] TimeSeries.rename!(prices, Symbol.(assets)) pretty_table(prices[(end - 5):end]; formatters = [fmt1])

Compute the returns.

rd = pricestoreturns(prices)

Define the continuous solver.

slv = Solver(; name = :clarabel1, solver = Clarabel.Optimizer, settings = Dict("verbose" => false, "maxstepfraction" => 0.9), checksol = (; allowlocal = true, allow_almost = true))

PortfolioOptimisers.jl implements a number of optimisation types as estimators. All the ones which use mathematical optimisation require a JuMPOptimiser structure which defines general solver constraints. This structure in turn requires an instance (or vector) of Solver.

opt = JuMPOptimiser(; slv = slv);

Vanilla (Markowitz) mean risk optimisation, i.e. minimum variance portfolio

mr = MeanRisk(; opt = opt)

Perform the optimisation, res.w contains the optimal weights.

res = optimise(mr, rd)

Define the MIP solver for finite discrete allocation.

mip_slv = Solver(; name = :highs1, solver = HiGHS.Optimizer, settings = Dict("logtoconsole" => false), checksol = (; allowlocal = true, allow_almost = true));

Discrete finite allocation.

da = DiscreteAllocation(; slv = mip_slv)

Perform the finite discrete allocation, uses the final asset

prices, and an available cash amount. This is for us mortals

without infinite wealth.

mip_res = optimise(da, FiniteAllocationInput(; w = res.w, prices = vec(values(prices[end])), cash = 4206.90))

df = DataFrame(:assets => rd.nx, :shares => mipres.shares, :cost => mipres.cost, :optweights => res.w, :mipweights => mip_res.w) pretty_table(df; formatters = [fmt2])

Plot the portfolio cumulative returns of the finite allocation portfolio.

plotptfcumulativereturns(mipres.w, rd.X; ts = rd.ts, compound = true)

Fig. 1

# Furthermore, we can also plot the risk contribution per asset. For this, we must provide an instance of the risk measure we want to use with the appropriate statistics/parameters. We can do this by using the factory function (recommended when doing so programmatically), or manually set the quantities ourselves.
plotriskcontribution(factory(Variance(), res.pr), mip_res.w, rd.X; nx = rd.nx, erc = false)

This awkwardness is due to the fact that PortfolioOptimisers.jl tries to decouple the risk measures from optimisation estimators and results. However, the advantage of this approach is that it lets us use multiple different risk measures as part of the risk expression, or as risk limits in optimisations. We explore this further in the examples.

Fig. 2

# We can also plot the returns' histogram and probability density.
plothistogram(mipres.w, rd.X; slv = slv)

Fig. 3

# Plot compounded or uncompounded drawdowns.
plotdrawdowns(mipres.w, rd.X; slv = slv, ts = rd.ts, compound = true)

Fig. 4

🔗 More in this category

© 2026 GitRepoTrend · dcelisgarza/PortfolioOptimisers.jl · Updated daily from GitHub