How do I calculate one result per stock or per day?

Use axis=0 for one result per stock and axis=1 for one result per day on a days-by-stocks return matrix, and check the daily mean against a hand calculation.

After this lesson, you can compute each stock’s average return and each day’s equally weighted portfolio return from one matrix.

How do I get one mean per stock?

On a matrix with one row per day and one column per stock, returns.mean(axis=0) runs down the rows and gives one mean per stock. AAA’s average daily return is 0.124%, the highest of the three. Without an axis, .mean() averages all 24 cells into one number.

The returns are three made-up stocks’ daily returns in decimals over eight days, as in the lesson on return matrices. The shape (8, 3) gives the number of rows first, axis 0, and the number of columns second, axis 1. The same axes work for .sum() and .std().

The following box computes the means per stock and over all cells.

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],
])
print(returns.shape)
print(dict(zip(tickers, returns.mean(axis=0).round(5).tolist())), returns.mean().round(5))
(8, 3)
{'AAA': 0.00124, 'BBB': 0.0011, 'CCC': 0.00106} 0.00113

How do I get one portfolio return per day?

returns.mean(axis=1) runs across each row and gives one mean per day, which is the return of a portfolio with a third in each stock at the start of each day. On 2 March it is \((0.0120 - 0.0064 + 0.0031) / 3 = 0.0029\).

The following box computes the eight daily means and checks 2 March by hand.

daily = returns.mean(axis=1)
print(daily.shape, daily.round(5))
print(round((0.0120 - 0.0064 + 0.0031) / 3, 5))
(8,) [ 0.0029  -0.001   -0.00027 -0.0026  -0.00507  0.0099   0.0044   0.0008 ]
0.0029

The lesson on portfolio weights computes the same return with weights other than a third.

Your turn

Print each stock’s daily volatility, the sample standard deviation of its returns, in percent with two decimals. You should see 0.93 for AAA, 1.0 for BBB and 1.01 for CCC.

ddof=1 divides by 7, the number of returns minus 1, for the sample standard deviation.

print(dict(zip(tickers, (100 * returns.std(axis=0, ddof=1)).round(2).tolist())))
{'AAA': 0.93, 'BBB': 1.0, 'CCC': 1.01}