Mathew K Analytics

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…

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.

📓 Full notebook

Download .ipynb

Pandas 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)
(506, 11)
Date AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted dn mavg up direction
173 2015-10-22 114.330002 115.500000 114.099998 115.500000 41654100 112.018901 107.992084 111.493667 114.995250 Increasing
274 2016-03-18 106.339996 106.500000 105.190002 105.919998 44205200 103.727179 93.952721 100.647167 107.341612 Decreasing
491 2017-01-27 122.139999 122.349998 121.599998 121.949997 20562900 121.423555 115.190236 118.935667 122.681098 Decreasing
ret = raw["AAPL.Close"].pct_change() * 100
ret.describe().round(2)
count    505.00
mean       0.02
std        1.53
min       -6.57
25%       -0.66
50%        0.00
75%        0.83
max        6.50
Name: AAPL.Close, dtype: float64

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()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 raw["AAPL.Close"].resample("ME").mean()

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\generic.py:9411, in NDFrame.resample(self, rule, closed, label, convention, on, level, origin, offset, group_keys)
   9056 """
   9057 Resample time-series data.
   9058 
   (...)
   9407 Freq: 17min, dtype: int64
   9408 """
   9409 from pandas.core.resample import get_resampler
-> 9411 return get_resampler(
   9412     cast("Series | DataFrame", self),
   9413     freq=rule,
   9414     label=label,
   9415     closed=closed,
   9416     convention=convention,
   9417     key=on,
   9418     level=level,
   9419     origin=origin,
   9420     offset=offset,
   9421     group_keys=group_keys,
   9422 )

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\resample.py:2335, in get_resampler(obj, **kwds)
   2331 """
   2332 Create a TimeGrouper and return our resampler.
   2333 """
   2334 tg = TimeGrouper(obj, **kwds)  # type: ignore[arg-type]
-> 2335 return tg._get_resampler(obj)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\resample.py:2541, in TimeGrouper._get_resampler(self, obj)
   2533 elif isinstance(ax, TimedeltaIndex):
   2534     return TimedeltaIndexResampler(
   2535         obj,
   2536         timegrouper=self,
   2537         group_keys=self.group_keys,
   2538         gpr_index=ax,
   2539     )
-> 2541 raise TypeError(
   2542     "Only valid with DatetimeIndex, "
   2543     "TimedeltaIndex or PeriodIndex, "
   2544     f"but got an instance of '{type(ax).__name__}'"
   2545 )

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
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)
DatetimeIndex
Date
2015-02-28    129.70
2015-03-31    125.97
2015-04-30    127.29
Freq: ME, Name: AAPL.Close, dtype: float64
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)
open high low close volume
Date
2015-02-17 127.489998 128.880005 126.919998 127.830002 63152400
2015-02-18 127.629997 128.779999 127.449997 128.720001 44891700
2015-02-19 128.479996 129.029999 128.330002 128.449997 37362400
print(df.isna().sum().sum())
gaps = df.index.to_series().diff()
gaps.value_counts()
0
Date
1 days    399
3 days     89
4 days     15
2 days      2
Name: count, dtype: int64

Quick check: why are so many gaps exactly 3 days long?

three = gaps[gaps == "3 days"]
three.index.day_name().value_counts()
Date
Monday    89
Name: count, dtype: int64
daily = df["close"].asfreq("D")
print(daily.isna().sum())
daily.ffill().loc["2015-02-20":"2015-02-24"]
225
Date
2015-02-20    129.500000
2015-02-21    129.500000
2015-02-22    129.500000
2015-02-23    133.000000
2015-02-24    132.169998
Freq: D, Name: close, dtype: float64

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)")
No description has been provided for this image

Common mistake: using the old 'M' alias for monthly.

df["close"].resample("M").mean()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
File pandas/_libs/tslibs/offsets.pyx:6338, in pandas._libs.tslibs.offsets.to_offset()

File pandas/_libs/tslibs/offsets.pyx:6205, in pandas._libs.tslibs.offsets._validate_to_offset_alias()

ValueError: 'M' is no longer supported for offsets. Please use 'ME' instead.

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
Cell In[11], line 1
----> 1 df["close"].resample("M").mean()

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\generic.py:9411, in NDFrame.resample(self, rule, closed, label, convention, on, level, origin, offset, group_keys)
   9056 """
   9057 Resample time-series data.
   9058 
   (...)
   9407 Freq: 17min, dtype: int64
   9408 """
   9409 from pandas.core.resample import get_resampler
