Correlation measures how asset movements relate: positive correlation indicates movement in the same direction, while negative correlation indicates movement in opposite directions. Use returns rather than absolute share prices when comparing performance, because prices depend on factors such as share splits. section 7.2.2
def collect_prices_returns(tickers: list):
close_prices = pd.DataFrame()
log_returns = pd.DataFrame()
for ticker in tickers:
close_prices[ticker] = yf.Ticker(ticker).history(
start='2024-01-01',
end='2024-12-31',
interval="1d")['Close']
log_returns[ticker] = np.log(close_prices[ticker]
/ close_prices[ticker].shift(1))
return close_prices, log_returns
tickers = ["MSFT", "AMZN", "GOOGL"]
close_prices, log_returns = collect_prices_returns(tickers)
Load closing prices for several tickers and calculate log returns before analyzing their relationships. section 7.2.2
A practical correlation workflow connects several risk measures:
- Calculate log returns, then inspect standard deviation, variance, covariance, and correlation rather than comparing raw share prices. section 7.2.2
- Use correlation to assess whether holdings may move together when constructing a diversified portfolio. section 7.7
- Treat historical correlation cautiously: diversification requires understanding which assets may correlate, and correlation alone does not remove investment risk. section 7.7
Comparing technology stocks
The calculated log-return correlations are 0.68765 for Microsoft and Amazon, 0.57522 for Microsoft and Alphabet, and 0.54331 for Amazon and Alphabet. Walmart and NVIDIA produce a correlation of −0.00532, indicating almost no linear co-movement in the observed data. section 7.2.2















