How to compute the death cross with Pandas in Python

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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.
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.