How to compute the death cross with Pandas in Python

2 min

The death cross is a chart pattern that tells us when a short-term moving average (e.g. 50 SMA) crosses below a long-term moving average (e.g. 200 SMA).

It is the exact opposite to the golden cross and is often known as a trigger point for a trend reversal.

Here is how to compute it

# How to compute the golden cross in Python

# In order to get Apple stock price data from yahoo
import yfinance as yf

# Basic data manipulation libraries
import numpy as np
import pandas as pd

# Data visualisation library
import matplotlib.pyplot as plt

# We download the stock price from start date until end date
df = yf.download("AAPL", start="2018-01-01", end="2021-06-01")

# We compute our simple moving averages
df["50_sma"] = df["Adj Close"].rolling(50).mean()
df["200_sma"] = df["Adj Close"].rolling(200).mean()

# This is important so that we have both SMA starting a the same time.
df = df.dropna() 

# We compute our death cross
df["death_cross"] = df.apply(lambda row: 1 if row[f"50_sma"] < row[f"200_sma"]  else 0, axis=1)

# To store when our death crosses are happening
list_death_cross_ts = []
first_death_cross = False

# We take the date where the first 50 SMA < 200 SMA appears
for idx, each in df["death_cross"].iteritems():
    if each == 1:
        # If its the first death cross we see we add the timestamp
        if first_death_cross:
            list_death_cross_ts.append(idx)
            first_death_cross = False
    else:
        first_death_cross = True

# We plot our prices / SMAs and Death Cross dates
fig, axes = plt.subplots(1,1, figsize=(8,4))
df[["200_sma","50_sma","Adj Close"]].plot(figsize=(8,4), grid=True, title="SMA 50 vs SMA 200 on AAPL prices", ax=axes)

for each in list_death_cross_ts:
    axes.axvline(x=each, label="Death Cross", c="black")
    
axes.legend()
fig.tight_layout()
plt.savefig("death_cross_python.png")
Here is how to compute the death cross with Pandas in Python

Here is the result

Here you are! You now know how to compute the death cross with Pandas in Python.

More on financial analysis

If you want to know more about financial analysis in Python without headaches... check out the other articles I wrote by clicking just here:

Financial Analysis - The Python You Need
We gathered the only Python essentials that you will probably ever need.