This lecture is a bootcamp in Python and linear algebra. We’ll start by opening a data file and getting comfortable with the table. What does a row represent? Which column has the values we want? Once we know how to pick out the numbers for one calculation, we can write a loop to repeat it. Working through the first few trips through the loop lets us see which values Python uses each time and where the answers go.
Once we understand those steps, we can use functions for tasks that come up often. After calculating a few percentage changes in a loop, we’ll use a pandas method, a function we call on the table, to calculate the changes for every column. We can check that the first few answers agree. The same idea applies to visualizing data. We give a plotting function the dates and values we want to see. With two series on the same axes, we can spot where their paths diverge, something that’s hard to see by reading down two columns.
You may have seen vectors and matrices in a math course. It turns out that these are useful when we’re working with data. A vector keeps a list of numbers in order, and a matrix lets us arrange several of those lists in rows or columns. Let’s work through an example with stock returns and portfolio weights. For one date and one allocation, we multiply each stock’s return by its weight and add the products. That’s a dot product. To compare allocations on that same date, we can give each allocation its own weight column and work out all the dot products in one matrix multiplication.
By the end of the lecture, you should be able to pick an entry of a matrix product, trace it back to the row and column that produced it, and check it in Python. In Lecture 2, we’ll use the same calculation to get a fitted value in a regression.
2 From Prices to Returns
2.1 Read and plot the price data
The adjusted closes in stock_prices_daily.csv come from the course’s archived stock price data.
We want to see how the price of a stock changes over time. First we need to open the file and find the dates and prices we’ll send to a plot. In Python, an import makes the tools in a package available. We give pandas the short name pd for working with tables, matplotlib’s plotting tools the name plt, and NumPy the name np for numerical operations we’ll use later. The left side of = names the result on the right. pd.read_csv opens the file as a DataFrame, pandas’ table of rows and columns. With parse_dates and index_col we read the dates as dates and make them the row labels. Run this example with the notebook open in your Lecture1 folder, with the shared Data folder one level up.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltprices = pd.read_csv('../Data/stock_prices_daily.csv', parse_dates=['date'], index_col='date')prices[['AAPL', 'MSFT']].head().round(2)
AAPL
MSFT
date
2018-01-02
40.48
79.47
2018-01-03
40.47
79.84
2018-01-04
40.66
80.55
2018-01-05
41.12
81.55
2018-01-08
40.97
81.63
The list ['AAPL', 'MSFT'] selects the Apple and Microsoft columns. .head() shows the first few rows, and .round(2) displays the prices to two decimal places. To plot just Apple, prices['AAPL'] selects that column and prices.index gives its dates. The two arguments to plt.plot give the horizontal and vertical coordinates in that order.
Look at the fall and recovery around 2020, then try substituting Microsoft for Apple. To see when the two paths move together or diverge, put both on the same axes. Two calls to plt.plot before plt.show() put both series in the same drawing. Give each a label and use plt.legend() so you can tell which is which.
Apple and Microsoft’s adjusted closes on the same axes.
Microsoft starts at a higher value and ends at a higher value. The levels tell us the scale of each series. To compare performance, we need to divide each change by its own starting value. A dollar gained on $20 and a dollar gained on $200 are very different results.
2.2 Calculate one return, then repeat
A simple return tells us how much the price changed relative to its starting value. Let \(P_t\) be a stock’s adjusted close on trading date \(t\). The return is
The subscript \(t\) identifies a date in the sequence of trading dates. The subscript \(t-1\) means the preceding trading date, so for a Monday it usually refers to Friday. We record \(r_t\) on date \(t\), when both prices are known. The first price in the file supplies the starting value for the return on the second date. We calculate returns as decimals and multiply by 100 to display them as percentages.
To repeat the calculation, we need the current and preceding prices at each step. In pandas, .iloc stands for integer location. Here apple is a single column, so apple.iloc[t] looks up its price by row number. Python starts counting at zero. apple.iloc[0] gets the first row and apple.iloc[1] gets the second. range(1, 4) supplies row numbers 1, 2 and 3, starting at 1 so there is a preceding row for each calculation. For each t, Python executes the indented lines, reads the two prices, calculates the return, and moves on. The price we called current becomes the previous price on the next trip through the loop.
apple = prices['AAPL']for t inrange(1, 4): previous = apple.iloc[t -1] current = apple.iloc[t] daily_return = current / previous -1print(apple.index[t].date(), 100* daily_return)
The first three Apple returns are \(-0.0174\%\), \(0.4645\%\) and \(1.1385\%\). To compare stocks or combine them in a portfolio, we’ll need the same calculation for every stock on every date. Pandas can repeat the divide-and-subtract calculation down every price series with pct_change. Its result is a decimal change. fill_method=None uses the observed prices without filling a missing value. In this complete panel, dropna() removes one row, leaving 1,508 daily returns. The first three values of the Apple column agree with the loop.
We now have a return for each stock on each date. If we hold several of these stocks together, what did we earn on the portfolio? How much each stock contributes depends on how much of our money we put in it.
3.1 From weights to contributions
Suppose I have $100 to invest and you have $1,000,000. We split our money evenly across the same ten stocks. I put $10 into each stock and you put $100,000 into each. A stock’s portfolio weight is its fraction of the portfolio’s starting value. Divide each holding by the total and the weights are the same for both of us, 10% in each stock.
Say one stock goes up 1% and the other nine stay flat. I gain ten cents on my $100 and you gain $1,000 on your $1,000,000. Divide each gain by the starting value and we both earn 0.10%. A portfolio return is scale-invariant, just like an individual stock return. When we multiply every holding by the same factor, both the gain and the starting value get multiplied by that factor, which cancels when we divide. The weights stay the same too, so we can work with weights to calculate the portfolio return.
In our example, the stock that went up accounted for one tenth of the starting portfolio value, so one tenth of its 1% return made it into the portfolio return. We can do that calculation for every stock, including those whose prices fell. Let \(R_{i,t}\) be the return on stock \(i\) on date \(t\), and let \(w_i\) be its weight at the beginning of the day. Then \(w_iR_{i,t}\) is the stock’s contribution. The capital sigma in the formula means “add up.” The index \(i\) runs from the first stock to the last, and \(n\) is the number of stocks.
\[R_{p,t}=\sum_{i=1}^{n}w_i R_{i,t}.\]
Let’s do this for the first date in our return table. We use the ten stock columns and set aside SP500, which is the market index. np.ones(n) gives us a list of \(n\) ones, and dividing by n gives each stock \(1/n\) of the money. On each trip through the loop, we use i to get the stock’s ticker and its weight from the same position in their respective lists. .iloc[0] gets that stock’s return on the first date. We multiply by its weight and add the contribution to the running total.
Nvidia rose about 6.58% on January 3 and contributed about \(+0.6581\) percentage points. Tesla fell about 1.02% and contributed about \(-0.1023\) percentage points. Add the contributions at full precision and the portfolio earned 1.4062% on this day. The contribution tells you how much a position added to the return of the whole portfolio.
3.2 Read the same calculation as a dot product
Look at what the loop needed to work. If we hold ten stocks, we need ten weights and ten returns for the date we’re calculating. Add a stock and we need one more entry in each list. The order matters too. If Apple is first, Apple’s weight has to go with Apple’s return. Once the two lists are lined up, the calculation is the same at every position.
An ordered list of numbers is a vector. Let’s write the weights in one column, \(\vec w\), and the returns for date \(t\) in another, \(\vec R_t\). Each column has \(n\) entries, and entry \(i\) in both columns refers to stock \(i\).
The loop multiplied the matched pairs and added the products. We call that sum a dot product and write it with a dot between the two vectors. Start with Apple’s return times Apple’s weight, add Microsoft’s return times Microsoft’s weight, and keep going until we’ve included every stock. The answer is one number, the portfolio return on date \(t\).
\[R_{p,t}=\vec R_t\cdot\vec w
=R_{1,t}w_1+R_{2,t}w_2+\cdots+R_{n,t}w_n.\]
In Python, .iloc[0] picks the first date’s returns and .to_numpy() gives us the numbers in their current order. Give np.dot the two arrays. It multiplies their entries position by position and adds up the products, just as we did in the loop.
We get 1.4062% again. The products are the ten contributions and the sum is the same one we accumulated in the loop.
4 Comparing Portfolio Allocations
4.1 Work out each portfolio’s return
On January 3, 2018, our equal-weight portfolio earned 1.4062%. How would we have done that same day with a different allocation? Let’s keep the same ten stocks and change just their weights. For the Apple tilt, move five percentage points from Microsoft to Apple. That gives us 15% Apple, 5% Microsoft and 10% in each of the other eight stocks. Apple and Microsoft are the first two stocks in the return table, so we can copy equal_weights and change those two entries.
We could also build a price-weighted portfolio. Think of holding one unit of each of the ten adjusted price series. Each stock’s weight is then its starting price divided by the sum of all ten starting prices. For the January 3 return, we use the January 2 adjusted closes. Microsoft’s adjusted close is $79.47 out of a total of $898.50, so it gets about 8.85% of the weight. In Python, prices[stock_returns.columns] gives us the same ten stocks in the same order as the returns. Select the January 2 row with .iloc[0], then divide each price by the sum.
Every allocation uses the same ten stock returns in first_returns. Give np.dot that same vector each time and change the weight vector. That gives us three portfolio returns. Pass their names and the returns in percent to plt.bar so each allocation gets one bar. plt.bar_label writes the return above each bar.
Portfolio returns on January 3, 2018, calculated with three dot products.
The Apple tilt earned 1.3821%, just below the equal-weight portfolio. Microsoft gained more than Apple that day, so moving some of its weight to Apple reduced the return. The price-weighted portfolio earned 1.2778%. Nvidia gained about 6.58% that day, and its starting price gave it about half a percent of the weight in that portfolio, compared with 10% in the equal-weight portfolio.
4.2 How do we do all three dot products at once?
Notice what we just did. We took three dot products against the same ten stock returns. The weights changed each time. Wouldn’t it be nice if we could do all three at once? It turns out we can. Matrix multiplication batches dot products.
A matrix arranges numbers in rows and columns. We write its shape with the number of rows first. To multiply two matrices, take a row from the first and a column from the second. Multiply the matching entries and add the products, just as we did with the weight and return vectors.
Look at the highlighted row and column below. The first entry of the row, \(a\), meets the first entry of the column, \(f\). The second pair is \(b\) and \(h\). Add those two products and write \(af+bh\) in row 1, column 2. Where would the answer go if we kept the same row and used the first column?
The highlighted first row and second column give the highlighted entry (af+bh) in the product.
Every pairing gives one entry of the result. If \(A\) has \(m\) rows and \(B\) has \(p\) columns, we have \(m\) rows and \(p\) columns of answers. The row we take from \(A\) and the column we take from \(B\) must have the same number of entries, \(n\), so every entry has a partner. In the product \(C=AB\), row \(i\) and column \(j\) give
\[C_{ij}=\sum_{k=1}^n A_{ik}B_{kj}.\]
The index \(k\) moves through the two lists one position at a time. In the highlighted example there are two positions, giving \(af+bh\).
4.3 Batch the January 3 returns
Now put our ten January 3 stock returns across one row, \(\mathbf r\). Stack the three weight vectors in columns to make \(W\). We have ten stocks across the return row and the same ten stocks down each weight column, in the same order. The single return row meets three weight columns, so the result has one row and three columns.
Take the second column, just as we did in the diagram. This time it’s the weights for the Apple tilt. The first two products are \((-0.0174)\times0.15\) for Apple and \(0.4654\times0.05\) for Microsoft, in percentage points. Add the other eight stock contributions to get 1.3821%, the second bar. Match the same row with the first and third weight columns to get the other two bars.
In Python, .reshape(1, n) arranges the stock returns in one row, np.column_stack puts each weight vector into its own column, and @ multiplies the two matrices. Use [0] to read the only row of the output and pass those three returns to the same bar chart. Compare the two sets of returns in the order of the bars.
Portfolio returns on January 3, 2018, calculated with one matrix multiplication.
The printed returns agree, and the bars have the same heights. Add a fourth allocation and we get a fourth weight column, a fourth dot product and a fourth bar. Before calculating it, pick the two inputs that will produce the new bar.
NoteAdvanced: A dot product is a special case of matrix multiplication
Take two column vectors \(x\) and \(y\), each with \(n\) entries. A column vector is an \(n\times1\) matrix. The transpose swaps rows and columns, so \(x^\prime\) is a \(1\times n\) row. We can also write \(x^\top\) and use .T in NumPy.
The product \(x^\prime y\) has just one row and one column. Its only entry is the sum we already know from the dot product.
For example, transpose the January 3 return column \(\vec R_t\) and multiply by the Apple-tilt weight column alone. The one entry gives the return in the second bar.
5 Portfolio Mean and Volatility
5.1 Read the return history
We now know how the three allocations did on January 3. What did the equal-weight portfolio earn on an average day, and how much did its return vary? To answer those questions, we need its return history. Take the equal weights as a single column and multiply all 1,508 rows of stock returns by that column. This describes a portfolio restored to equal weights at the start of each day, before trading costs. We take the resulting return column with [:, 0] and attach the original dates to it.
The historical mean adds the daily returns and divides by the number of dates. Here it gives 0.1206% per trading day. To measure how far the returns tend to be from that mean, we start with the difference between each day’s return and the mean. We square the differences so a day far below the mean counts as much as a day equally far above it. The sample variance adds the squares and divides by \(T-1\), where \(T\) is the number of returns. This denominator accounts for estimating the mean from the same data. The square root gives the standard deviation, back in the units of the return. For returns we call it volatility. The portfolio’s daily volatility is 1.799%. Apple’s daily volatility over these dates is 1.995%.
5.2 Average first, then apply the weights
If we’re comparing several allocations, do we have to calculate the whole return history for each one just to get its mean? Look at Apple’s contribution. On every date it is one tenth of Apple’s return, so its average contribution is one tenth of its average return, about \(0.0123\) percentage points per day. The same reasoning works for the other nine stocks. We can average the stocks once and apply a different set of weights for each allocation we want to check.
Before a day begins, the stock returns \(\vec R\) are uncertain. The expected return, \(\mathbb E[R_i]\), is an average over possible outcomes weighted by their probabilities. We estimate it with the stock’s sample mean, \(\bar R_i=\frac{1}{T}\sum_{t=1}^T R_{i,t}\). Each historical date gets the same weight in this estimate. For the portfolio’s expected return, the same weighted sum gives
We can use the same dot product as on January 3. This time match each stock’s weight with its average return. stock_returns.mean() gives one average per stock column, and np.dot multiplies the matching entries and adds them. Both routes give 0.1206% per day.
Can we work out portfolio volatility from the stocks in the same way? Imagine holding two stocks in equal weights. If both are a percentage point above their own means, the portfolio is a percentage point above its mean. If one is a point above and the other is a point below, their contributions cancel. The individual deviations are just as large in both cases. What changes is how they add up in the portfolio. To work out its volatility, we need to know how often and by how much the stocks move together.
Start with the difference between each stock’s return and its mean, as we did for variance. Now take two stocks on the same date and multiply their deviations. The product is positive when both are above their means or both are below. Opposite-signed deviations give a negative product. Covariance combines those products across the dates. We estimate it for stocks \(i\) and \(j\) with
The hat denotes the estimate from this sample. When \(i=j\) the two deviations are the same and their product is a square. This gives the sample variance. Dividing covariance by both standard deviations gives correlation, a unitless measure of linear co-movement on a scale from \(-1\) to \(1\).
With ten stocks, we want to look up the covariance for any pair. We already have an order for the stocks in the weight column. Use that order for both the rows and columns of a matrix \(\boldsymbol\Sigma\) (capital sigma). Then we can find, for example, the covariance of Apple with Microsoft in Apple’s row and Microsoft’s column. The diagonal pairs each stock with itself, giving the stock variances. The matrix is symmetric because reversing the order of the two stocks leaves the product of their deviations unchanged.
Here’s the upper-left corner of the sample covariance matrix. stock_returns.cov() calculates it, and .iloc[:3, :3] shows the first three rows and columns. The \(0.000284\) in the Apple row and Microsoft column is their sample covariance, in decimal-return units squared. We can find Apple’s variance in the same row, where Apple meets itself.
5.4 From the covariance matrix to portfolio volatility
To get a portfolio mean, we needed one weight for each stock’s average return. For portfolio variance we need a weight for each pair of stocks in the covariance matrix. If we put very little in Microsoft, its co-movement with Apple can have only a small effect on the portfolio, even if we hold a lot of Apple. The weight for the pair is \(w_iw_j\), the product of the two stocks’ weights.
Why the product? The portfolio’s deviation from its mean is a sum of weighted stock deviations. When you square that sum, every weighted deviation gets multiplied by every other one. Think of \((a+b)^2=a^2+2ab+b^2\). The cross term brings in both weights. Averaging the products of the stock deviations gives the covariances we already put in the matrix.
You can read \(\vec w^{\,\prime}\boldsymbol\Sigma\vec w\) from the middle out. On the right, Sigma @ w applies the column stock’s weight to each covariance. The result has one entry per row stock. On the left, w.T turns the weights into a row and applies the other weight. The product has shape \(1\times1\). Take its only entry and use np.sqrt to get back to return units. We can check it against the standard deviation of the daily portfolio returns.
Both routes give the same volatility because they use the same dates and weights. For long positions, positive cross terms reinforce portfolio fluctuations. Small or negative co-movements create room for diversification. Now think back to the price-weighted allocation. It earned less than the equal-weight portfolio on January 3. What would you need to compare the two allocations over the sample? Try using the January 2 price weights as fixed weights in the mean and volatility calculations. The stock means and covariance matrix are already in the right order for the new weight column.
6 Summary
A simple return compares the change in a price to its starting value. A portfolio return adds up those changes, weighted by where you put the money. One portfolio return is a dot product. Put each allocation in a column and a single matrix multiplication gives one return for every allocation.
A mean and a volatility summarize that return history. You can obtain the mean using the weighted stock averages. To obtain volatility from the individual stocks, you also need their co-movements. The covariance matrix stores them in the same order as the weights. Once you can trace an output entry back to the row and column that produced it, you can read both calculations.
Covariance lets us describe how two series move together. In Lecture 2 we’ll ask a related question about Apple and the market. If the market rises by 1%, how much would we expect Apple to move? We’ll use the return pairs to fit a rule, then use a dot product to get a fitted return from that rule.
7 Sources and Further Reading
The price snapshot is stock_prices_daily.csv, the frozen RSM338 course price panel. The source provider, download timestamp and original adjustment settings for these saved series are unavailable. The stock observations are third-party data. See Kevin Mott’s Linear Algebra for Quantitative Finance for more on batching dot products.