Python for Algorithmic Trading: Historical Data Ingestion & Technical Momentum Strategies
What You Will Master in This Tutorial
- Fetch clean historical stock data for equities and ETFs using modern Python APIs
- Calculate vectorized indicators: Exponential Moving Averages (EMA 20/50), MACD, and RSI
- Generate deterministic buy and sell signals without lookahead bias
- Compute key risk metrics: Maximum Drawdown, Sharpe Ratio, and CAGR
PYTHON
import pandas as pd
import numpy as np
def calculate_momentum_strategy(df: pd.DataFrame, fast: int = 20, slow: int = 50) -> pd.DataFrame:
"""
Computes EMA crossover signals and backtests portfolio equity curve.
"""
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()
# Generate position signal (1 for Long, 0 for Cash)
df['Signal'] = np.where(df['EMA_Fast'] > df['EMA_Slow'], 1, 0)
df['Position'] = df['Signal'].shift(1) # Avoid lookahead bias
# Daily logarithmic returns
df['Market_Return'] = np.log(df['Close'] / df['Close'].shift(1))
df['Strategy_Return'] = df['Position'] * df['Market_Return']
df['Cumulative_Market'] = df['Market_Return'].cumsum().apply(np.exp)
df['Cumulative_Strategy'] = df['Strategy_Return'].cumsum().apply(np.exp)
return df
Advertisement
View Blueprints β
Verified Partner
Quantitative Trading Systems & 30 AI Business Blueprints
Build predictable monthly recurring revenue with retainers & automated bots.
Frequently Asked Questions
Why is avoiding lookahead bias critical in backtesting?
Lookahead bias occurs when an algorithm makes a trading decision based on data that wouldn't have been available until the candle closed. Shifting signals forward by 1 period guarantees realistic execution prices.