NumPy Financial Examples#
This notebook presents a wide range of financial examples using NumPy.
We’ll first work through some compounding examples bfore moving on to analyzing stocks through their prices over time.
1import numpy as np
2
3# Set print options for better readability
4np.set_printoptions(precision=4, suppress=True,linewidth=120)
Compounding#
When you work with money over time, you almost always end up doing the same two things:
Letting some initial amount grow by compounding interest (a lump-sum investment).
Adding new money at regular intervals (a systematic investment plan), then letting all of it compound.
Both of these are inherently time-series operations: the value in year 10 depends on what happened in years 1–9.
When first presenting Python, we used iteration (explicit loops) to calculate the time value of money.
NumPy gives us another way: treat the entire sequence of years, rates, and balances as arrays, and let NumPy do the looping for us under the hood. That not only makes the code shorter and often faster, it also encourages us to think in terms of whole scenarios rather than one period at a time.
Below we’ll start with a simple lump-sum compounding example, then build tables of yearly balances and rate scenarios using NumPy instead of manual iteration.
Single Interest Rate Compounding#
1initial_amount = 1000
2interest_rate = 0.05 # 5% annual interest
3interest_rates = np.full(10, interest_rate) # e.g., annual rates for 10 years
4growth_factors = 1 + interest_rates
5
6# Calculate the value after each compounding period
7cumulative_growth = np.cumprod(growth_factors)
8yearly_amounts = initial_amount * cumulative_growth
9
10print(f"Cumulative growth factors: {cumulative_growth}")
11print("Value after each year:", yearly_amounts)
12
13print(f"Final amount after compounding: {yearly_amounts[-1]:.2f}")
Cumulative growth factors: [1.05 1.1025 1.1576 1.2155 1.2763 1.3401 1.4071 1.4775 1.5513 1.6289]
Value after each year: [1050. 1102.5 1157.625 1215.5063 1276.2816 1340.0956 1407.1004 1477.4554 1551.3282 1628.8946]
Final amount after compounding: 1628.89
Here’s what this code is doing, step by step:
interest_ratesis a length-10 NumPy array:[0.05, 0.05, ..., 0.05].growth_factorsturns those into per-year multipliers:[1.05, 1.05, ..., 1.05].np.cumprod(growth_factors)computes the cumulative product:After year 1:
1.05After year 2:
1.05 * 1.05…
After year 10:
1.05 ** 10
amountsmultiplies each growth factor by the initial amount, giving the balance at the end of each year.final_amountis just the last entry ofamounts, pulled out explicitly.
In other words, we’ve replaced a loop like:
balance = initial_amount
balances = []
for r in interest_rates:
balance *= (1 + r)
balances.append(balance)
with a handful of array operations.
Random Interest Rate Compounding#
Now, we can easily move into stochastic compounding.
So far, we’ve assumed a constant 5% interest rate every year. Real markets don’t behave that politely. To make our example more realistic, we can approximate stock-market-like behavior by drawing yearly returns from a normal distribution calibrated to a broad index such as the Dow Jones Industrial Average.
Historically, US stock indices have delivered around 10% average nominal annual returns, with a relatively high year-to-year volatility (standard deviation) of around 18%. We’ll use those two numbers as parameters for a normal distribution, and let NumPy generate a different sequence of annual returns for us each time we run the code.
So we’ll replace
interest_rates = np.full(10, 0.05)
with
mean_return = 0.10 # 10% average annual return
std_return = 0.18 # 18% standard deviation
n_years = 10
# Draw 10 random annual returns from a normal distribution
interest_rates = np.random.normal(loc=mean_return,
scale=std_return,
size=n_years)
While it looks like more code, that’s due to explainability. We could have written this as
interest_rates = np.random.normal(loc=0.10, scale=0.18, size=10)
The completed code
1np.random.seed(42) # to make the example reproducible
2
3initial_amount = 1000
4
5# Approximate DJIA-style parameters (nominal)
6mean_return = 0.10 # 10% average annual return
7std_return = 0.18 # 18% standard deviation
8
9n_years = 10
10
11# Draw 10 random annual returns from a normal distribution
12interest_rates = np.random.normal(loc=mean_return,
13 scale=std_return,
14 size=n_years)
15
16growth_factors = 1 + interest_rates
17
18# Calculate the value after each compounding period
19cumulative_growth = np.cumprod(growth_factors)
20amounts = initial_amount * cumulative_growth
21final_amount = amounts[-1]
22
23print("Random annual returns:")
24print(interest_rates)
25print("\nCumulative growth factors:")
26print(cumulative_growth)
27print("\nAmounts by year:")
28print(amounts)
29print(f"\nFinal amount after {n_years} years: {final_amount:.2f}")
Random annual returns:
[0.1894 0.0751 0.2166 0.3741 0.0579 0.0579 0.3843 0.2381 0.0155 0.1977]
Cumulative growth factors:
[1.1894 1.2787 1.5557 2.1378 2.2614 2.3923 3.3115 4.1001 4.1637 4.9866]
Amounts by year:
[1189.4085 1278.7479 1555.7042 2137.7637 2261.4384 2392.2747 3311.5262 4100.1272 4163.6571 4986.6489]
Final amount after 10 years: 4986.65
This is the same NumPy machinery (vectorized operations, np.cumprod, np.column_stack)
but now driven by random draws instead of fixed numbers.
Financially, each run is a different possible “history” of the market. we can use this underlying concept to develop simulations and Monte Carlo analysis.
Comparing different interest rates#
In many financial scenarios, we want to compare how the final value changes across different rates. Previously, you might have written nested loops: an outer loop over rates and an inner loop over years.
With NumPy, we can generate a table of final balances for a range of interest rates in one shot.
Suppose we want to see the value after 10 years for rates from 1% to 10%:
1initial_amount = 1000
2N = 10
3
4# Years 1..N
5years = np.arange(1, N + 1) # shape (N,)
6
7# Interest rates from 1% to 10% (note: upper bound is exclusive, so use 0.11)
8rates = np.arange(0.01, 0.11, 0.01) # shape (N,)
9
10# Reshape rates to (N, 1) so NumPy can broadcast over years
11rates_2d = rates.reshape(-1, 1) # shape (N, 1)
12
13# growth_factors[i, j] = (1 + rates[i]) ** years[j]
14growth_factors = (1 + rates_2d) ** years # shape (N, N)
15
16# amounts[i, j] = future value for rate[i] at year[j]
17amounts = initial_amount * growth_factors # shape (N, N)
18
19print("Rates:", rates)
20print("Years:", years)
21print("Growth factors shape:", growth_factors.shape)
22print("Amounts shape:", amounts.shape)
23print("Final Amounts:\n", amounts[:, -1]) # Final amounts after N years for each rate
Rates: [0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1 ]
Years: [ 1 2 3 4 5 6 7 8 9 10]
Growth factors shape: (10, 10)
Amounts shape: (10, 10)
Final Amounts:
[1104.6221 1218.9944 1343.9164 1480.2443 1628.8946 1790.8477 1967.1514 2158.925 2367.3637 2593.7425]
What’s happening:
rates_2dhas shape (N, 1) — a column vector of rates.yearshas shape (N,) — a row-like 1D array of years.(1 + rates_2d) ** yearsuses broadcasting:Each rate in the column is raised to each year in the row.
Result: a full (N, N) grid.
So amounts[i, j] is the value of the investment using rates[i] after years[j] years.
The underlying idea:
Take all rates and all years, form every combination, and compute the future value in one vectorized shot.
Now, let’s pretty-print this table. We’ll use a combination of explicit and implicit loops to accomplish this.
1# Header row
2header = "Rate | " + " ".join(f"{y:>10d}" for y in years)
3print(header)
4print("-" * len(header))
5
6# Each row: fixed rate, amounts across years
7for i, r in enumerate(rates):
8 row_values = " ".join(f"{amounts[i, j]:10.2f}" for j in range(len(years)))
9 print(f"{r:>6.2%} | {row_values}")
Rate | 1 2 3 4 5 6 7 8 9 10
----------------------------------------------------------------------------------------------------------------------
1.00% | 1010.00 1020.10 1030.30 1040.60 1051.01 1061.52 1072.14 1082.86 1093.69 1104.62
2.00% | 1020.00 1040.40 1061.21 1082.43 1104.08 1126.16 1148.69 1171.66 1195.09 1218.99
3.00% | 1030.00 1060.90 1092.73 1125.51 1159.27 1194.05 1229.87 1266.77 1304.77 1343.92
4.00% | 1040.00 1081.60 1124.86 1169.86 1216.65 1265.32 1315.93 1368.57 1423.31 1480.24
5.00% | 1050.00 1102.50 1157.63 1215.51 1276.28 1340.10 1407.10 1477.46 1551.33 1628.89
6.00% | 1060.00 1123.60 1191.02 1262.48 1338.23 1418.52 1503.63 1593.85 1689.48 1790.85
7.00% | 1070.00 1144.90 1225.04 1310.80 1402.55 1500.73 1605.78 1718.19 1838.46 1967.15
8.00% | 1080.00 1166.40 1259.71 1360.49 1469.33 1586.87 1713.82 1850.93 1999.00 2158.92
9.00% | 1090.00 1188.10 1295.03 1411.58 1538.62 1677.10 1828.04 1992.56 2171.89 2367.36
10.00% | 1100.00 1210.00 1331.00 1464.10 1610.51 1771.56 1948.72 2143.59 2357.95 2593.74
System Investment Plan#
Now, we’ll start to look at cash flows over time instead of a single initial deposit.
We’ll assume:
You invest $100 at the end of every month.
Interest is compounded monthly.
Annual nominal rates from 1% to 10%.
Investment horizons from 1 to 10 years.
For a monthly contribution \((C)\), monthly rate \((i)\), and \((n)\) months, the future value is:
We’ll use NumPy broadcasting to compute FV for all combinations of:
10 annual rates (1–10%), and
10 horizons (1–10 years, i.e. 12–120 months)
giving us a 10 × 10 table.
1monthly_contribution = 100
2N = 10 # 1..10% and 1..10 years
3
4# Annual rates: 1% to 10% (inclusive)
5annual_rates = np.arange(0.01, 0.11, 0.01) # shape (10,)
6
7# Convert to monthly rates
8monthly_rates = annual_rates / 12 # shape (10,)
9monthly_rates_2d = monthly_rates.reshape(-1, 1) # shape (10, 1)
10
11# Investment horizons: 1..10 years
12years = np.arange(1, N + 1) # shape (10,)
13months = years * 12 # shape (10,)
14months_2d = months.reshape(1, -1) # shape (1, 10)
15
16# For each (rate, year) pair:
17# i = monthly_rates[row]
18# n = months[col]
19# FV factor = ((1 + i)^n - 1) / i
20growth_factors = (1 + monthly_rates_2d) ** months_2d # shape (10, 10)
21fv_factors = (growth_factors - 1) / monthly_rates_2d # shape (10, 10)
22
23sip_amounts = monthly_contribution * fv_factors # shape (10, 10)
24
25print("Years:", years)
26print("months_2d:", months_2d)
27print("Annual rates (%):", annual_rates * 100)
28print("SIP amounts shape:", sip_amounts.shape)
29
30# Now, print the SIP amounts table
31print("\nSIP Amounts Table of $100 monthly contribution")
32header = "Rate | " + " ".join(f"{y:>6d} yrs" for y in years)
33print(header)
34print("-" * len(header))
35
36# Each row: fixed rate, balances across years
37for i, r in enumerate(annual_rates):
38 row_values = " ".join(f"{sip_amounts[i, j]:10.2f}" for j in range(len(years)))
39 print(f"{r:>6.2%} | {row_values}")
Years: [ 1 2 3 4 5 6 7 8 9 10]
months_2d: [[ 12 24 36 48 60 72 84 96 108 120]]
Annual rates (%): [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
SIP amounts shape: (10, 10)
SIP Amounts Table of $100 monthly contribution
Rate | 1 yrs 2 yrs 3 yrs 4 yrs 5 yrs 6 yrs 7 yrs 8 yrs 9 yrs 10 yrs
----------------------------------------------------------------------------------------------------------------------
1.00% | 1205.52 2423.14 3653.00 4895.21 6149.90 7417.20 8697.23 9990.12 11295.99 12614.99
2.00% | 1211.06 2446.57 3707.01 4992.90 6304.74 7643.05 9008.39 10401.28 11822.28 13271.97
3.00% | 1216.64 2470.28 3762.06 5093.12 6464.67 7877.94 9334.19 10834.74 12380.93 13974.14
4.00% | 1222.25 2494.29 3818.16 5195.96 6629.90 8122.26 9675.42 11291.85 12974.15 14724.98
5.00% | 1227.89 2518.59 3875.33 5301.49 6800.61 8376.43 10032.87 11774.05 13604.32 15528.23
6.00% | 1233.56 2543.20 3933.61 5409.78 6977.00 8640.89 10407.39 12282.85 14273.99 16387.93
7.00% | 1239.26 2568.10 3993.01 5520.92 7159.29 8916.09 10799.90 12819.88 14985.89 17308.48
8.00% | 1244.99 2593.32 4053.56 5634.99 7347.69 9202.53 11211.33 13386.86 15742.95 18294.60
9.00% | 1250.76 2618.85 4115.27 5752.07 7542.41 9500.70 11642.69 13985.62 16548.32 19351.43
10.00% | 1256.56 2644.69 4178.18 5872.25 7743.71 9811.13 12095.04 14618.11 17405.37 20484.50
Detailed Breakdown#
Let’s perform a a deep dive into this code.
monthly_rates_2dhas shape(10, 1)→ 10 different annual rates converted to monthly, arranged as a column vector. Rowi= one specific monthly rate ( i_i ).months_2dhas shape(1, 10)→ 10 different investment horizons in months, arranged as a row vector. Columnj= one specific number of months ( n_j ).
So we have:
growth_factors = (1 + monthly_rates_2d) ** months_2d # shape (10, 10)
fv_factors = (growth_factors - 1) / monthly_rates_2d # shape (10, 10)
sip_amounts = monthly_contribution * fv_factors # shape (10, 10)
Let’s go line by line.
Detailed Breakdown: growth_factors#
growth_factors = (1 + monthly_rates_2d) ** months_2d
Math meaning
For a single monthly rate \((i)\) and a single time horizon \((n)\) (in months), the growth factor of $1 is:
\((1 + i)^n\)
That tells you: “How many dollars do I get after ( \(n\) ) months if I invest $1 today at monthly rate \((i)\)?”
Here, we’re not doing it for just one \((i)\) and one \((n)\); we want all combinations:
10 different rates ( \(i_0, i_1, \dots, i_9\) )
10 different horizons ( \( n_0, n_1, \dots, n_9\) )
So we want a grid where each entry is:
NumPy mechanics
monthly_rates_2dis(10, 1):[[i_0], [i_1], ... [i_9]]
months_2dis(1, 10):[[n_0, n_1, ..., n_9]]
When you write:
(1 + monthly_rates_2d) ** months_2d
NumPy applies broadcasting:
It “stretches” the
(10, 1)array horizontally across 10 columns.It “stretches” the
(1, 10)array vertically across 10 rows.
Conceptually, NumPy is computing:
n_0 n_1 ... n_9
i_0 (1+i_0)^n_0 (1+i_0)^n_1 ... (1+i_0)^n_9
i_1 (1+i_1)^n_0 (1+i_1)^n_1 ... (1+i_1)^n_9
...
i_9 (1+i_9)^n_0 (1+i_9)^n_1 ... (1+i_9)^n_9
The result is a (10, 10) array: 10 rates × 10 horizons.
If you wrote this with loops, it would be like:
growth_factors = np.empty((10, 10))
for i in range(10): # loop over rates
for j in range(10): # loop over horizons
growth_factors[i, j] = (1 + monthly_rates[i]) ** months[j]
NumPy just compresses those two loops into one broadcasting expression.
Detailed Breakdown: fv_factors#
fv_factors = (growth_factors - 1) / monthly_rates_2d
This line applies the future value of an annuity formula element-wise.
For a given monthly rate ( \(i\) ) and ( \(n\) ) monthly deposits of $1 at the end of each month, the future value factor is:
\( \text{FV factor}(i, n) = \frac{(1 + i)^n - 1}{i} \)
This is a dimensionless multiplier: if you contribute ( \(C\) ) each month instead of 1, the future value is:
\( \text{FV} = C \cdot \text{FV factor}(i, n) \)
How the code matches the math
Look at:
fv_factors = (growth_factors - 1) / monthly_rates_2d
growth_factorsis the(1 + i)^ngrid from the previous step.So
(growth_factors - 1)is a grid of(1 + i)^n - 1.monthly_rates_2dis a(10, 1)column of monthly rates ( i_i ).
Again, broadcasting kicks in when you divide a (10, 10) array by a (10, 1) array:
For row
i, every columnjis divided by the same ratemonthly_rates_2d[i, 0] = i_i.
So entry-wise:
\( \text{FV factors}[i, j] = \frac{(1 + i_i)^{n_j} - 1}{i_i} \)
That’s exactly the FV factor formula for “\(1 deposited every month for ( \)n_j\( ) months at rate ( \)i_i$ ).”
Loop version:
fv_factors = np.empty((10, 10))
for i in range(10):
for j in range(10):
i_rate = monthly_rates[i]
n_month = months[j]
fv_factors[i, j] = ((1 + i_rate)**n_month - 1) / i_rate
NumPy version = same math, but in one vectorized line.
Detailed Breakdown: sip_amounts#
sip_amounts = monthly_contribution * fv_factors
Now we just scale the FV factors by the actual monthly contribution amount.
If the FV factor gives the future value of $1 per month, then for a monthly contribution ( C ) you just multiply:
\( \text{FV}(i, n) = C \cdot \text{FV factor}(i, n) \)
The code:
sip_amounts = monthly_contribution * fv_factors
does exactly that, element-wise, across the entire (10, 10) grid.
monthly_contributionis just a scalar (e.g., 100).fv_factorsis the(10, 10)array.Multiplying a scalar by an array scales every entry:
\( \text{sip amounts}[i, j] = C \cdot \text{fv factors}[i, j] =C \cdot \frac{(1 + i_i)^{n_j} - 1}{i_i} \)
That gives you:
“Future value after
n_jmonths, investing $C per month, at monthly ratei_i.”
Again, the explicit loop version would be:
sip_amounts = np.empty((10, 10))
for i in range(10):
for j in range(10):
sip_amounts[i, j] = monthly_contribution * fv_factors[i, j]
NumPy’s broadcasting makes this a single, very readable line.
Summary#
Compute all growth factors at once
growth_factors = (1 + monthly_rates_2d) ** months_2d→ build a 10×10 grid where each cell is “how much $1 grows if you invest it today and leave it for n months at rate r.”Turn growth into an annuity factor
fv_factors = (growth_factors - 1) / monthly_rates_2d→ convert those growth factors into the standard future value multiplier for a stream of monthly contributions of $1.Scale by the actual contribution
sip_amounts = monthly_contribution * fv_factors→ multiply every cell by $100 to get real balances.
This is the “real work” because it’s where both:
the financial formula (future value of an annuity), and
the NumPy broadcasting logic (all rate–year combinations at once)
come together. Everything else in the script is just setup and pretty-printing.
Stock Analysis#
We’ll use the AdjustedCloseMatrix matrix presented in the
NumPy stock load notebook. You can adjust the
lookback_days to bring in more or less data as need. This is computed
from today.
Instances of the AdjustedCloseMatrix have three primary properties:
prices(NumPy array of floats, symbols are rows, columns are dates ordered sequentially)dates(NumPy array of timestamps)symbols(NumPy array of ticker strings).
1from finance import AdjustedCloseMatrix
2
3# Load sample data
4matrix = AdjustedCloseMatrix(lookback_days=365)
5matrix.load_from_csv("../StockData/stocks")
6print("Shape:", matrix.prices.shape)
7print("First Date:", matrix.dates[0])
8print("Last Date:", matrix.dates[-1])
9print("Available Symbols:", matrix.get_available_symbols())
10print("matrix.prices type:", type(matrix.prices.dtype))
11print("matrix.dates type:", type(matrix.dates.dtype))
12print("matrix.symbols type:", type(matrix.symbols.dtype))
Shape: (30, 365)
First Date: 2024-06-07T00:00:00.000000000
Last Date: 2025-11-19T00:00:00.000000000
Available Symbols: ['AAPL', 'AMGN', 'AXP', 'BA', 'CAT', 'CRM', 'CSCO', 'CVX', 'DIS', 'GS', 'HD', 'HON', 'IBM', 'JNJ', 'JPM', 'KO', 'MCD', 'MMM', 'MRK', 'MSFT', 'NKE', 'PG', 'TRV', 'UNH', 'V', 'VZ', 'WMT', 'AMZN', 'NVDA', 'SHW']
matrix.prices type: <class 'numpy.dtypes.Float64DType'>
matrix.dates type: <class 'numpy.dtypes.DateTime64DType'>
matrix.symbols type: <class 'numpy.dtypes.ObjectDType'>
To make our examples smaller in order to see the values involved, we’ll limit to just 5 stocks and 10 days of prices.
1matrix = AdjustedCloseMatrix(symbols=["AAPL", "MSFT", "GOOGL", "AMZN", "NVDA"], lookback_days=10)
2matrix.load_from_csv("../StockData/stocks")
3print("Shape:", matrix.prices.shape)
Shape: (5, 10)
Rates of Return#
The calculate a stock’s rate of return, we subtract the initial investment value from the final value and divide by the initial value.
\( rate of return = \frac{Final Value - Initial Value}{Initial Value}\)
Numpy provides the diff method to calculate the differences between successive
elements in an array. The size of the resulting array will be n-1. diff provides us \(Final Value - Initial Value\). We’ll then need to divde
by the initial values, which we can get by slicing and taking away the last final value.
We’ll first show this example for a single stock and then expand to all stocks in our matrix.
1# Print stock prices for AAPL:
2aapl_prices = matrix.prices[matrix.symbol_to_row["AAPL"],:]
3print(aapl_prices)
4
5# compute daily returns AAPL:
6returns = np.diff(aapl_prices) / aapl_prices[:-1]
7print(returns)
[269.5099 268.2112 269.43 275.25 273.47 272.95 272.41 267.46 267.44 268.56 ]
[-0.0048 0.0045 0.0216 -0.0065 -0.0019 -0.002 -0.0182 -0.0001 0.0042]
1all_returns = np.diff(matrix.prices) / matrix.prices[:, :-1]
2print(all_returns)
[[-0.0048 0.0045 0.0216 -0.0065 -0.0019 -0.002 -0.0182 -0.0001 0.0042]
[-0.0006 0.0185 0.0053 0.0048 -0.0154 0.0137 -0.0053 -0.027 -0.0135]
[-0.0208 0.0404 0.0042 -0.0158 -0.0284 -0.0078 0.0311 -0.0026 0.03 ]
[ 0.0056 0.0163 0.0028 -0.0197 -0.0271 -0.0122 -0.0078 -0.0443 0.0006]
[ 0.0004 0.0579 -0.0296 0.0033 -0.0358 0.0177 -0.0188 -0.0281 0.0285]]
As alternative, we could also compute this as
\( rate of return = \frac{Final Value - Initial Value}{Initial Value} = \frac{Final Value }{Initial Value} - 1\)
So we’ll remove the first value to get the “final value” and then ignore the last value to get the “initial value” when dividing. Notice how this code uses slicing:
grab all rows
[:, *columns*]for the numerator, drop the first value to get the future values
for the denominator, drop the last value to the initial values
Since the resulting matrices have the same dimensions, we can simply divide them - this results in performing an element by element division in the same location.
Then we use broadcasting to substract 1 from every element.
1alternate = matrix.prices[:, 1:] / matrix.prices[:, :-1] - 1.0 # (n_symbols, n_dates-1)
2print(alternate)
[[-0.0048 0.0045 0.0216 -0.0065 -0.0019 -0.002 -0.0182 -0.0001 0.0042]
[-0.0006 0.0185 0.0053 0.0048 -0.0154 0.0137 -0.0053 -0.027 -0.0135]
[-0.0208 0.0404 0.0042 -0.0158 -0.0284 -0.0078 0.0311 -0.0026 0.03 ]
[ 0.0056 0.0163 0.0028 -0.0197 -0.0271 -0.0122 -0.0078 -0.0443 0.0006]
[ 0.0004 0.0579 -0.0296 0.0033 -0.0358 0.0177 -0.0188 -0.0281 0.0285]]
Statistics#
Using Numpy’s universal functions, we can quickly analyze the returns to generate descriptive statistics.
1mean_daily_return = np.mean(all_returns, axis=1) # (n_symbols,)
2median_daily_return = np.median(all_returns, axis=1) # (n_symbols,)
3
4# Volatility (std dev). Use ddof=1 for sample standard deviation
5std_daily_return = np.std(all_returns, axis=1, ddof=1) # (n_symbols,)
6
7# Extremes
8max_daily_return = np.max(all_returns, axis=1) # (n_symbols,)
9min_daily_return = np.min(all_returns, axis=1) # (n_symbols,)
10
11for sym, mean_r, median_r, std_r, max_r, min_r in zip(matrix.symbols, mean_daily_return, median_daily_return, std_daily_return, max_daily_return, min_daily_return):
12 print(f"{sym}: mean={mean_r:.6f}, median={median_r:.6f}, std={std_r:.6f}, max={max_r:.6f}, min={min_r:.6f}")
13
14# Find stock with highest standard deviation
15highest_std_idx = np.argmax(std_daily_return)
16highest_std_symbol = matrix.symbols[highest_std_idx]
17highest_std_value = std_daily_return[highest_std_idx]
18
19print(f"\nStock with highest standard deviation: {highest_std_symbol} (std={highest_std_value:.6f})")
AAPL: mean=-0.000342, median=-0.001901, std=0.010645, max=0.021601, min=-0.018171
MSFT: mean=-0.002155, median=-0.000563, std=0.014636, max=0.018478, min=-0.026996
GOOGL: mean=0.003380, median=-0.002596, std=0.024933, max=0.040419, min=-0.028391
AMZN: mean=-0.009512, median=-0.007755, std=0.018662, max=0.016325, min=-0.044317
NVDA: mean=-0.000497, median=0.000372, std=0.031200, max=0.057933, min=-0.035810
Stock with highest standard deviation: NVDA (std=0.031200)
1# Stock returns
2prices = np.array([100, 102, 98, 105, 103, 108])
3returns = np.divide(np.diff(prices), prices[:-1])
4
5# Moving average using ufunc methods
6window = 3
7moving_avg = np.convolve(prices, np.ones(window)/window, mode='valid')
8
9# Compound returns
10cumulative_returns = np.multiply.accumulate(1 + returns)
11print(f"Returns: {returns}")
12print(f"Cumulative returns: {cumulative_returns}")
13print(f"Moving average (window={window}): {moving_avg}")
Returns: [ 0.02 -0.0392 0.0714 -0.019 0.0485]
Cumulative returns: [1.02 0.98 1.05 1.03 1.08]
Moving average (window=3): [100. 101.6667 102. 105.3333]
Log Returns#
So far we have used simple (arithmetic) returns, defined as:
\( R_t = \frac{P_t - P_{t-1}}{P_{t-1}} \)
A log return instead uses the natural logarithm:
\( r_t = \ln\left(\frac{P_t}{P_{t-1}}\right) = \ln(1 + R_t) \)
Log returns measure the continuously-compounded growth rate of the price.
Why Use Log Returns?#
Log returns have several mathematical properties that make them extremely convenient for modeling:
Multi-Period Additivity#
Simple returns multiply across time: \( (1+R_1)(1+R_2)\cdots(1+R_T) - 1 \)
Log returns add: \( r_1 + r_2 + \cdots + r_T = \ln\left(\frac{P_T}{P_0}\right) \)
This means that cumulative performance over time is just a sum, which is easier to analyze statistically.
Approximate Normality#
For daily/weekly horizons, log returns often look more symmetric and closer to a normal distribution than simple returns. This is extremely useful because many quantitative models assume normality or use maximum likelihood methods built on that assumption.
Ensures Prices Stay Positive#
Modeling log returns avoids the possibility that a naïvely simulated price becomes negative.
Then Why Aren’t Log Returns Used with Retail Investors?#
Investor communication (brokerage statements, fund fact sheets, performance reports) almost always uses simple returns, not log returns.
Reasons:
Simple returns are more intuitive (“The stock went up 5% today”).
Compounded growth over multiple periods still uses simple returns in practice: “Your portfolio returned 12% last year.”
Log returns can be misleading for large moves (e.g., −50% followed by +50% gives a log gain but no capital recovery).
Non-technical audiences prefer direct percentage gains/losses.
In short: Quants use log returns for modeling convenience. Investors use simple returns for interpretability.
Motivating Example: The Power of Additivity#
Suppose a stock goes through the following price path:
Day |
Price |
|---|---|
0 |
100 |
1 |
110 |
2 |
105 |
Let’s compare simple vs log returns.
Simple Returns#
Day 1: \( R_1 = \frac{110-100}{100} = 0.10 \)
Day 2: \( R_2 = \frac{105-110}{110} \approx -0.04545 \)
Cumulative simple return: \( (1+R_1)(1+R_2) -1 = 1.10 \cdot 0.954545 - 1 = 0.050 \)
So the portfolio gained 5% total.
Log Returns#
\( r_1 = \ln(110/100) = \ln(1.10) \approx 0.09531 \)
\( r_2 = \ln(105/110) = \ln(0.954545) \approx -0.04652 \)
Add log returns:
\( r_1 + r_2 = 0.04879 \)
Exponentiate to get cumulative effect:
\( e^{,0.04879} - 1 = 0.0500 \)
We get the same 5% total return, but log returns achieved this through addition, not multiplication.
Why this matters#
For a time series of thousands of daily returns, it is far easier to compute:
cumulative_log = np.cumsum(log_returns)
than to multiply many terms. Additivity also simplifies mathematical modeling and statistical analysis.
NumPy Example#
1# 1. Simple returns along the time axis (axis=1)
2# shape: (n_stocks, n_days - 1)
3simple_returns = np.diff(matrix.prices, axis=1) / matrix.prices[:, :-1]
4
5# 2. Log returns along the time axis
6log_returns = np.log(matrix.prices[:, 1:] / matrix.prices[:, :-1])
7
8print("Price matrix:\n", matrix.prices)
9print("\nSimple returns:\n", simple_returns)
10print("\nLog returns:\n", log_returns)
11
12
13
14# 3. Cumulative simple and log returns for a single stock (e.g., first row)
15stock_idx = 3 # pick a stock
16simple_r = simple_returns[stock_idx]
17log_r = log_returns[stock_idx]
18
19cum_simple = np.prod(1 + simple_r) - 1
20cum_log = np.exp(np.sum(log_r)) - 1
21
22print(f"\nStock {matrix.symbols[stock_idx]} cumulative simple return: {cum_simple:.4f}")
23print(f"Stock {matrix.symbols[stock_idx]} cumulative log return: {cum_log:.4f}")
Price matrix:
[[269.5099 268.2112 269.43 275.25 273.47 272.95 272.41 267.46 267.44 268.56 ]
[497.1 496.82 506. 508.68 511.14 503.29 510.18 507.49 493.79 487.12 ]
[284.75 278.83 290.1 291.31 286.71 278.57 276.41 285.02 284.28 292.81 ]
[243.04 244.41 248.4 249.1 244.2 237.58 234.69 232.87 222.55 222.69 ]
[188.08 188.15 199.05 193.16 193.8 186.86 190.17 186.6 181.36 186.52 ]]
Simple returns:
[[-0.0048 0.0045 0.0216 -0.0065 -0.0019 -0.002 -0.0182 -0.0001 0.0042]
[-0.0006 0.0185 0.0053 0.0048 -0.0154 0.0137 -0.0053 -0.027 -0.0135]
[-0.0208 0.0404 0.0042 -0.0158 -0.0284 -0.0078 0.0311 -0.0026 0.03 ]
[ 0.0056 0.0163 0.0028 -0.0197 -0.0271 -0.0122 -0.0078 -0.0443 0.0006]
[ 0.0004 0.0579 -0.0296 0.0033 -0.0358 0.0177 -0.0188 -0.0281 0.0285]]
Log returns:
[[-0.0048 0.0045 0.0214 -0.0065 -0.0019 -0.002 -0.0183 -0.0001 0.0042]
[-0.0006 0.0183 0.0053 0.0048 -0.0155 0.0136 -0.0053 -0.0274 -0.0136]
[-0.021 0.0396 0.0042 -0.0159 -0.0288 -0.0078 0.0307 -0.0026 0.0296]
[ 0.0056 0.0162 0.0028 -0.0199 -0.0275 -0.0122 -0.0078 -0.0453 0.0006]
[ 0.0004 0.0563 -0.03 0.0033 -0.0365 0.0176 -0.019 -0.0285 0.0281]]
Stock AMZN cumulative simple return: -0.0837
Stock AMZN cumulative log return: -0.0837
Covariance and Correlation#
From a finance perspective, covariance is a statistical measure that tells you how the returns of two different stocks move in relation to each other. It quantifies the directional relationship between two assets.
If they move together (both go up or both go down), covariance is positive.
If they move oppositely (one goes up, the other goes down), covariance is negative.
Investors use this primarily to build diversified portfolios. By combining assets with negative covariance, you can lower the overall risk of your portfolio.
The Covariance Formula#
In finance, we typically use the Sample Covariance formula because we are analyzing a sample of historical data (e.g., the last 12 months of returns).
Variable Explanation#
Here is what each variable represents in the context of analyzing two stocks, Stock X and Stock Y:
\(Cov(X, Y)\): The covariance between Stock X and Stock Y.
\(R_{x,i}\): The return of Stock X in a specific period \(i\) (e.g., the return of Apple in January or a particular date).
\(\bar{R}_x\) (read as “R-bar”): The average (mean) return of Stock X over the entire timeframe analyzed.
\(R_{y,i}\): The return of Stock Y in the same specific period \(i\) (e.g., the return of Exxon in January).
\(\bar{R}_y\): The average (mean) return of Stock Y over the entire timeframe.
\(n\): The number of observations (e.g., if you look at monthly returns over one year, \(n = 12\)).
\(\sum\): The Greek letter Sigma, representing the “sum.” It means you calculate the calculation for every single period and add them all together.
How to Interpret the Results#
When you calculate this number, the magnitude (how big the number is) matters less than the sign (positive or negative).
1. Positive Covariance (\(> 0\))#
The two stocks tend to move in the same direction.
Example: Google and Microsoft. When the tech sector is doing well, both usually rise. When the sector is hit, both usually fall.
Risk: Holding two stocks with high positive covariance does not provide much diversification.
2. Negative Covariance (\(< 0\))#
The two stocks tend to move in opposite directions.
Example: Airline Stocks vs. Oil Stocks. Often, when oil prices rise, oil stocks go up, but airline stocks go down (because their fuel costs increase).
Risk: This is the “Holy Grail” of diversification. Losses in one stock are offset by gains in the other, smoothing out your portfolio’s volatility.
3. Zero Covariance (\(\approx 0\))#
There is no predictable relationship between the two stocks. They move independently.
Example: A pharmaceutical company vs. a casual dining chain. The success of a new drug trial usually has no impact on how many people buy burgers.
A Critical Note on “Scale”#
The main weakness of covariance is that the number isn’t standardized. If Stock A moves $100 and Stock B moves $100, the covariance will be a huge number. If they move $0.01, it will be tiny, even if the relationship is exactly the same.
Because of this, analysts often convert covariance into Correlation, which standardizes the measure between -1 and +1, making it easier to compare different pairs of stocks, regardless of their price or volatility..
Correlation Formula#
To get the Correlation Coefficient (often denoted by the Greek letter Rho, \(\rho\), or simply \(r\)), you divide the covariance by the product of the standard deviations of both stocks.
Variable Explanation#
\(Cov(X, Y)\): The Covariance you just calculated. This represents the direction of the relationship (positive or negative) and a non-standardized magnitude.
\(\sigma_x\) (Sigma X): The Standard Deviation of Stock X. This measures the standalone volatility (risk) of Stock X.
\(\sigma_y\) (Sigma Y): The Standard Deviation of Stock Y. This measures the standalone volatility (risk) of Stock Y.
Why We Divide by Standard Deviation#
Think of the standard deviation as the “total possible movement” for each stock. By dividing the Covariance by the Standard Deviations, you are asking:
“Of all the movement these stocks experienced, how much of it was shared movement?”
If the result is +1: 100% of their volatility is shared and directional (they are practically the same asset).
If the result is 0: 0% of their movement is shared (complete independence).
NumPy Code for Covariance and Correlation#
NumPy provides a cov method to calculate the covariance matrix
as well as the corrcoef method to calculate the correlation matrix.
1returns = np.diff(matrix.prices) / matrix.prices[:, :-1]
2
3# 1. Calculate Covariance Matrix
4# Note: 'rowvar=True' is the default, so we don't strictly need to specify it.
5# if the rows represented dates and columns represented stocks, we would set rowvar=False.
6cov_matrix = np.cov(returns)
7
8# 2. Calculate Correlation Matrix
9corr_matrix = np.corrcoef(returns)
10
11print("Covariance Matrix:\n", cov_matrix)
12print("\nCorrelation Matrix:\n", corr_matrix)
Covariance Matrix:
[[0.0001 0. 0. 0.0001 0. ]
[0. 0.0002 0.0001 0.0002 0.0003]
[0. 0.0001 0.0006 0.0002 0.0004]
[0.0001 0.0002 0.0002 0.0003 0.0004]
[0. 0.0003 0.0004 0.0004 0.001 ]]
Correlation Matrix:
[[1. 0.1657 0.0545 0.2695 0.0357]
[0.1657 1. 0.2056 0.6921 0.5982]
[0.0545 0.2056 1. 0.5133 0.5454]
[0.2695 0.6921 0.5133 1. 0.6269]
[0.0357 0.5982 0.5454 0.6269 1. ]]
1# Note, we can manually compute the covariance matrix step-by-step:
2# 1. Get the number of date(period) observations
3N = returns.shape[1]
4
5# 2. Calculate Means
6# We calculate the mean across axis 1 (the dates).
7# keepdims=True ensures the shape remains (3,1) instead of (3,),
8# which allows for correct broadcasting in the next step.
9means = np.mean(returns, axis=1, keepdims=True)
10
11# 3. Center the Data (X - X_bar)
12# Subtracting the mean removes the scale, leaving only the "movement"
13centered_data = returns - means
14
15# 4. Compute Covariance (Matrix Multiplication)
16# We perform a dot product of the centered matrix and its transpose.
17# (Stocks x Dates) @ (Dates x Stocks) = (Stocks x Stocks)
18# We divide by (N - 1) for Sample Covariance (standard in finance).
19cov_matrix_manual = (centered_data @ centered_data.T) / (N - 1)
20
21print("Manual Calculation:\n", cov_matrix_manual)
22
23# Similarly, we can manually compute the correlation matrix step-by-step:
24# 1. Compute Standard Deviations
25std_devs = np.std(returns, axis=1, ddof=1, keepdims=True) # (n_stocks, 1)
26# Alternatively, compute from covariance matrix
27variances = np.diag(cov_matrix_manual) # note that the diagonal of covariance matrix contains variances
28std_devs_alt = np.sqrt(variances).reshape(-1, 1) # (n_stocks, 1)
29
30print("Standard Deviations:\n", std_devs)
31print("Standard Deviations:\n", std_devs_alt)
32
33# 2. Compute Outer Product of Standard Deviations - Denominator Matrix (Sigma_i * Sigma_j)
34stddev_outer = std_devs @ std_devs.T # (n_stocks, n_stocks)
35
36# 3. Correlation Matrix
37corr_matrix_manual = cov_matrix_manual / stddev_outer # (n_stocks, n_stocks)
38print("Manual Correlation Calculation:\n", corr_matrix_manual)
Manual Calculation:
[[0.0001 0. 0. 0.0001 0. ]
[0. 0.0002 0.0001 0.0002 0.0003]
[0. 0.0001 0.0006 0.0002 0.0004]
[0.0001 0.0002 0.0002 0.0003 0.0004]
[0. 0.0003 0.0004 0.0004 0.001 ]]
Standard Deviations:
[[0.0106]
[0.0146]
[0.0249]
[0.0187]
[0.0312]]
Standard Deviations:
[[0.0106]
[0.0146]
[0.0249]
[0.0187]
[0.0312]]
Manual Correlation Calculation:
[[1. 0.1657 0.0545 0.2695 0.0357]
[0.1657 1. 0.2056 0.6921 0.5982]
[0.0545 0.2056 1. 0.5133 0.5454]
[0.2695 0.6921 0.5133 1. 0.6269]
[0.0357 0.5982 0.5454 0.6269 1. ]]
Portfolio Returns and Risk#
So far, we have:
A matrix of daily returns,
returns, with shape(n_stocks, n_days-1).The covariance matrix of returns,
cov_matrix, from the previous section.
Now we’ll combine these to analyze portfolios—weighted combinations of stocks.
Portfolio Return and Volatility: Math Recap#
Let:
\(\mu\) = vector of expected returns for each stock (length (n)).
\(\Sigma\) = covariance matrix of returns (shape (n \times n)).
\(w\)= vector of portfolio weights (length (n)), where \(\sum_i w_i = 1\).
Then:
Expected portfolio return: \( \mu_p = w^\top \mu \)
Portfolio variance: \( \sigma_p^2 = w^\top \Sigma w \)
Portfolio volatility (standard deviation): \(\sigma_p = \sqrt{w^\top \Sigma w} \)
We’ll implement these formulas using NumPy.
Step 1: Estimate Expected Returns and Covariance#
We’ll work with daily returns and later scale if needed.
1# returns: shape (n_stocks, n_days-1)
2# rows = stocks, columns = days
3
4# 1. Mean daily return for each stock (length n_stocks)
5mu_daily = np.mean(returns, axis=1) # axis=1 averages across time
6
7# 2. Covariance matrix of daily returns (n_stocks x n_stocks)
8cov_matrix = np.cov(returns)
If you want annualized numbers (assuming 252 trading days per year):
trading_days = 252
mu_annual = mu_daily * trading_days
cov_annual = cov_matrix * trading_days
For the rest of this section, we’ll stick to daily numbers, but you can swap in the annualized ones as needed.
Step 2: Portfolio Return and Volatility for a Given Weight Vector#
We can now write a small helper function.
1def portfolio_stats(weights, mu, cov):
2 """
3 Compute portfolio expected return and volatility.
4
5 weights: 1D array of shape (n_stocks,)
6 mu: 1D array of expected returns (n_stocks,)
7 cov: 2D covariance matrix (n_stocks x n_stocks)
8 """
9 # Ensure arrays
10 w = np.asarray(weights)
11 mu = np.asarray(mu)
12 cov = np.asarray(cov)
13
14 # Expected return
15 port_return = w @ mu
16
17 # Variance and volatility
18 port_var = w @ cov @ w
19 port_vol = np.sqrt(port_var)
20
21 return port_return, port_vol
22
23# Example: equal-weight portfolio
24n_stocks = returns.shape[0]
25weights_equal = np.ones(n_stocks) / n_stocks
26
27p_ret_daily, p_vol_daily = portfolio_stats(weights_equal, mu_daily, cov_matrix)
28
29print("Equal-weight portfolio expected daily return:", p_ret_daily)
30print("Equal-weight portfolio daily volatility:", p_vol_daily)
Equal-weight portfolio expected daily return: -0.0018251230235838125
Equal-weight portfolio daily volatility: 0.014983861623311404
This uses the @ operator for matrix multiplication:
w @ mu→ inner productw @ cov @ w→ quadratic form \( w^\top \Sigma w \)
Step 3: Exploring Many Portfolios (Random Weights)#
To see diversification in action, we can simulate many random portfolios and compare their risk and return.
1# Number of random portfolios
2n_portfolios = 5000
3
4all_weights = []
5port_returns = []
6port_vols = []
7
8for _ in range(n_portfolios):
9 # Random non-negative weights that sum to 1
10 weights = np.random.rand(n_stocks)
11 weights = weights / np.sum(weights)
12
13 r, v = portfolio_stats(weights, mu_daily, cov_matrix)
14
15 all_weights.append(weights)
16 port_returns.append(r)
17 port_vols.append(v)
18
19port_returns = np.array(port_returns)
20port_vols = np.array(port_vols)
21all_weights = np.array(all_weights)
22
23print("Simulated", n_portfolios, "portfolios.")
Simulated 5000 portfolios.
At this point, you can:
Plot
port_volson the x-axis (risk)Plot
port_returnson the y-axis (expected return)
to see a cloud of portfolios. The upper-left “edge” of this cloud is an approximation to the efficient frontier.
1import matplotlib.pyplot as plt
2import seaborn as sns
3
4
5plt.figure(figsize=(8, 6), layout='constrained')
6sns.scatterplot(x=port_vols, y=port_returns, s=10, alpha=0.6)
7plt.xlabel("Portfolio Volatility (Risk)")
8plt.ylabel("Expected Portfolio Return")
9plt.title("Simulated Portfolio Risk–Return Tradeoff (Daily)")
10plt.show()
Note: You’ll probably just see a cloud of data see when only loaded 10 trading days. Re-run this code by using a year, 5 years, or 10 years of data instead.
Rolling Statistics and Volatility#
Financial time series are not stationary—their statistical properties change over time. A stock might be calm for months and then suddenly volatile. To visualize and quantify this, we often compute rolling (moving-window) statistics such as:
rolling mean
rolling volatility (standard deviation)
rolling correlation between two stocks
In this section, we compute rolling metrics using pure NumPy.
Rolling Windows Using NumPy#
We’ll use np.lib.stride_tricks.sliding_window_view to create an efficient rolling window over the matrix of returns.
Assume:
returnsis our(n_stocks, n_days-1)matrix of daily returns.
Let’s compute 20-day rolling volatility for each stock.
1matrix = AdjustedCloseMatrix(symbols=["AAPL", "MSFT", "GOOGL", "AMZN", "NVDA"], lookback_days=252*10)
2matrix.load_from_csv("../StockData/stocks")
3returns = np.diff(matrix.prices) / matrix.prices[:, :-1]
4
5
6from numpy.lib.stride_tricks import sliding_window_view
7
8# returns: shape (n_stocks, n_days-1)
9window = 20
10
11# sliding_window_view creates a view of shape:
12# (n_stocks, n_days-1 - window + 1, window)
13roll_windows = sliding_window_view(returns, window_shape=window, axis=1)
14
15print("Rolling windows shape:", roll_windows.shape)
16# -> (n_stocks, num_rolling_points, window)
Rolling windows shape: (5, 2500, 20)
Now compute rolling volatility:
1# Rolling mean and std across the window axis (axis=2)
2roll_mean = np.mean(roll_windows, axis=2)
3roll_vol = np.std(roll_windows, axis=2)
4
5print("Rolling volatility shape:", roll_vol.shape)
Rolling volatility shape: (5, 2500)
roll_mean[i]is the 20-day rolling mean return for stockiroll_vol[i]is the 20-day rolling volatility for stocki
These arrays are shorter along the time dimension because the first window - 1 days don’t have enough history.
Example: Plot 20-Day Rolling Volatility for One Stock#
1stock_idx = 1 # pick a stock
2dates_roll = matrix.dates[window:] # align dates
3
4sns.set_theme(style="whitegrid")
5plt.figure(figsize=(10, 5), layout='constrained')
6sns.lineplot(
7 x=dates_roll,
8 y=roll_vol[stock_idx],
9)
10plt.ylabel("20-day rolling volatility")
11plt.xlabel("Date")
12plt.title(f"{matrix.symbols[stock_idx]}: 20-day Rolling Volatility")
13plt.show()
Rolling Correlation Between Two Stocks#
Let’s compute 30-day rolling correlation between stock AAPL and MSFT (indices i and j).
1i, j = 0, 1 # two stocks to compare
2window = 30
3
4roll_i = sliding_window_view(returns[i], window_shape=window)
5roll_j = sliding_window_view(returns[j], window_shape=window)
6
7# Compute rolling correlation
8# corr = cov / (std_i * std_j)
9roll_cov = np.mean( (roll_i - roll_i.mean(axis=1, keepdims=True)) *
10 (roll_j - roll_j.mean(axis=1, keepdims=True)),
11 axis=1)
12
13roll_std_i = roll_i.std(axis=1)
14roll_std_j = roll_j.std(axis=1)
15
16roll_corr = roll_cov / (roll_std_i * roll_std_j)
1# Now plot the rolling correlation
2sns.set_theme(style="whitegrid")
3
4# Align dates: one date per rolling window
5dates_roll_corr = matrix.dates[1:][window-1:] # same alignment idea as above
6
7plt.figure(figsize=(10, 5), layout='constrained')
8sns.lineplot(
9 x=dates_roll_corr,
10 y=roll_corr,
11)
12plt.title(f"Rolling 30-day Correlation: {matrix.symbols[i]} vs {matrix.symbols[j]}")
13plt.xlabel("Date")
14plt.ylabel("Correlation")
15plt.show()
Why Rolling Statistics Matter#
Rolling measures help you:
Identify volatility regimes (calm vs turbulent markets).
Spot changes in co-movement between assets.
Build risk-aware strategies (dynamic asset allocation).
Understand why the covariance matrix used in portfolio optimization may need to be updated frequently in practice.
Drawdowns and Maximum Drawdown#
So far we have focused on volatility as a measure of risk. Investors, however, care a lot about how much money they can lose from a peak before recovering.
This is captured by drawdowns:
A drawdown at time ( t ) is the percentage drop from the previous peak value.
The maximum drawdown (MDD) is the worst such drop over the whole period.
Drawdowns are useful because they answer questions like:
“What was the largest peak-to-trough loss I would have had to sit through to earn this return?”
From Returns to Wealth Index#
We’ll work with a single stock (or portfolio) at a time.
Assume:
returnshas shape(n_stocks, n_days-1)(daily simple returns)datesis aligned with the price or return seriessymbolsholds ticker names aligned with rows
For stock i, define its wealth index (cumulative growth of $1):
\(\text{Wealth}_t = \prod_{k=1}^{t} (1 + R_k) \)
Then:
Running peak:
running_max_t = max_{s ≤ t} Wealth_sDrawdown: \( \text{DD}_t = \frac{\text{Wealth}_t}{\text{running max}_t} - 1 \)
Compute Drawdowns with NumPy#
1# Pick a stock
2stock_idx = 0
3
4# Daily simple returns for this stock: shape (n_days-1,)
5r = returns[stock_idx]
6
7# 1. Wealth index (start at 1.0)
8wealth = np.cumprod(1 + r)
9
10# 2. Running maximum of wealth
11running_max = np.maximum.accumulate(wealth)
12
13# 3. Drawdown series
14drawdown = wealth / running_max - 1
15
16# 4. Maximum drawdown
17max_drawdown = drawdown.min() # should be a negative number
18
19print(f"Stock: {matrix.symbols[stock_idx]}")
20print(f"Maximum drawdown: {max_drawdown:.2%}")
Stock: AAPL
Maximum drawdown: -38.52%
max_drawdown is the worst percentage loss from a peak to a subsequent trough over the sample.
Aligning Dates#
If returns is derived from prices with shape (n_stocks, n_days), then:
returnshas lengthn_days - 1along time.You can align the drawdown with
dates[1:].
1dates_ret = matrix.dates[1:] # match the returns and wealth index length
Visualizing Drawdown with seaborn#
We’ll plot both the wealth index and the drawdown series for one stock.
1import matplotlib.pyplot as plt
2import seaborn as sns
3
4sns.set_theme(style="whitegrid")
5
6dates_ret = matrix.dates[1:]
7
8fig, axes = plt.subplots(2, 1, figsize=(10, 8), sharex=True, layout='constrained')
9
10# 1. Wealth index
11sns.lineplot(
12 x=dates_ret,
13 y=wealth,
14 ax=axes[0],
15)
16axes[0].set_ylabel("Wealth (starting at 1.0)")
17axes[0].set_title(f"{matrix.symbols[stock_idx]}: Wealth Index")
18
19# 2. Drawdown (as negative percentages)
20sns.lineplot(
21 x=dates_ret,
22 y=drawdown,
23 ax=axes[1],
24)
25axes[1].set_ylabel("Drawdown")
26axes[1].set_xlabel("Date")
27axes[1].set_title(f"{matrix.symbols[stock_idx]}: Drawdown (from peak)")
28
29# Emphasize the maximum drawdown point
30dd_min_idx = np.argmin(drawdown)
31axes[1].scatter(
32 [dates_ret[dd_min_idx]],
33 [drawdown[dd_min_idx]],
34)
35axes[1].annotate(
36 f"Max DD: {max_drawdown:.2%}",
37 xy=(dates_ret[dd_min_idx], drawdown[dd_min_idx]),
38 xytext=(10, -20),
39 textcoords="offset points",
40 arrowprops=dict(arrowstyle="->"),
41)
42
43plt.show()
This gives a nice two-panel figure:
Top: how $1 grows over time.
Bottom: how far below the previous peak you are at each date, with the maximum drawdown clearly marked.
Interpreting Maximum Drawdown#
Suppose we see:
Maximum drawdown: -35.00%
That means:
At some point, the investor would have seen their wealth fall 35% below the previous high before (possibly) recovering.
Two portfolios with the same average return but different max drawdowns can feel very different to an investor:
A smoother ride (small MDD)
vs. a roller coaster (large MDD)
Drawdown is therefore a complement to volatility:
Volatility measures “wiggliness” around the mean.
Drawdown measures “how bad it gets” relative to highs.
Annualizing Returns and Volatility#
Up to now we’ve mostly worked with daily returns and volatility. In practice, people often quote performance and risk on an annual basis:
“Expected annual return of 8%”
“Annualized volatility of 20%”
Assuming there are \(N\) trading days in a year (often \(N = 252\)), we can convert daily statistics to annual ones.
From Daily Simple Returns to Annualized Mean and Volatility#
Let:
\( R_t \) = simple return on day \(t\)
\( \mu_d = \mathbb{E}[R_t] \) = mean daily return
\( \sigma_d = \sqrt{\mathbb{V}[R_t]} \) = daily standard deviation
Under a simple independent and identically distributed (i.i.d.) assumption:
Annualized mean (approximation): \( \mu_{\text{ann}} \approx N \cdot \mu_d \)
Annualized volatility: \( \sigma_{\text{ann}} = \sqrt{N} \cdot \sigma_d \)
This is often good enough for many applications, especially when daily returns are small.
Using Log Returns for Annualized “Geometric” Return#
A slightly more precise way uses log returns.
Let:
\( r_t = \ln(1 + R_t) \) = log return
\( m_d = \mathbb{E}[r_t] \) = mean daily log return
Then the annualized log return is: \( m_{\text{ann}} = N \cdot m_d \)
and the corresponding annualized geometric mean return is: \( \mu_{\text{geom, ann}} = e^{m_{\text{ann}}} - 1 \)
This matches the idea of compounding over the year.
NumPy Example: Per-Stock Annualized Stats#
Assume:
returnsis(n_stocks, n_days-1)daily simple returnstrading_days = 252
1trading_days = 252
2
3# Mean and std of daily simple returns (per stock)
4mu_daily = np.mean(returns, axis=1) # shape: (n_stocks,)
5sigma_daily = np.std(returns, axis=1) # shape: (n_stocks,)
6
7# Annualized (simple) approximations
8mu_annual = mu_daily * trading_days
9sigma_annual = sigma_daily * np.sqrt(trading_days)
10
11print("Annualized mean returns (per stock):")
12print(mu_annual)
13
14print("\nAnnualized volatilities (per stock):")
15print(sigma_annual)
Annualized mean returns (per stock):
[0.2757 0.271 0.2468 0.2441 0.6769]
Annualized volatilities (per stock):
[0.2912 0.2676 0.2873 0.3287 0.498 ]
Now using log returns for geometric annualized return:
1# Daily log returns
2log_returns = np.log1p(returns)
3
4# Mean daily log return
5m_daily = np.mean(log_returns, axis=1)
6
7# Annualized log return and geometric mean return
8m_annual = m_daily * trading_days
9mu_geom_annual = np.exp(m_annual) - 1
10
11print("\nAnnualized geometric mean returns (per stock):")
12print(mu_geom_annual)
Annualized geometric mean returns (per stock):
[0.2627 0.265 0.228 0.2094 0.739 ]
Example: Annualizing a Portfolio’s Return and Volatility#
Suppose you have a portfolio with fixed weights weights (length n_stocks).
We can construct its daily return series and then annualize.
1# weights: shape (n_stocks,)
2weights = np.ones(returns.shape[0]) / returns.shape[0] # equal-weight example
3
4# Daily portfolio returns: weighted sum of asset returns each day
5# returns: (n_stocks, T) -> portfolio_returns: (T,)
6portfolio_returns = weights @ returns
7
8# Daily stats
9mu_port_daily = np.mean(portfolio_returns)
10sigma_port_daily = np.std(portfolio_returns)
11
12# Annualized
13mu_port_annual = mu_port_daily * trading_days
14sigma_port_annual = sigma_port_daily * np.sqrt(trading_days)
15
16print("Portfolio annualized mean return:", mu_port_annual)
17print("Portfolio annualized volatility:", sigma_port_annual)
Portfolio annualized mean return: 0.3428987738586141
Portfolio annualized volatility: 0.2767740475914089
Using log returns for the same portfolio:
1portfolio_log_returns = np.log1p(portfolio_returns)
2m_port_daily = np.mean(portfolio_log_returns)
3m_port_annual = m_port_daily * trading_days
4mu_port_geom_annual = np.exp(m_port_annual) - 1
5
6print("Portfolio annualized geometric mean return:", mu_port_geom_annual)
Portfolio annualized geometric mean return: 0.355784244535468
When to Use Which?#
Simple annualization (
mu_annual ≈ N * mu_daily)Easy to compute and explain
Good for small daily returns and rough comparisons
Log-return-based annualization (
exp(N * mean_log) - 1)More accurate for compounding
Preferred in quantitative modeling
In practice:
For communication (“about 8% per year”), either method is usually fine.
For modeling or when dealing with larger returns/volatility, the log-return approach is more consistent.
Summary: NumPy for Stock Analysis#
In this chapter we walked through a mini “quant stack” using only NumPy (plus seaborn for plots), starting from raw prices:
Prices → Returns
Built daily simple and log returns from a price matrix.
Discussed why log returns are convenient for modeling and compounding.
Single-Asset Statistics
Computed mean, median, and standard deviation of returns.
Introduced log returns and multi-period compounding.
Cross-Asset Dependence
Computed covariance and correlation matrices.
Found most/least correlated stock pairs to motivate diversification.
Portfolios and the Efficient Frontier
Computed portfolio return and volatility from weights, mean returns, and covariance.
Generated many random portfolios and plotted risk–return with seaborn.
(Optionally) constructed an efficient frontier via SciPy or pure NumPy linear algebra.
Time-Varying Risk
Used rolling windows (
sliding_window_view) for:Rolling mean and volatility
Rolling correlation between two stocks
Visualized how risk and co-movement change over time.
Drawdowns and Maximum Drawdown
Built a wealth index from returns.
Computed drawdown and maximum drawdown to quantify peak-to-trough losses.
Visualized drawdown time series and highlighted the worst drawdown.
Annualization
Converted daily returns and volatility to annualized quantities.
Showed both simple and log-return-based annualization for stocks and portfolios.
Up to this point we’ve done everything with raw NumPy arrays: prices as matrices, returns as matrices, weights as plain vectors. That’s great for understanding the math, but real-world financial data usually comes with labels: tickers, dates, sectors, missing values, and so on. This is where pandas becomes really helpful. In the next section, we’ll take the same ideas—prices, returns, portfolios, rolling stats, drawdowns—and rebuild them using DataFrame and Series objects. That will let us attach index labels (dates) and column names (stock tickers), handle missing data more gracefully, and write more readable code for time-series operations like resampling, shifting, and rolling windows. Essentially, pandas will give us a higher-level, more “finance-friendly” interface on top of the NumPy concepts you’ve already learned.