How do I calculate portfolio returns with @?

Turn a days-by-stocks return matrix and a weight vector into daily portfolio returns with returns @ weights, check one day by hand, and keep the weights in the order of the columns.

After this lesson, you can turn daily stock returns and portfolio weights into the portfolio’s daily return in one line.

How does one product give every day’s return?

A portfolio’s return on a day is the sum of each stock’s return times its weight, and returns @ weights computes that sum for every row of the return matrix at once, one portfolio return per day. On 2 March, with weights of 0.5, 0.3 and 0.2, it is 0.47%.

\[ r_{p,t} = \sum_{j} w_j\, r_{j,t} \]

Here \(r_{j,t}\) is stock \(j\)’s return on day \(t\), \(w_j\) its weight at the start of the day, and the weights add up to 1.

The returns are three made-up stocks’ daily returns in decimals over eight days, one column per stock, as in the lesson on return matrices. NumPy has no labels, so the weights must follow the order of the columns, which the list comprehension makes sure of by reading the weight dictionary in the order of tickers. (returns * weights).sum(axis=1) gives the same totals, as in the lesson on portfolio weights, and also keeps each stock’s contribution.

The following box builds the weights in column order and computes the daily returns.

import numpy as np

tickers = ["AAA", "BBB", "CCC"]
returns = np.column_stack([
    [0.0120, -0.0085, 0.0034, -0.0151, 0.0062, 0.0097, -0.0023, 0.0045],
    [-0.0064, 0.0102, -0.0130, 0.0058, -0.0011, 0.0076, 0.0149, -0.0092],
    [0.0031, -0.0047, 0.0088, 0.0015, -0.0203, 0.0124, 0.0006, 0.0071],
])
weight_of = {"BBB": 0.3, "CCC": 0.2, "AAA": 0.5}
weights = np.array([weight_of[ticker] for ticker in tickers])
portfolio = returns @ weights
print(weights, portfolio.round(5))
print(round(0.5 * 0.0120 + 0.3 * -0.0064 + 0.2 * 0.0031, 5))
[0.5 0.3 0.2] [ 0.0047  -0.00213 -0.00044 -0.00551 -0.00129  0.00961  0.00344  0.00091]
0.0047

What if two weights are in the wrong order?

Swapped weights still fit the shape, so NumPy computes a wrong return without an error. Giving AAA 0.3 and BBB 0.5 lowers the 2 March return from 0.47% to 0.102%.

The same weights on every row describe a portfolio that is rebalanced to them before each day, as the lesson on drifting weights explains.

The following box compares the right and the swapped weights on the first three days.

print(np.column_stack([portfolio[:3], returns[:3] @ np.array([0.3, 0.5, 0.2])]).round(5))
[[ 0.0047   0.00102]
 [-0.00213  0.00161]
 [-0.00044 -0.00372]]

Your turn

With a third in each stock, print the 2 March return in percent and check that every day’s return equals the row’s mean. You should see 0.29% True.

np.full(3, 1 / 3) makes three equal weights.

equal = returns @ np.full(3, 1 / 3)
print(f"{equal[0]:.2%}", np.allclose(equal, returns.mean(axis=1)))
0.29% True