Linear regression — fitting a line through returns
▸ Pretest — guess, even if you don't know
You regress AAPL daily returns on SPY daily returns and find slope = 1.2, intercept = 0.0001. What does the slope mean?
The setup
You have pairs of observations for — read: "x and y at time t, for t running from 1 up to N." Think of a scatter plot: each day gives you one dot, with that day's SPY return on the x-axis and that day's AAPL return on the y-axis. Linear regression fits the best straight line through the dots:
In words: each day's y equals a fixed baseline, plus a slope times that day's x, plus whatever is left over.
Symbol by symbol:
- — the Greek letter alpha — is the intercept: the value of when is zero.
- — beta — is the slope: how much moves for each 1-unit move in .
- — the Greek letter epsilon, read "epsilon sub t" — is the residual at observation : the leftover gap between the actual and what the line predicted. Every dot misses the line by some amount; that miss is the residual.
What counts as the "best" line? The usual answer is ordinary least squares (OLS): choose the line that minimizes the sum of squared residuals, — for each dot, square its miss, add them all up, and make that total as small as possible. Squaring means big misses hurt much more than small ones.
The OLS answers have closed forms — direct formulas, no trial-and-error search needed. One more piece of notation first: a hat, as in (read "beta hat"), marks an estimate computed from data; a bar, as in (read "x bar"), means the average of :
In words: the estimated slope is the covariance of x and y (how much they move together — see A2-08) divided by the variance of x (how much x moves on its own). The estimated intercept is the average of y minus the slope times the average of x — which just forces the line to pass through the point of averages.
So beta answers: "how much does move with , in -units per -unit?" The division by rescales the co-movement into that per-unit form.
In finance: regressing on market returns
The single most-used regression in finance is the same line, with returns plugged in:
In words: the return of stock i on day t equals the stock's own baseline return, plus its market sensitivity times the market's return that day, plus stock-specific noise.
Reading the subscripts (each one is just a label):
- — "r sub i, t" — the return on asset at time .
- — "r sub m, t" — the market return at time (usually SPY or a broader index).
- — the asset's idiosyncratic mean return — "idiosyncratic" means specific to this asset, unrelated to the market. It's what you'd earn if the market were flat.
- — the asset's sensitivity to market moves.
Real-world beta values: for AAPL regressed on SPY since 2010, . Utilities sit around — less market-sensitive. High-beta tech and biotech can run 1.5–2.5. Long/short hedged portfolios — funds that own some stocks and bet against others — target by construction.
This is the Capital Asset Pricing Model regression — we'll cover its economic interpretation in the next lesson (D2-01).
Correlation vs. slope
A frequent confusion: correlation (the Greek letter rho, from A2-08) and slope are related but different:
In words: both start from the covariance of x and y, but divide by different things. Correlation divides by both standard deviations, giving a pure, unitless number. Slope divides by the variance of x only — so the slope equals the correlation times the ratio of the two standard deviations.
Correlation is unitless and always lands between −1 and +1. Slope has units of "y per x" and can be any number.
Concrete example. Returns of AAPL and SPY have , with and (AAPL swings 1.5× as much as SPY). Then:
You can have high correlation but low beta (correlated but moves less than ) or low correlation but high beta (rarely co-moves but when it does, moves a lot).
— explained variance
— read "R squared" — measures what fraction of 's variance the regression explains:
In words: take the variance of the leftovers (the residuals), divide by the total variance of y, and subtract that fraction from 1. What remains is the share of y's movement the line accounts for.
For a regression with one predictor, — just the correlation, squared. Correlation of 0.7 means of about 0.49.
- : regression explains nothing.
- : regression is a perfect fit (all residuals zero — usually a sign of overfitting, or that you accidentally regressed a variable on itself).
- : regression explains half the variance.
For AAPL on SPY: . About half the variance of AAPL is explained by the market; the rest is idiosyncratic (Apple-specific news).
Multiple regression — more factors
If you have multiple predictors — that's different input series, each with its own subscript:
In words: y is a baseline, plus a separate slope times each predictor, plus a residual. Each slope measures y's sensitivity to predictor holding the other predictors fixed.
OLS still has a closed-form solution (the normal equations — a system of equations you solve directly), but the math is cleaner in matrix notation. We'll meet that in Track A3 (linear algebra) and use it in Track D2 (factor models — Fama-French 3 and 5 factors, etc.).
A common mistake: regress AAPL on (SPY, momentum, value) and get coefficient estimates that "look reasonable." But if the predictors are correlated with each other — a condition called multicollinearity — the individual coefficient estimates become unstable. We'll cover diagnostics in A2-07.
Code snippet (for laptop)
import statsmodels.api as sm
import yfinance as yf
import numpy as np
data = yf.download(["AAPL", "SPY"], start="2010-01-01")["Adj Close"]
returns = np.log(data / data.shift(1)).dropna()
# Need to add a constant for the intercept
X = sm.add_constant(returns["SPY"])
y = returns["AAPL"]
model = sm.OLS(y, X).fit()
print(model.summary())
# Look for: const (alpha), SPY (beta), R-squared, t-statistics, p-values
statsmodels gives you a full diagnostic printout — standard errors, t-stats, p-values, R². For Phase 1 we'll use statsmodels for almost all regressions; for production models, numpy.linalg.lstsq or scikit-learn are also options.
Assumptions OLS makes (and where they break)
Under five assumptions, OLS is "BLUE" — the Best Linear Unbiased Estimator, meaning no other line-fitting method of its kind gets closer to the truth on average:
- Linearity — the true relationship really is a straight line.
- No autocorrelation — residuals are independent over time — today's miss tells you nothing about tomorrow's.
- Homoscedasticity — read "ho-mo-skuh-das-TIH-city" — residuals have constant variance: the misses are equally noisy everywhere, not calm in some periods and wild in others.
- Normality of residuals — the misses follow a bell curve. Only needed for hypothesis tests, not for the fitted line itself.
- No multicollinearity among predictors.
Financial data breaks 2, 3, and often 5. The point estimates — the fitted and themselves — are still consistent (they converge to the truth as data grows). But the standard errors are wrong, which means your t-statistics and p-values are wrong. You can trust the line more than you can trust the claim that the line is "significant."
Fix: use corrected standard errors. Newey-West corrects for autocorrelation; White (also called "robust") corrects for heteroscedasticity; HAC — heteroscedasticity and autocorrelation consistent — corrects for both. statsmodels provides these via model.fit(cov_type='HAC', cov_kwds={'maxlags': 5}).
We'll cover diagnostics and corrections in A2-07.
Try it
Compute beta from the closed form — no statsmodels needed, just the covariance-over-variance formula:
Implement beta(asset_returns, market_returns) = Cov(asset, market) / Var(market). Use np.cov(asset_returns, market_returns)[0, 1] for the covariance and np.var(market_returns, ddof=1) for the variance - np.cov defaults to ddof=1, so the denominators must match.
⧉ Review cardWhat is the slope of an OLS regression in formula form?
⧉ Review cardWhat is beta in finance?
⧉ Review cardWhat's the relationship between correlation and regression slope?
⧉ Review cardWhat does R² = 0.5 mean?
⧉ Review cardWhy are OLS standard errors usually wrong for financial data?
Predict before the next lesson
Tomorrow: CAPM (D2-01), where we interpret the alpha and beta of the market regression economically. Predict:
- If a stock has positive alpha vs. the market, what does this imply about its risk-adjusted return?
- Why might a stock with β = 1.5 reasonably be expected to have higher returns than the market?
◈ Calibration check
Could you set up and interpret a single-factor regression on real return data?
1 = guessing · 5 = could teach it
⏻ End of lesson
Mark it read to book its 5 review cards into your deck.
Sources & further reading
- bookWasserman (2004), All of Statistics — §13
- bookHamilton (1994), Time Series Analysis — §8
- bookTsay (2010), Analysis of Financial Time Series, 3e — §2.3
- bookGelman & Hill (2007), Data Analysis Using Regression — §3, 4