Lesson 60 · Pandas Full Course
Analyse Stock Price Trends in Pandas: Moving Averages and Crossovers | Pandas Course #60
In this lesson you'll be able to: Load a price history with a real date index Zoom out from days to months with resample Smooth prices with moving averages…
- CoursePandas Full Course
- Lesson60 of 65
- FormatJupyter notebook · 41 code cells
- Data2 datasets
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- aapl.csv preview58.8 KB
- stocks.csv preview148.1 KB
📓 Full notebook
Download .ipynbPandas 60: Hands-on Project - Analysing Stock Prices and Trends#
In this lesson you'll be able to:
- Load a price history with a real date index
- Zoom out from days to months with resample
- Smooth prices with moving averages and spot trend changes
- Measure highs, lows, drawdowns and big one-day moves
- Compare two price trends on one scale Data: Apple daily prices (aapl.csv) and five price series (stocks.csv)
Warm-up: daily returns#
Lesson 59 measured daily returns. Here's the same idea on Apple.
import pandas as pd
import matplotlib.pyplot as plt
raw = pd.read_csv("data/pandas/aapl.csv")
print(raw.shape)
raw.sample(3, random_state=42)
ret = raw["AAPL.Close"].pct_change() * 100
ret.describe().round(2)
Load prices with a real date index#
Problem: pandas treats the Date column as plain text until told otherwise.
Common mistake: using a time tool on a table indexed by row numbers.
raw["AAPL.Close"].resample("ME").mean()
df = pd.read_csv("data/pandas/aapl.csv", parse_dates=["Date"],
index_col="Date")
print(type(df.index).__name__)
df["AAPL.Close"].resample("ME").mean().round(2).head(3)
keep = ["AAPL.Open", "AAPL.High", "AAPL.Low", "AAPL.Close",
"AAPL.Volume"]
df = df[keep]
df.columns = df.columns.str.replace("AAPL.", "").str.lower()
df.head(3)
print(df.isna().sum().sum())
gaps = df.index.to_series().diff()
gaps.value_counts()
Quick check: why are so many gaps exactly 3 days long?
three = gaps[gaps == "3 days"]
three.index.day_name().value_counts()
daily = df["close"].asfreq("D")
print(daily.isna().sum())
daily.ffill().loc["2015-02-20":"2015-02-24"]
Zoom out from days to months#
Problem: 506 daily prices are too noisy to read at a glance.
ax = df["close"].plot(figsize=(9, 4))
ax.set_title("Apple daily closing price")
ax.set_xlabel("Date")
ax.set_ylabel("Price (USD)")
Common mistake: using the old 'M' alias for monthly.
df["close"].resample("M").mean()
monthly = df["close"].resample("ME").mean().round(2)
print(len(monthly))
monthly.head()
Quick check: which month had the lowest average close?
low = monthly.idxmin()
print(low.strftime("%B %Y"), monthly.min())
rules = {"open": "first", "high": "max", "low": "min",
"close": "last", "volume": "sum"}
bars = df.resample("ME").agg(rules)
bars.head(3).round(2)
bars["change_%"] = bars["close"].pct_change() * 100
bars["change_%"].dropna().sort_values().iloc[[0, -1]].round(2)
Smooth the noise with moving averages#
Problem: daily wiggles hide the direction the price is heading.
df["ma20"] = df["close"].rolling(20).mean()
df[["close", "ma20"]].iloc[17:22].round(2)
Quick check: why is ma20 empty for the first 19 rows?
early = df["close"].rolling(20, min_periods=5).mean()
early.iloc[3:6].round(2)
df["ma50"] = df["close"].rolling(50).mean()
df["ma200"] = df["close"].rolling(200).mean()
print(df[["ma50", "ma200"]].notna().sum())
cols = ["close", "ma50", "ma200"]
ax = df[cols].plot(figsize=(9, 4))
ax.set_title("Apple close with 50 and 200 day averages")
ax.set_xlabel("Date")
ax.set_ylabel("Price (USD)")
Your turn: on what share of days did Apple close above its 50-day average? Hint: skip the days where ma50 is still empty.
valid = df.dropna(subset=["ma50"])
above = valid["close"] > valid["ma50"]
print(above.sum(), len(valid), round(above.mean() * 100, 1))
Spot trend changes with crossovers#
Problem: find the exact days the 20-day average crossed the 50-day.
sig = df[["close", "ma20", "ma50"]].dropna().copy()
sig["up"] = sig["ma20"] > sig["ma50"]
sig["up"].value_counts()
change = sig["up"].astype(int).diff()
crosses = sig[change.abs() == 1].copy()
names = {True: "upward", False: "downward"}
crosses["kind"] = crosses["up"].map(names)
crosses[["close", "kind"]].round(2)
later = sig["close"].shift(-40)
crosses["after_40d_%"] = (later / sig["close"] - 1) * 100
crosses[["kind", "after_40d_%"]].round(2)
crosses.groupby("kind")["after_40d_%"].agg(["count", "mean"]).round(2)
ax = sig[["ma20", "ma50"]].plot(figsize=(9, 4))
for day in crosses.index:
ax.axvline(day, color="grey", linestyle="--")
ax.set_title("Apple 20 and 50 day averages with crossovers")
ax.set_xlabel("Date")
ax.set_ylabel("Price (USD)")
Find highs, lows and big moves#
Problem: pin down the record days and the deepest fall from a peak.
top = df["close"].idxmax()
bottom = df["close"].idxmin()
print("High:", top.date(), df.loc[top, "close"].round(2))
print("Low:", bottom.date(), df.loc[bottom, "close"].round(2))
peak = df["close"].cummax()
df["drawdown_%"] = (df["close"] / peak - 1) * 100
worst = df["drawdown_%"].idxmin()
print(worst.date(), df.loc[worst, "drawdown_%"].round(2))
ax = df["drawdown_%"].plot.area(figsize=(9, 3), alpha=0.4)
ax.set_title("Apple drawdown from its running peak")
ax.set_xlabel("Date")
ax.set_ylabel("Below peak (%)")
df["ret"] = df["close"].pct_change() * 100
print(df["ret"].round(2).agg(["min", "max"]))
Common mistake: joining two conditions with the word or.
big = df[(df["ret"] > 4) or (df["ret"] < -4)]
big = df[df["ret"].abs() > 4]
print(len(big))
big[["close", "ret", "volume"]].round(2)
Compare two trends on one scale#
Problem: a 100 dollar share and a 2000 point index won't share an axis.
s = pd.read_csv("data/pandas/stocks.csv", parse_dates=["Date"],
index_col="Date")
print(s.shape, s.index.min().date(), s.index.max().date())
s.head(3)
pair = s[["AAPL", "GSPC"]]
growth = pair / pair.iloc[0] * 100
growth.iloc[-1].round(1)
ax = growth.plot(figsize=(9, 4))
ax.set_title("Growth of 100 invested, 2007 to 2016")
ax.set_xlabel("Date")
ax.set_ylabel("Value (start = 100)")
yearly = pair.resample("YE").last().pct_change() * 100
yearly.dropna().round(1)
Quick check: in how many of those years did Apple beat the index?
diffs = yearly.dropna()
wins = diffs["AAPL"] > diffs["GSPC"]
print(wins.sum(), len(wins))
Mini-project: do volume spikes mark big moves?#
Question: were Apple's busiest trading days also its biggest price moves? Plan: top days, correlation, busy versus normal days, then a chart.
top5 = df.nlargest(5, "volume")
top5[["close", "ret", "volume"]].round(2)
df["abs_ret"] = df["ret"].abs()
r = df["volume"].corr(df["abs_ret"])
print(round(r, 2))
busy = df["volume"] > df["volume"].quantile(0.9)
df.groupby(busy)["abs_ret"].agg(["count", "mean"]).round(2)
fig, ax = plt.subplots(figsize=(9, 4))
ax.plot(df.index, df["close"], color="tab:blue")
ax2 = ax.twinx()
ax2.bar(df.index, df["volume"], color="tab:orange", alpha=0.3)
ax.set_title("Apple close and trading volume")
ax.set_xlabel("Date")
ax.set_ylabel("Price (USD)")
ax2.set_ylabel("Shares traded")
import os
os.makedirs("output/pandas", exist_ok=True)
path = "output/pandas/l60_aapl_trends.csv"
df.to_csv(path)
back = pd.read_csv(path, parse_dates=["Date"], index_col="Date")
print(back.shape)
normal = df.loc[~busy, "abs_ret"].mean()
heavy = df.loc[busy, "abs_ret"].mean()
print(f"Busy days move {heavy / normal:.1f} times as much")
Recap#
- parse_dates plus index_col gives a DatetimeIndex for time tools
- resample with ME and agg rules turns days into monthly bars
- rolling means smooth noise; crossovers mark trend changes
- cummax gives drawdowns; abs() catches big moves either way
- Rebase to 100 to compare series with different scales
Challenges#
- Repeat the crossover test with the 50 and 200 day averages.
- Find Microsoft's deepest drawdown in stocks.csv.
- Build monthly bars for Apple and count the up months.
What's next#
Lesson 61: Building a KPI Dashboard with Pandas Turn a large sales table into the handful of numbers a business watches.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



