How to compute the golden 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 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 = 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 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:
            list_golden_cross_ts.append(idx)
            first_golden_cross = False
    else:
        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")
    
axes.legend()
fig.tight_layout()
plt.savefig("golden_cross_python.png")
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.
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.