Algorithmic Trading & Indicators
Beginner
200 EMA & 50 EMA Golden Cross Strategy in Python (Single-Trade Flip)
Automate the Golden Cross and Death Cross trading strategy in Python using Pandas. Includes 50/200 EMA calculation and non-repainting signal logic.
#pandas#numpy#yfinance
Problem Statement
Beginners often fire duplicate buy signals on every candle where 50 EMA stays above 200 EMA. This script detects state transitions to fire strictly once on the crossover candle.
Formula / Core Logic
Multiplier k = 2 / (Period + 1)
Golden Cross (Signal = 1) occurs when EMA_50 crosses above EMA_200.
Installation
pip install pandas numpy yfinance
python-script-200-ema-50-ema-crossover-strategy.py
import pandas as pd
import numpy as np
def ema_crossover(df, fast=50, slow=200):
df = df.copy()
df['EMA_Fast'] = df['Close'].ewm(span=fast, adjust=False).mean()
df['EMA_Slow'] = df['Close'].ewm(span=slow, adjust=False).mean()
df['Regime'] = np.where(df['EMA_Fast'] > df['EMA_Slow'], 1, -1)
df['Signal'] = np.where((df['Regime'] == 1) & (df['Regime'].shift(1) == -1), 1, np.where((df['Regime'] == -1) & (df['Regime'].shift(1) == 1), -1, 0))
return df
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: How to filter sideways markets in EMA crossovers?
Combine the crossover with an ADX > 25 filter or confirm that price is trading above intraday VWAP.