Momentum Crossover Strategy#
Strategy description#
We use RSI as an indicator of momentum and slow ema and fast ema to indicate trend direction
Buy signal#
The short-term SMA crosses above the long-term SMA. This crossover signals a potential upward trend.
The RSI crosses below 30 and then moves back above it. This suggests that the asset might be moving out of an oversold condition and starting to gain upward momentum.
Sell signal#
The short-term SMA crosses below the long-term SMA. This crossover signals a potential downward trend.
The RSI crosses above 70 and then moves back below it. This suggests that the asset might be moving out of an overbought condition and starting to lose upward momentum.
For both the buy and sell signals, the conditions should be ideally occur around the same time for a stronger signal.
Set up#
Set up the parameters used in in this strategy backtest study.
Backtested blockchain, exchange and trading pair
Backtesting period
Strategy parameters for EMA crossovers
[1]:
import datetime
import pandas as pd
from tradingstrategy.chain import ChainId
from tradingstrategy.timebucket import TimeBucket
from tradeexecutor.strategy.cycle import CycleDuration
from tradeexecutor.strategy.strategy_module import StrategyType, TradeRouting, ReserveCurrency
# Tell what trade execution engine version this strategy needs to use
# NOTE: this setting has currently no effect
TRADING_STRATEGY_TYPE_ENGINE_VERSION = "0.1"
# What kind of strategy we are running.
# This tells we are going to use
# NOTE: this setting has currently no effect
TRADING_STRATEGY_TYPE = StrategyType.managed_positions
# How our trades are routed.
# PancakeSwap basic routing supports two way trades with BUSD
# and three way trades with BUSD-BNB hop.
TRADE_ROUTING = TradeRouting.uniswap_v2_usdc
# How often the strategy performs the decide_trades cycle.
# We do it for every 4h.
TRADING_STRATEGY_CYCLE = CycleDuration.cycle_1h
# Strategy keeps its cash in USDC
RESERVE_CURRENCY = ReserveCurrency.usdc
# Time bucket for our candles
CANDLE_TIME_BUCKET = TimeBucket.h1
# Which trading pair we are trading
TRADING_PAIR = (ChainId.ethereum, "uniswap-v2", "WETH", "USDT", 0.0030) # Ether-Tether USD https://tradingstrategy.ai/trading-view/ethereum/uniswap-v2/eth-usdt
# How much of the cash to put on a single trade
POSITION_SIZE = 0.70
#
# Strategy thinking specific parameter
#
BATCH_SIZE = 50
SLOW_EMA_CANDLE_COUNT = 15
FAST_EMA_CANDLE_COUNT = 5
RSI_CANDLE_COUNT = 5
LOOKBACK = 5
RSI_LOWER_THRESHOLD = 30
RSI_UPPER_THRESHOLD = 70
# Range of backtesting and synthetic data generation.
# Because we are using synthetic data actual dates do not really matter -
# only the duration
START_AT = datetime.datetime(2022, 1, 1)
END_AT = datetime.datetime(2023, 4,1)
# Start with 10,000 USD
INITIAL_DEPOSIT = 10_000
# If the price drops 5 we trigger a stop loss
STOP_LOSS_PCT = 0.95
STOP_LOSS_TIME_BUCKET = TimeBucket.h1
Strategy logic and trade decisions#
decide_trades
function decide what trades to take.In this example, we calculate two exponential moving averages (EMAs) and make decisions based on those.
Indicators#
Note how we also make use of detached and overlayed technical indicators, so that the price chart is not overcrowded
[2]:
from typing import List, Dict
from pandas_ta.overlap import ema
from pandas_ta import rsi
from tradeexecutor.state.visualisation import PlotKind, PlotShape
from tradeexecutor.utils.crossover import contains_cross_over, contains_cross_under
from tradeexecutor.state.trade import TradeExecution
from tradeexecutor.strategy.pricing_model import PricingModel
from tradeexecutor.strategy.pandas_trader.position_manager import PositionManager
from tradeexecutor.state.state import State
from tradingstrategy.universe import Universe
from tradeexecutor.strategy.pandas_trader.position_manager import PositionManager
def decide_trades(
timestamp: pd.Timestamp,
universe: Universe,
state: State,
pricing_model: PricingModel,
cycle_debug_data: Dict) -> List[TradeExecution]:
"""The brain function to decide the trades on each trading strategy cycle.
- Reads incoming execution state (positions, past trades)
- Reads the current universe (candles)
- Decides what trades to do next, if any, at current timestamp.
- Outputs strategy thinking for visualisation and debug messages
:param timestamp:
The Pandas timestamp object for this cycle. Matches
TRADING_STRATEGY_CYCLE division.
Always truncated to the zero seconds and minutes, never a real-time clock.
:param universe:
Trading universe that was constructed earlier.
:param state:
The current trade execution state.
Contains current open positions and all previously executed trades, plus output
for statistics, visualisation and diangnostics of the strategy.
:param pricing_model:
Pricing model can tell the buy/sell price of the particular asset at a particular moment.
:param cycle_debug_data:
Python dictionary for various debug variables you can read or set, specific to this trade cycle.
This data is discarded at the end of the trade cycle.
:return:
List of trade instructions in the form of :py:class:`TradeExecution` instances.
The trades can be generated using `position_manager` but strategy could also hand craft its trades.
"""
# The pair we are trading
pair = universe.pairs.get_single()
# How much cash we have in the hand
cash = state.portfolio.get_current_cash()
# Get OHLCV candles for our trading pair as Pandas Dataframe.
# We could have candles for multiple trading pairs in a different strategy,
# but this strategy only operates on single pair candle.
# We also limit our sample size to N latest candles to speed up calculations.
candles: pd.DataFrame = universe.candles.get_single_pair_data(timestamp, sample_count=BATCH_SIZE)
# We have data for open, high, close, etc.
# We only operate using candle close values in this strategy.
close_prices = candles["close"]
# Calculate exponential moving averages based on slow and fast sample numbers.
slow_ema_series = ema(close_prices, length=SLOW_EMA_CANDLE_COUNT)
fast_ema_series = ema(close_prices, length=FAST_EMA_CANDLE_COUNT)
rsi_series = rsi(close_prices, length=RSI_CANDLE_COUNT)
slow_ema_latest = slow_ema_series.iloc[-1]
fast_ema_latest = fast_ema_series.iloc[-1]
price_latest = close_prices.iloc[-1]
rsi_latest = rsi_series.iloc[-1]
trades = []
# Create a position manager helper class that allows us easily to create
# opening/closing trades for different positions
position_manager = PositionManager(timestamp, universe, state, pricing_model)
if not position_manager.is_any_open():
# No open positions, decide if BUY in this cycle.
# Buy Signal:
#
# 1. The short-term SMA crosses above the long-term SMA. This crossover signals a potential upward trend.
# 2. The RSI crosses below 30 and then moves back above it. This suggests that the asset might be moving out of an oversold condition and starting to gain upward momentum.
#
# Both conditions should occur around the same time for a stronger buy signal.
crossover_ema, ema_crossover_index = contains_cross_over(
fast_ema_series,
slow_ema_series,
lookback_period=LOOKBACK,
must_return_index=True
)
crossunder_rsi_30, rsi_crossunder_index = contains_cross_under(
rsi_series,
pd.Series([RSI_LOWER_THRESHOLD] * len(rsi_series)),
lookback_period=LOOKBACK,
must_return_index=True
)
crossover_rsi_30, rsi_crossover_index = contains_cross_over(
rsi_series,
pd.Series([RSI_LOWER_THRESHOLD] * len(rsi_series)),
lookback_period=LOOKBACK,
must_return_index=True
)
if (crossover_ema and crossunder_rsi_30 and crossover_rsi_30) \
and (ema_crossover_index == -1 or rsi_crossover_index == -1) \
and rsi_crossunder_index < rsi_crossover_index:
# Buy condition is met
buy_amount = cash * POSITION_SIZE
new_trades = position_manager.open_1x_long(
pair,
buy_amount,
stop_loss_pct=STOP_LOSS_PCT
)
trades.extend(new_trades)
assert len(new_trades) == 1
else:
# Sell Signal:
#
# 1. The short-term SMA crosses below the long-term SMA. This crossover signals a potential downward trend.
# 2. The RSI crosses above 70 and then moves back below it. This suggests that the asset might be moving out of an overbought condition and starting to lose upward momentum.
# Again, for a stronger sell signal, both conditions should ideally occur around the same time.
crossunder_ema, ema_crossunder_index = contains_cross_under(
fast_ema_series,
slow_ema_series,
lookback_period=LOOKBACK,
must_return_index=True
)
crossunder_rsi_70, rsi_crossunder_index = contains_cross_under(
rsi_series,
pd.Series([RSI_UPPER_THRESHOLD] * len(rsi_series)),
lookback_period=LOOKBACK,
must_return_index=True
)
crossover_rsi_70, rsi_crossover_index = contains_cross_over(
rsi_series,
pd.Series([RSI_UPPER_THRESHOLD] * len(rsi_series)),
lookback_period=LOOKBACK,
must_return_index=True
)
if (crossunder_ema and crossover_rsi_70 and crossunder_rsi_70) \
and (ema_crossunder_index == -1 or rsi_crossover_index == -1) \
and rsi_crossover_index < rsi_crossunder_index:
# sell condition is met
new_trades = position_manager.close_all()
assert len(new_trades) == 1
trades.extend(new_trades)
# Visualize strategy
# See available Plotly colours here
# https://community.plotly.com/t/plotly-colours-list/11730/3?u=miohtama
visualisation = state.visualisation
visualisation.plot_indicator(timestamp, "Fast EMA", PlotKind.technical_indicator_on_price, fast_ema_latest, colour="red")
visualisation.plot_indicator(timestamp, "Slow EMA", PlotKind.technical_indicator_on_price, slow_ema_latest, colour="green")
visualisation.plot_indicator(timestamp, "RSI", PlotKind.technical_indicator_detached, rsi_latest, colour="orange")
visualisation.plot_indicator(timestamp, "RSI 30", PlotKind.technical_indicator_overlay_on_detached, RSI_LOWER_THRESHOLD, colour="green", detached_overlay_name="RSI")
visualisation.plot_indicator(timestamp, "RSI 70", PlotKind.technical_indicator_overlay_on_detached, RSI_UPPER_THRESHOLD, colour="green", detached_overlay_name="RSI")
return trades
Defining the trading universe#
We create a trading universe with a single blockchain, exchange and trading pair. For the sake of easier understanding the code, we name this “Uniswap v2” like exchange with a single ETH-USDC trading pair.
The trading pair contains generated noise-like OHLCV trading data.
[3]:
from typing import Optional
from tradeexecutor.strategy.trading_strategy_universe import load_pair_data_for_single_exchange, TradingStrategyUniverse
from tradeexecutor.strategy.execution_context import ExecutionContext
from tradeexecutor.strategy.universe_model import UniverseOptions
from tradingstrategy.client import Client
import datetime
def create_single_pair_trading_universe(
ts: datetime.datetime,
client: Client,
execution_context: ExecutionContext,
universe_options: UniverseOptions,
) -> TradingStrategyUniverse:
dataset = load_pair_data_for_single_exchange(
client,
execution_context,
CANDLE_TIME_BUCKET,
pair_tickers=[TRADING_PAIR],
universe_options=universe_options,
stop_loss_time_bucket=STOP_LOSS_TIME_BUCKET
)
# Filter down to the single pair we are interested in
universe = TradingStrategyUniverse.create_single_pair_universe(
dataset,
pair=TRADING_PAIR,
)
return universe
Set up the market data client#
The Trading Strategy market data client is the Python library responsible for managing the data feeds needed to run the backtest.None
We set up the market data client with an API key.
If you do not have an API key yet, you can register one.
[4]:
from tradingstrategy.client import Client
client = Client.create_jupyter_client()
Started Trading Strategy in Jupyter notebook environment, configuration is stored in /home/alex/.tradingstrategy
Load data#
[5]:
from tradeexecutor.strategy.execution_context import ExecutionMode
from tradeexecutor.strategy.universe_model import UniverseOptions
universe = create_single_pair_trading_universe(
END_AT,
client,
ExecutionContext(mode=ExecutionMode.data_preload),
UniverseOptions()
)
print(f"We loaded {universe.universe.candles.get_candle_count():,} candles.")
We loaded 29,212 candles.
Run backtest#
Run backtest using giving trading universe and strategy function.
Running the backtest outputs
state
object that contains all the information on the backtesting position and trades.The trade execution engine will download the necessary datasets to run the backtest. The datasets may be large, several gigabytes.
[6]:
import logging
from tradeexecutor.backtest.backtest_runner import run_backtest_inline
state, universe, debug_dump = run_backtest_inline(
name="ETH/USDC fast and slow EMA example",
start_at=START_AT,
end_at=END_AT,
client=client,
cycle_duration=TRADING_STRATEGY_CYCLE,
decide_trades=decide_trades,
universe=universe,
# create_trading_universe=create_single_pair_trading_universe,
initial_deposit=INITIAL_DEPOSIT,
reserve_currency=RESERVE_CURRENCY,
trade_routing=TRADE_ROUTING,
log_level=logging.WARNING,
)
trade_count = len(list(state.portfolio.get_all_trades()))
print(f"Backtesting completed, backtested strategy made {trade_count} trades")
Backtesting completed, backtested strategy made 70 trades
Examine backtest results#
Examine state
that contains all actions the trade executor took.
We plot out a chart that shows - The price action - When the strategy made buys or sells
[7]:
print(f"Positions taken: {len(list(state.portfolio.get_all_positions()))}")
print(f"Trades made: {len(list(state.portfolio.get_all_trades()))}")
Positions taken: 35
Trades made: 70
[8]:
from tradeexecutor.visual.single_pair import visualise_single_pair
figure = visualise_single_pair(
state,
universe.universe.candles,
start_at=START_AT,
end_at=END_AT,
height = 1000,
)
figure.show()