How to Backtest a Crossover Strategy in Python
16 September, 2024
21
21
0
Contributors
Crossover strategies are popular in technical analysis for trading financial instruments.
Crossover strategies are popular in technical analysis for trading financial instruments. They involve the crossing of two moving averages, which can signal a potential change in the trend of the asset being analyzed.
Introduction
Crossover strategies are popular in technical analysis for trading financial instruments. They involve the crossing of two moving averages, which can signal a potential change in the trend of the asset being analyzed.
Background
The goal of the strategy is to create a very basic crossover strategy where we use a fast moving simple moving average (SMA) and a slow moving simple moving average. Buy when the fast line crosses above the slow line, and sell when it crosses below.
Using the code
A brief description of how to use the article or code. The class names, the methods and properties, any tricks or tips.
Blocks of code should be set as style "Formatted" like this:
C++
Shrink ▲
//
from backtester.data_handler import DataHandler
from backtester.backtester import Backtester
from backtester.strategies import Strategy
symbol = "AAPL,MSFT"
start_date = "2023-01-01"
end_date = "2023-12-31"
data = DataHandler(
symbol=symbol, start_date=start_date, end_date=end_date
).load_data()
strategy = Strategy(
indicators={
"sma_20": lambda row: row["close"].rolling(window=20).mean(),
"sma_60": lambda row: row["close"].rolling(window=60).mean(),
},
signal_logic=lambda row: 1 if row["sma_20"] > row["sma_60"] else -1,
)
data = strategy.generate_signals(data)
backtester = Backtester()
backtester.backtest(data)
backtester.calculate_performance()
//
Output Results:
Final Portfolio Value: $11,804.58
Total Return: 18.05%
Annualized Return: 18.20%
Annualized Volatility: 13.06%
Sharpe Ratio: 1.39
Sortino Ratio: 2.06
Maximum Drawdown: -12.07%