-> 9411 return get_resampler(
   9412     cast("Series | DataFrame", self),
   9413     freq=rule,
   9414     label=label,
   9415     closed=closed,
   9416     convention=convention,
   9417     key=on,
   9418     level=level,
   9419     origin=origin,
   9420     offset=offset,
   9421     group_keys=group_keys,
   9422 )

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\resample.py:2334, in get_resampler(obj, **kwds)
   2330 def get_resampler(obj: Series | DataFrame, **kwds) -> Resampler:
   2331     """
   2332     Create a TimeGrouper and return our resampler.
   2333     """
-> 2334     tg = TimeGrouper(obj, **kwds)  # type: ignore[arg-type]
   2335     return tg._get_resampler(obj)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\resample.py:2420, in TimeGrouper.__init__(self, obj, freq, key, closed, label, how, fill_method, limit, convention, origin, offset, group_keys, **kwargs)
   2418     freq = to_offset(freq, is_period=True)
   2419 else:
-> 2420     freq = to_offset(freq)
   2422 if not isinstance(freq, Tick):
   2423     if offset is not None:

File pandas/_libs/tslibs/offsets.pyx:6254, in pandas._libs.tslibs.offsets.to_offset()

File pandas/_libs/tslibs/offsets.pyx:6377, in pandas._libs.tslibs.offsets.to_offset()

File pandas/_libs/tslibs/offsets.pyx:6162, in pandas._libs.tslibs.offsets.raise_invalid_freq()

ValueError: Invalid frequency: M. Failed to parse with error message: ValueError("'M' is no longer supported for offsets. Please use 'ME' instead.")
monthly = df["close"].resample("ME").mean().round(2)
print(len(monthly))
monthly.head()
25
Date
2015-02-28    129.70
2015-03-31    125.97
2015-04-30    127.29
2015-05-31    128.76
2015-06-30    127.81
Freq: ME, Name: close, dtype: float64

Quick check: which month had the lowest average close?

low = monthly.idxmin()
print(low.strftime("%B %Y"), monthly.min())
May 2016 94.97
rules = {"open": "first", "high": "max", "low": "min",
         "close": "last", "volume": "sum"}
bars = df.resample("ME").agg(rules)
bars.head(3).round(2)
open high low close volume
Date
2015-02-28 127.49 133.60 126.61 128.46 562571100
2015-03-31 129.25 130.28 121.63 124.43 1138642100
2015-04-30 124.82 134.54 123.10 125.15 996135500
bars["change_%"] = bars["close"].pct_change() * 100
bars["change_%"].dropna().sort_values().iloc[[0, -1]].round(2)
Date
2016-04-30   -13.99
2016-03-31    12.72
Name: change_%, dtype: float64

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)
close ma20
Date
2015-03-12 124.45 NaN
2015-03-13 123.59 NaN
2015-03-16 124.95 127.71
2015-03-17 127.04 127.67
2015-03-18 128.47 127.66

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)
Date
2015-02-20       NaN
2015-02-23    129.50
2015-02-24    129.94
Name: close, dtype: float64
df["ma50"] = df["close"].rolling(50).mean()
df["ma200"] = df["close"].rolling(200).mean()
print(df[["ma50", "ma200"]].notna().sum())
ma50     457
ma200    307
dtype: int64
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)")
No description has been provided for this image

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))
226 457 49.5

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()
up
True     238
False    219
Name: count, dtype: int64
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)
close kind
Date
2015-06-25 127.50 downward
2015-10-27 114.55 upward
2015-12-18 106.03 downward
2016-03-11 102.26 upward
2016-05-05 93.24 downward
2016-07-01 95.89 upward
2016-07-08 96.68 downward
2016-07-25 97.34 upward
2016-11-15 107.11 downward
2016-12-22 116.29 upward
later = sig["close"].shift(-40)
crosses["after_40d_%"] = (later / sig["close"] - 1) * 100
crosses[["kind", "after_40d_%"]].round(2)
kind after_40d_%
Date
2015-06-25 downward -17.05
2015-10-27 upward -5.19
2015-12-18 downward -9.21
2016-03-11 upward -9.26
2016-05-05 downward 2.84
2016-07-01 upward 11.40
2016-07-08 downward 11.43
2016-07-25 upward 16.67
2016-11-15 downward 11.14
2016-12-22 upward NaN
crosses.groupby("kind")["after_40d_%"].agg(["count", "mean"]).round(2)
count mean
kind
downward 5 -0.17
upward 4 3.41
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)")
No description has been provided for this image

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))
High: 2017-02-15 135.51
Low: 2016-05-12 90.34
peak = df["close"].cummax()
df["drawdown_%"] = (df["close"] / peak - 1) * 100
worst = df["drawdown_%"].idxmin()
print(worst.date(), df.loc[worst, "drawdown_%"].round(2))
2016-05-12 -32.08
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 (%)")
No description has been provided for this image
df["ret"] = df["close"].pct_change() * 100
print(df["ret"].round(2).agg(["min", "max"]))
min   -6.57
max    6.50
Name: ret, dtype: float64

