411 REFERENCE · Wikibooks
Scientific Calculations with Julia/Maximizing Returns in Finance
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
Scientific Calculations with Julia Maximizing Returns in Finance Risk Minimization in Finance Portfolio Optimization in Finance
In finance, when you want to maximize the expected return of a portfolio of n assets, such as n stocks, you solve the problem by minimizing the following objective function, which is typically a linear programming problem:
where are the portfolio weights, is the vector of expected returns.
Implementation in Julia
First, I install the Julia libraries I need:
using Pkg
Pkg.add(["JuMP", "HiGHS"])
Suppose we consider three stocks: Apple (AAPL), Microsoft (MSFT), and Amazon ("AMZN"). Using the YFinance package, I download daily prices for the last 5 years and transform the data into a DataFrame:
using YFinance, DataFrames, Statistics
tickers = ["AAPL", "MSFT", "AMZN"]
data = get_prices.(tickers, range="5y", interval="1d")
data = data |> DataFrame
I create a dictionary and then a DataFrame with the closing prices of the stocks and their respective dates:
prices = Dict()
for t in tickers
prices[t] = data[data.ticker.==t,"close"] # adjusted price column
end
# Convert to a single DataFrame
df = DataFrame(Date = data[data.ticker.=="AMZN","timestamp"])
for t in tickers
df[!, t] = prices[t]
end
df
Calculate the expected annual returns of the three stocks and note that Apple's returns are higher at 15.82%:
Date = reduce(vcat, df.Date)
AAPL = reduce(vcat, df.AAPL)
MSFT = reduce(vcat, df.MSFT)
AMZN = reduce(vcat, df.AMZN)
# Calculate daily returns
rets = dropmissing(DataFrame(
Date = Date[2:end],
AAPL = diff(log.(AAPL)),
MSFT = diff(log.(MSFT)),
AMZN = diff(log.(AMZN)),
))
# Daily average → annualized (252 days)
μ = Dict(
"AAPL" => mean(rets.AAPL) * 252,
"MSFT" => mean(rets.MSFT) * 252,
"AMZN" => mean(rets.AMZN) * 252,
)
println("Annualized expected returns:")
println(μ)
Annualized expected returns:
Dict("MSFT" => 0.11644058687702825, "AMZN" => 0.07435392903921334, "AAPL" => 0.1582824969436331)
Using the HiGHS linear programming model, we choose the optimal weights and note that all the capital goes to Apple because it has the highest expected return, but risk or variance minimization must be taken into account - portfolio volatility:
using JuMP, HiGHS, LinearAlgebra
mu_vec = [μ["AAPL"], μ["MSFT"], μ["AMZN"]]
n = length(mu_vec)
model = Model(HiGHS.Optimizer)
@variable(model, w[1:n] >= 0)
@constraint(model, sum(w) == 1)
@objective(model, Max, dot(mu_vec, w))
optimize!(model)
println("------------------------------------------------------------------------")
println("Optimal weights: ", value.(w))
println("Expected return: ", objective_value(model))
Running HiGHS 1.13.1 (git hash: 1d267d97c): Copyright (c) 2026 under Apache 2.0 license terms
Using BLAS: blastrampoline
LP has 1 row; 3 cols; 3 nonzeros
Coefficient ranges:
Matrix [1e+00, 1e+00]
Cost [7e-02, 2e-01]
Bound [0e+00, 0e+00]
RHS [1e+00, 1e+00]
Presolving model
1 rows, 1 cols, 1 nonzeros 0s
0 rows, 0 cols, 0 nonzeros 0s
Presolve reductions: rows 0(-1); columns 0(-3); nonzeros 0(-3) - Reduced to empty
Performed postsolve
Solving the original LP from the solution after postsolve
Model status : Optimal
Objective value : 1.5828249694e-01
P-D objective error : 0.0000000000e+00
HiGHS run time : 0.00
----------------------------------------------------------------------
Optimal weights: [1.0, 0.0, 0.0]
Expected return: 0.1582824969436331