Portfolio Optimisation with Linear Algebra in Python
Before we get into more complex concepts and techniques in finance (or even data science), it’s good to just get started by going back to…
Portfolio Optimisation with Linear Algebra in Python
Before we get into more complex concepts and techniques in finance (or even data science), it’s good to just get started by going back to school.
Let’s quickly see how to do linear algebra with the numpy library, and solve a very simple portfolio optimisation problem.
Before we get into the portfolio optimisation problem, let’s try to solve a set of linear equations.
We can solve the following equations in numpy quite easily.
2x + 3y + 4z = 11
10x + y + z = 32
5x + 7y + 8z = 20
Express these equations in matrices.
A = np.array([[2, 3, 4], [10, 1, 1], [5, 7, 8]])
b = np.array([[11], [32], [20]])And solve it with the numpy function — linalg.solve.
x = np.linalg.solve(A, b)Linear Algebra for a Simple Portfolio Optimisation
With this same approach, let’s try getting an optimised portfolio of CASH, EQUITIES and BONDS. The assumptions/constraints to apply are as follows -
Proportion of CASH, EQUITIES, and BONDS should add up to 1 (i.e. 100%)
The mix of CASH, EQUITIES and BONDS should give us a total return of 0.05 (i.e. 5%)
CASH returns = 0.01, EQUITIES returns = 0.1, BOND returns = 0.05
Proportion of CASH should be 0.2 (20%)
The corresponding equations are -
CASH + EQUITIES + BONDS = 1
0.01*CASH + 0.1*EQUITIES + 0.05*BONDS = 0.05
CASH = 0.2
Express these equations as matrices again.
A = np.array([[1,1,1], [0.01,0.1,0.05], [1,0,0]])
B = np.array([1,0.05,0.2])And solve it.
print(np.linalg.solve(A,B))
[ 0.2 0.16 0.64]A portfolio with 20% in CASH, 16% in EQUITIES and 64% in BONDS will get us what we want.
The notebook here has the code above, and also some other common linear algebra operations.

