How to compute the golden cross with Pandas in Python

2 min

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

It is often known as a trigger point for a trend reversal.

It is approximative of course, no one can truly know the moment when a bearish trend turns into a bullish trend.

Furthermore, the lagging effect is a bit annoying and past predictions most often fail to predict the future.

However, it is a widely used indicator for technical analysis.

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 viz library
import matplotlib.pyplot as plt

# We download the stock price from start date until end date
df ="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 50 SMA > 200 SMA
df["golden_cross_signal"] = df.apply(lambda row: 1 if row[f"50_sma"] > row[f"200_sma"]  else 0, axis=1)

# To store when our golden cross are happening
list_golden_cross_ts = []
first_golden_cross = False

# We take the date where the first 50 SMA > 200 SMA appears
for idx, each in df["golden_cross"].iteritems():
    if each == 1:
        # If its the first golden cross we see we add the timestamp
        if first_golden_cross:
            first_golden_cross = False
        first_golden_cross = True

# We plot our prices / SMAs and Golden 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_golden_cross_ts:
    axes.axvline(x=each, label="Golden Cross", c="yellow")
Here is how to compute the golden cross with Pandas in Python

How to compute the golden cross in Python

Here you are! You now know how to compute the golden 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.