expanding Method¶
The expanding() method computes statistics over all data from the start up to each point, with a window that grows over time.
Basic Expanding¶
Create expanding window calculations.
1. Cumulative Mean¶
import pandas as pd
import yfinance as yf
aapl = yf.download('AAPL', start='2023-01-01', end='2024-01-01')
aapl['Cumulative_Mean'] = aapl['Close'].expanding().mean()
print(aapl[['Close', 'Cumulative_Mean']].head(10))
2. Cumulative Sum¶
aapl['Cumulative_Sum'] = aapl['Volume'].expanding().sum()
3. Cumulative Standard Deviation¶
aapl['Cumulative_STD'] = aapl['Close'].expanding().std()
How Expanding Works¶
At time t, includes observations 1 to t.
1. Window Growth¶
# Day 1: window = [1]
# Day 2: window = [1, 2]
# Day 3: window = [1, 2, 3]
# Day N: window = [1, 2, ..., N]
2. Formula for Mean¶
At time \(t\):
\[\text{Expanding Mean}_t = \frac{1}{t} \sum_{i=1}^{t} x_i\]
3. vs Rolling¶
# Rolling: fixed window size
# Expanding: window grows from 1 to N
min_periods Parameter¶
Minimum observations before calculating.
1. Default (min_periods=1)¶
s.expanding().mean() # Starts from first value
2. With Minimum¶
s.expanding(min_periods=5).mean() # First 4 values are NaN
3. Use Case¶
# Wait for enough data before computing volatility
s.expanding(min_periods=20).std()
Common Applications¶
Typical expanding calculations.
1. Cumulative Returns¶
returns = aapl['Close'].pct_change()
cumulative = (1 + returns).expanding().prod() - 1
2. Running Statistics¶
aapl['Running_Max'] = aapl['Close'].expanding().max()
aapl['Running_Min'] = aapl['Close'].expanding().min()
3. Progressive Estimates¶
# Track how estimates converge
aapl['Mean_Estimate'] = aapl['Close'].expanding().mean()
Financial Example¶
Track cumulative performance metrics.
1. Cumulative Sharpe¶
import numpy as np
returns = aapl['Close'].pct_change()
aapl['Cum_Mean'] = returns.expanding().mean()
aapl['Cum_Std'] = returns.expanding().std()
aapl['Cum_Sharpe'] = aapl['Cum_Mean'] / aapl['Cum_Std'] * np.sqrt(252)
2. All-Time High¶
aapl['ATH'] = aapl['Close'].expanding().max()
aapl['Drawdown'] = aapl['Close'] / aapl['ATH'] - 1
3. Since Inception Returns¶
first_price = aapl['Close'].iloc[0]
aapl['Since_Inception'] = aapl['Close'] / first_price - 1
Expanding vs cumsum/cumprod¶
Comparison with built-in cumulative functions.
1. cumsum¶
# Equivalent for sum
s.expanding().sum()
s.cumsum() # Same result, faster
2. cumprod¶
# Equivalent for product
s.expanding().prod()
s.cumprod() # Same result, faster
3. When to Use Each¶
# Use cumsum/cumprod for simple cumulative operations
# Use expanding() for mean, std, custom functions