Common mistake: joining two conditions with the word or.

big = df[(df["ret"] > 4) or (df["ret"] < -4)]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_5300\4183925537.py in ?()
----> 1 big = df[(df["ret"] > 4) or (df["ret"] < -4)]

~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\generic.py in ?(self)
   1499     @final
   1500     def __bool__(self) -> NoReturn:
-> 1501         raise ValueError(
   1502             f"The truth value of a {type(self).__name__} is ambiguous. "
   1503             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1504         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
big = df[df["ret"].abs() > 4]
print(len(big))
big[["close", "ret", "volume"]].round(2)
13
close ret volume
Date
2015-07-22 125.22 -4.23 115450600
2015-08-11 113.49 -5.20 97082800
2015-08-21 105.76 -6.12 128275500
2015-08-26 109.69 5.74 96774600
2015-09-01 107.72 -4.47 76845900
2015-09-02 112.34 4.29 61888800
2015-10-28 119.27 4.12 85551400
2016-01-07 96.45 -4.22 81094400
2016-01-22 101.42 5.32 65800500
2016-01-27 93.42 -6.57 133369700
2016-04-27 97.82 -6.26 114602100
2016-07-27 102.95 6.50 92344800
2017-02-01 128.75 6.10 111985000

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)
(2306, 5) 2007-01-03 2016-03-01
MSFT IBM SBUX AAPL GSPC
Date
2007-01-03 23.950705 80.517962 16.149666 11.086612 1416.599976
2007-01-04 23.910599 81.378851 16.167992 11.332687 1418.339966
2007-01-05 23.774242 80.642129 16.099269 11.251984 1409.709961
pair = s[["AAPL", "GSPC"]]
growth = pair / pair.iloc[0] * 100
growth.iloc[-1].round(1)
AAPL    906.8
GSPC    139.7
Name: 2016-03-01 00:00:00, dtype: float64
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)")
No description has been provided for this image
yearly = pair.resample("YE").last().pct_change() * 100
yearly.dropna().round(1)
AAPL GSPC
Date
2008-12-31 -56.9 -38.5
2009-12-31 146.9 23.5
2010-12-31 53.1 12.8
2011-12-31 25.6 -0.0
2012-12-31 32.6 13.4
2013-12-31 8.1 29.6
2014-12-31 40.6 11.4
2015-12-31 -3.0 -0.7
2016-12-31 -4.0 -3.2

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))
5 9

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)
close ret volume
Date
2015-08-24 103.12 -2.50 162206300
2016-01-27 93.42 -6.57 133369700
2015-08-21 105.76 -6.12 128275500
2015-08-04 114.64 -3.21 124138600
2015-04-28 130.56 -1.58 118924000
df["abs_ret"] = df["ret"].abs()
r = df["volume"].corr(df["abs_ret"])
print(round(r, 2))
0.65
busy = df["volume"] > df["volume"].quantile(0.9)
df.groupby(busy)["abs_ret"].agg(["count", "mean"]).round(2)
count mean
volume
False 454 0.92
True 51 2.54
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")
No description has been provided for this image
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)
(506, 11)
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")
Busy days move 2.8 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#

  1. Repeat the crossover test with the 50 and 200 day averages.
  2. Find Microsoft's deepest drawdown in stocks.csv.
  3. 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.