Local averaging smooths short-term price fluctuations by averaging observations inside a rolling time window. For a simple moving average (SMA), add the closing prices in a window and divide by the number of observations; when a new price arrives, remove the oldest one. section 10.2.2
The window controls the trade-off: shorter averages respond sooner, while longer averages provide a broader view and greater smoothing. Different formulas emphasize different goals: EMAs weight recent values, WMAs apply linear weights, and HMAs seek smoother signals with reduced lag. section 10.2.2 section 10.4
Calculate averages with pandas
Given a DataFrame with a Price column, use df["Price"].rolling(window=3).mean() for an SMA and df["Price"].ewm(span=3, adjust=False).mean() for an EMA. Applying the same functions to historical Close prices lets you compare several averages for one asset and window. section 10.2.2
Listing 10.2 Calculating SMA and EMAs
import pandas as pd
data = {
"Date": pd.date_range(start="2023-01-01", periods=10),
"Price": [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
}
df = pd.DataFrame(data)
window_size = 3
df['SMA'] = df['Price'].rolling(
window=window_size).mean() #1
df['EMA'] = df['Price'].ewm(
span=window_size, adjust=False).mean() #2
Inspect the compact pandas listing that calculates SMA and EMA values from a ten-row price series. section 10.2.2
Plotting several SMAs together creates a moving-average ribbon. Contracting ribbons can indicate price consolidation, while crossovers between shorter and longer averages can become algorithmic buy or sell signals. These signals remain interpretations rather than guarantees: technical analysis is debated, and results depend on the asset, window, time horizon, and trading costs. section 10.1.3 section 10.4
A practical workflow is to calculate averages in a DataFrame, visualize them against closing prices, then backtest a defined rule on historical data. For example, a shorter SMA crossing above a longer SMA signals a buy, while crossing below signals a sell; transaction costs belong in the comparison. section 11.3.1






