I am trying to calculate the first and second order moments for a portfolio of stocks (i.e. expected return and standard deviation).
expected_returns_annual
In NumPy, a transpose .T
reverses the order of dimensions, which means that it doesn't do anything to your one-dimensional array weights
.
This is a common source of confusion for people coming from Matlab, in which one-dimensional arrays do not exist. See Transposing a NumPy Array for some earlier discussion of this.
np.dot(x,y)
has complicated behavior on higher-dimensional arrays, but its behavior when it's fed two one-dimensional arrays is very simple: it takes the inner product. If we wanted to get the equivalent result as a matrix product of a row and column instead, we'd have to write something like
np.asscalar(x @ y[:, np.newaxis])
adding a trailing dimension to y
to turn it into a "column", multiplying, and then converting our one-element array back into a scalar. But np.dot(x,y)
is much faster and more efficient, so we just use that.
Edit: actually, this was dumb on my part. You can, of course, just write matrix multiplication x @ y
to get equivalent behavior to np.dot
for one-dimensional arrays, as tel's excellent answer points out.