# Linear Algebra for Traders

> Linear algebra handles many assets at once using vectors and matrices. Learn portfolio variance with covariance matrices, PCA, regressions and the Python tools.

Source: https://learn.tradelabsai.com/math/linear-algebra-for-traders/  
Track: Math and Statistics · Level: Advanced · Updated: 2026-10-03  
Publisher: TradeLabs AI (https://tradelabsai.com). Education, not financial advice.  
Cite as: TradeLabs Learn, "Linear Algebra for Traders", https://learn.tradelabsai.com/math/linear-algebra-for-traders/

When you work with one asset, simple formulas are enough. With dozens or thousands of assets, you need a way to handle all of them at once. Linear algebra, the mathematics of vectors and matrices, does exactly that. It powers portfolio risk calculations, factor models, regressions, principal component analysis and much of machine learning. You do not need to be a mathematician, but understanding a few core ideas makes quantitative finance far easier to follow.

## Vectors and matrices

| Object | Description | Trading example |
|---|---|---|
| Vector | A list of numbers | Portfolio weights; expected returns of several assets |
| Matrix | A table of numbers | Returns of many assets over many days; a covariance matrix |
| Transpose | Flipping rows and columns | Turning a column of weights into a row |
| Matrix multiplication | Combining matrices according to rules | Computing portfolio returns from asset returns |

## Portfolio return and risk

With weights w (a vector), expected returns μ (a vector) and covariance matrix Σ:

```
portfolio expected return = wᵀ μ
portfolio variance = wᵀ Σ w
```

**Example: Three asset portfolio variance**
Weights: 50% stocks, 30% bonds, 20% gold. Annual volatilities: 16%, 6%, 15%. Correlations: stocks and bonds minus 0.2, stocks and gold 0.1, bonds and gold 0.3.

The covariance matrix has variances on the diagonal (0.0256, 0.0036, 0.0225) and covariances off the diagonal (for example, minus 0.2 × 0.16 × 0.06 = minus 0.00192 for stocks and bonds).

Computing wᵀ Σ w gives a portfolio variance of about 0.0079, so portfolio volatility is about 8.9%, well below the weighted average volatility of 12.8%, thanks to low correlations. See [Covariance and Correlation](https://learn.tradelabsai.com/math/covariance-and-correlation/) and [Diversification](https://learn.tradelabsai.com/portfolio/diversification/).

## Covariance matrices

A covariance matrix collects the variances of all assets and their pairwise covariances. For 500 stocks, it has 500 × 500 entries. Estimating it reliably is hard, because there are so many parameters relative to the data. Techniques such as shrinkage and factor models help. See [Bayesian Statistics](https://learn.tradelabsai.com/math/bayesian-statistics/) and [Factor Models](https://learn.tradelabsai.com/portfolio/factor-models/).

## Eigenvalues and principal component analysis

Principal component analysis (PCA) finds the directions in which a set of assets moves together most. It uses the eigenvalues and eigenvectors of the covariance or correlation matrix.

| Application | What PCA finds |
|---|---|
| Stock returns | The first component is usually the overall market |
| Yield curves | Level, slope and curvature explain most yield movements. See [Yield Curves](https://learn.tradelabsai.com/bonds-credit/yield-curves/) |
| Risk models | A few factors explain much of portfolio risk |
| Statistical arbitrage | Residuals after removing common components. See [Statistical Arbitrage](https://learn.tradelabsai.com/strategies/statistical-arbitrage/) |

## Regression in matrix form

Multiple regression can be written compactly:

```
β = (Xᵀ X)⁻¹ Xᵀ y
```

where X is the matrix of explanatory variables and y the vector of outcomes. This formula gives the ordinary least squares estimates for any number of variables. See [Regression Analysis](https://learn.tradelabsai.com/math/regression-analysis/).

## Optimisation

Mean variance portfolio optimisation finds weights that minimise wᵀ Σ w for a target return, subject to constraints. Matrix maths makes these problems solvable for large portfolios. See [Portfolio Optimization](https://learn.tradelabsai.com/portfolio/portfolio-optimization/) and [Optimization](https://learn.tradelabsai.com/math/optimization/).

## Practical tools

In Python, NumPy handles vectors and matrices efficiently:

```python
import numpy as np
w = np.array([0.5, 0.3, 0.2])
vol = np.array([0.16, 0.06, 0.15])
corr = np.array([[1.0, -0.2, 0.1],
                 [-0.2, 1.0, 0.3],
                 [0.1, 0.3, 1.0]])
cov = np.outer(vol, vol) * corr
port_vol = np.sqrt(w @ cov @ w)
print(round(port_vol, 4))
```

See [NumPy and Pandas for Traders](https://learn.tradelabsai.com/programming/numpy-and-pandas-for-traders/).

## Common pitfalls

- **Ill conditioned matrices:** nearly collinear assets make inverses unstable.
- **Estimation error:** small errors in Σ or μ produce extreme optimised weights.
- **Shape mismatches** in code.

## Where to learn more

A practical route is to learn NumPy array operations, then work through covariance matrices, regression and PCA on real return data. Seeing how changing one correlation changes portfolio volatility builds intuition faster than formulas alone. See [Python for Trading](https://learn.tradelabsai.com/programming/python-for-trading/).

## Frequently asked questions

### Why do traders need linear algebra?

To handle many assets at once in portfolio risk, factor models, regressions, PCA and optimisation.

### How is portfolio variance calculated with matrices?

As wᵀ Σ w, where w is the vector of weights and Σ is the covariance matrix.

### What is PCA used for in finance?

To find the main common drivers of a set of assets, such as the market factor in stocks or level, slope and curvature in yield curves.

Next, learn the calculus behind sensitivities in [Calculus for Traders](https://learn.tradelabsai.com/math/calculus-for-traders/).

## Continue learning

- Next lesson: [Calculus for Traders](https://learn.tradelabsai.com/math/calculus-for-traders/)
- Previous lesson: [Time Value of Money](https://learn.tradelabsai.com/math/time-value-of-money/)
- Related: [Time Value of Money](https://learn.tradelabsai.com/math/time-value-of-money/): A dollar today is worth more than a dollar tomorrow. Learn present and future value, discounting, annuities and NPV, the maths behind bonds, valuations and options.
- Related: [Covariance and Correlation](https://learn.tradelabsai.com/math/covariance-and-correlation/): Covariance and correlation measure how two assets move together. Learn the formulas, how to read them, why correlations change in crises and their portfolio role.
- Related: [Portfolio Optimization](https://learn.tradelabsai.com/portfolio/portfolio-optimization/): Portfolio optimisation uses maths to choose weights that best meet a goal. Learn mean variance, minimum variance, constraints and how to handle estimation error.
- Related: [Factor Models](https://learn.tradelabsai.com/portfolio/factor-models/): Factor models explain asset returns with common drivers such as the market, size, value and momentum. Learn CAPM, Fama French and how to run a factor regression.
- Related: [Regression Analysis](https://learn.tradelabsai.com/math/regression-analysis/): Regression models how one variable relates to others. Learn linear regression, beta, R squared, multiple regression for factors, hedge ratios and common pitfalls.
- Related: [NumPy and Pandas for Traders](https://learn.tradelabsai.com/programming/numpy-and-pandas-for-traders/): Learn the pandas and NumPy operations traders use most: loading price data, returns, rolling windows, resampling bars, joining assets and avoiding common traps.
