Tags: stop-loss, ema, trend-analysis, get-started

EMA cross over strategy with stop loss#

This is an example notebook how to create and run backtests where stop loss is being used. It is based on PancakeSwap EMA example.

  • We trade on BNB/BUSD pair using stop loss.

  • We define stop loss related variables stop_loss_time_bucket and stop_loss_pct.

  • Stop loss is set to 95% when a position is opened with open_1x_long

  • We pass stop_loss_time_bucket to load_pair_data_for_single_exchange when creating our trading universe. This will load more granular candle data that is used to simulate real-time stop loss triggers. In our case we use 1h candles to simulate stop loss, whereas strategy itself is using 4h candles. Stop loss trades happen outside normal decide_trades triggers. This all is baked in to the backtesting engine and you do not need to worry about it all.

  • Although stop loss is the most common special order feature in volatile crypto markets, you can use this to do take profit orders for strategies as well. TODO: Take profit trades do not have an example notebook yet.

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
trading_strategy_engine_version = "0.1"

# What kind of strategy we are running.
# This tells we are going to use
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.pancakeswap_busd

# How often the strategy performs the decide_trades cycle.
# We do it for every 16h.
trading_strategy_cycle = CycleDuration.cycle_16h

# Strategy keeps its cash in BUSD
reserve_currency = ReserveCurrency.busd

# Time bucket for our candles
candle_time_bucket = TimeBucket.h4

# We use more granular hourly price feed to
# to check for the stop loss / take profit conditions
stop_loss_time_bucket = TimeBucket.h1

# Which chain we are trading
chain_id = ChainId.bsc

# Which exchange we are trading on.
exchange_slug = "pancakeswap-v2"

# Which trading pair we are trading
trading_pair_ticker = ("WBNB", "BUSD")

# How much of the cash to put on a single trade
position_size = 0.10

#
# Strategy thinking specific parameter
#

batch_size = 90

slow_ema_candle_count = 15

fast_ema_candle_count = 5

# Set stop loss to 5% of the position
stop_loss_pct = 0.95


# 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(2021, 6, 1)

end_at = datetime.datetime(2022, 1, 1)

# Start with 10,000 USD
initial_deposit = 10_000


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.

[2]:
from typing import List, Dict

from pandas_ta.overlap import ema

from tradeexecutor.state.visualisation import PlotKind
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


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 to do next

    - 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 = candles["close"]

    # Calculate exponential moving averages based on slow and fast sample numbers.
    slow_ema_series = ema(close, length=slow_ema_candle_count)
    fast_ema_series = ema(close, length=fast_ema_candle_count)

    if slow_ema_series is None or fast_ema_series is None:
        # Cannot calculate EMA, because
        # not enough samples in backtesting
        return []

    slow_ema = slow_ema_series.iloc[-1]
    fast_ema = fast_ema_series.iloc[-1]

    # Get the last close price from close time series
    # that's Pandas's Series object
    # https://pandas.pydata.org/docs/reference/api/pandas.Series.iat.html
    current_price = close.iloc[-1]

    # List of any trades we decide on this cycle.
    # Because the strategy is simple, there can be
    # only zero (do nothing) or 1 (open or close) trades
    # decides
    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
        # Check for entry condition

        # Entry condition:
        # Close price is higher than the slow EMA
        if current_price >= slow_ema:
            buy_amount = cash * position_size
            trades += position_manager.open_1x_long(pair, buy_amount, stop_loss_pct=stop_loss_pct)

    else:
        # We do have an open position
        # check for exit condition

        # Exit condition:
        # Fast EMA crosses slow EMA
        if fast_ema >= slow_ema and current_price < slow_ema:
            trades += position_manager.close_all()
            assert len(trades) == 1

    # 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, "Slow EMA", PlotKind.technical_indicator_on_price, slow_ema, colour="darkblue")
    visualisation.plot_indicator(timestamp, "Fast EMA", PlotKind.technical_indicator_on_price, fast_ema, colour="#003300")

    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 tradeexecutor.strategy.universe_model import UniverseOptions
from tradeexecutor.strategy.trading_strategy_universe import TradingStrategyUniverse, \
    load_pair_data_for_single_exchange
from tradeexecutor.strategy.execution_context import ExecutionContext
from tradingstrategy.client import Client
import datetime

def create_trading_universe(
        ts: datetime.datetime,
        client: Client,
        execution_context: ExecutionContext,
        universe_options: UniverseOptions,
) -> TradingStrategyUniverse:
    """Creates the trading universe where the strategy trades.

    If `execution_context.live_trading` is true then this function is called for
    every execution cycle. If we are backtesting, then this function is
    called only once at the start of backtesting and the `decide_trades`
    need to deal with new and deprecated trading pairs.

    As we are only trading a single pair, load data for the single pair only.

    :param ts:
        The timestamp of the trading cycle. For live trading,
        `create_trading_universe` is called on every cycle.
        For backtesting, it is only called at the start

    :param client:
        Trading Strategy Python client instance.

    :param execution_context:
        Information how the strategy is executed. E.g.
        if we are live trading or not.

    :return:
        This function must return :py:class:`TradingStrategyUniverse` instance
        filled with the data for exchanges, pairs and candles needed to decide trades.
        The trading universe also contains information about the reserve asset,
        usually stablecoin, we use for the strategy.
    """

    # Load all datas we can get for our candle time bucket
    dataset = load_pair_data_for_single_exchange(
        client,
        execution_context,
        candle_time_bucket,
        chain_id,
        exchange_slug,
        [trading_pair_ticker],
        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,
        chain_id,
        exchange_slug,
        trading_pair_ticker[0],
        trading_pair_ticker[1],
    )

    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#

  • Load data from the server.

  • Calls create_trading_universe and prints out how much data we have loaded_

[5]:
from tradeexecutor.strategy.execution_context import ExecutionMode

universe = create_trading_universe(
    end_at,
    client,
    ExecutionContext(mode=ExecutionMode.data_preload),
    UniverseOptions(),
)

print(f"We loaded {universe.universe.candles.get_candle_count():,} candles.")
We loaded 5,353 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="BNB/USD EMA crossover example",
    start_at=start_at,
    end_at=end_at,
    client=client,
    cycle_duration=trading_strategy_cycle,
    decide_trades=decide_trades,
    universe=universe,
    initial_deposit=initial_deposit,
    reserve_currency=ReserveCurrency.busd,
    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 62 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: 31
Trades made: 62
[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)

figure.show()

Equity curve and drawdown#

Visualise equity curve and related performnace over time.

  • Returns

  • Drawdown

  • Daily returns

[9]:
# Set Jupyter Notebook output mode parameters
# Used to avoid warnings
from tradeexecutor.backtest.notebook import setup_charting_and_output
setup_charting_and_output()

# Needed to improve the resolution of matplotlib chart used here
%config InlineBackend.figure_format = 'svg'

from tradeexecutor.visual.equity_curve import calculate_equity_curve, calculate_returns
from tradeexecutor.visual.equity_curve import visualise_equity_curve

curve = calculate_equity_curve(state)
returns = calculate_returns(curve)
visualise_equity_curve(returns)
[9]:
../../_images/programming_strategy-examples_pancakeswap-ema-stop-loss_18_0.svg

Returns monthly breakdown#

  • Monthly returns

  • Best day/week/month/year

[10]:
from tradeexecutor.visual.equity_curve import visualise_returns_over_time

visualise_returns_over_time(returns)
[10]:
../../_images/programming_strategy-examples_pancakeswap-ema-stop-loss_20_0.svg

Benchmarking the strategy performance#

Here we benchmark the strategy performance against some baseline scenarios.

  • Buy and hold US dollar

  • Buy and hold the underlying trading pair base asset

[11]:
close = universe.universe.candles.get_single_pair_data()["close"]
[12]:
from tradeexecutor.visual.benchmark import visualise_benchmark

traded_pair = universe.universe.pairs.get_single()

fig = visualise_benchmark(
    state.name,
    portfolio_statistics=state.stats.portfolio,
    all_cash=state.portfolio.get_initial_deposit(),
    buy_and_hold_asset_name=traded_pair.base_token_symbol,
    buy_and_hold_price_series=universe.universe.candles.get_single_pair_data()["close"],
    start_at=start_at,
    end_at=end_at
)

fig.show()
[ ]:

Analysing the strategy success#

Here we calculate statistics on how well the strategy performed.

  • Won/lost trades

  • Timeline of taken positions with color coding of trade performance

[13]:
from tradeexecutor.analysis.trade_analyser import build_trade_analysis

analysis = build_trade_analysis(state.portfolio)

Strategy summary#

Overview of strategy performance

[14]:
from IPython.core.display_functions import display

summary = analysis.calculate_summary_statistics(candle_time_bucket, state)

with pd.option_context("display.max_row", None):
    summary.display()
Returns
Annualised return % 4.50%
Lifetime return % 2.60%
Realised PnL $259.98
Trade period 210 days 16 hours
Holdings
Total assets $10,259.98
Cash left $10,259.98
Open position value $0.00
Open positions 0
Winning Losing Total
Closed Positions
Number of positions 13 18 31
% of total 41.94% 58.06% 100.00%
Average PnL % 9.68% -5.46% 0.89%
Median PnL % 3.01% -5.97% -1.29%
Biggest PnL % 39.84% -12.95% -
Average duration 41 bars 20 bars 29 bars
Max consecutive streak 3 4 -
Max runup / drawdown 7.52% -4.34% -
Stop losses Take profits
Position Exits
Triggered exits 13 0
Percent winning 0.00% -
Percent losing 100.00% -
Percent of total 41.94% 0.00%
Risk Analysis
Biggest realized risk 0.52%
Average realized risk -0.55%
Max pullback of capital -2.54%
Sharpe Ratio 61.91%
Sortino Ratio 94.19%
Profit Factor 109.11%

Performance metrics#

Here is an example how to use Quantstats library to calculate the tearsheet metrics for the strategy with advanced metrics. The metrics include popular risk-adjusted return comparison metrics.

This includes metrics like:

  • Sharpe

  • Sortino

  • Max drawdown

Note: These metrics are based on equity curve and returns. Analysis here does not go down to the level of an individual trade or a position. Any consecutive wins and losses are measured in days, not in trade or candle counts.

[15]:
from tradeexecutor.visual.equity_curve import calculate_equity_curve, calculate_returns
from tradeexecutor.analysis.advanced_metrics import visualise_advanced_metrics, AdvancedMetricsMode

equity = calculate_equity_curve(state)
returns = calculate_returns(equity)
metrics = visualise_advanced_metrics(returns, mode=AdvancedMetricsMode.full)

with pd.option_context("display.max_row", None):
    display(metrics)
Strategy
Start Period 2021-05-31
End Period 2021-12-31
Risk-Free Rate 0.0%
Time in Market 81.0%
Cumulative Return 2.65%
CAGR﹪ 4.56%
Sharpe 0.52
Prob. Sharpe Ratio 68.73%
Smart Sharpe 0.5
Sortino 0.78
Smart Sortino 0.75
Sortino/√2 0.55
Smart Sortino/√2 0.53
Omega 1.09
Max Drawdown -4.34%
Longest DD Days 78
Volatility (ann.) 6.07%
Calmar 1.05
Skew 0.27
Kurtosis 4.2
Expected Daily 0.01%
Expected Monthly 0.33%
Expected Yearly 2.65%
Kelly Criterion 3.81%
Risk of Ruin 0.0%
Daily Value-at-Risk -0.51%
Expected Shortfall (cVaR) -0.51%
Max Consecutive Wins 6
Max Consecutive Losses 5
Gain/Pain Ratio 0.11
Gain/Pain (1M) 0.53
Payoff Ratio 1.3
Profit Factor 1.09
Common Sense Ratio 1.25
CPC Index 0.65
Tail Ratio 1.14
Outlier Win Ratio 4.61
Outlier Loss Ratio 4.26
MTD -1.36%
3M 2.83%
6M 4.04%
YTD 2.65%
1Y 2.65%
3Y (ann.) 4.56%
5Y (ann.) 4.56%
10Y (ann.) 4.56%
All-time (ann.) 4.56%
Best Day 1.52%
Worst Day -1.3%
Best Month 3.76%
Worst Month -2.05%
Best Year 2.65%
Worst Year 2.65%
Avg. Drawdown -2.19%
Avg. Drawdown Days 34
Recovery Factor 0.61
Ulcer Index 0.03
Serenity Index 0.08
Avg. Up Month 2.02%
Avg. Down Month -1.77%
Win Days 45.56%
Win Month 57.14%
Win Quarter 66.67%
Win Year 100.0%

Position and trade timeline#

Display all positions and how much profit they made.

[16]:
from tradeexecutor.analysis.trade_analyser import expand_timeline

timeline = analysis.create_timeline()

expanded_timeline, apply_styles = expand_timeline(
        universe.universe.exchanges,
        universe.universe.pairs,
        timeline)

# Do not truncate the row output
with pd.option_context("display.max_row", None):
    display(apply_styles(expanded_timeline))

Remarks Type Opened at Duration Exchange Base asset Quote asset Position max value PnL USD PnL % Open mid price USD Close mid price USD Trade count LP fees
SL Long 2021-05-31 11 days 11 hours PancakeSwap v2 WBNB BUSD $1,000.00 $-56.17 -5.62% $347.410409 $327.895530 2 $4.87
SL Long 2021-06-14 2 days 17 hours PancakeSwap v2 WBNB BUSD $994.38 $-61.30 -6.16% $367.453669 $344.803131 2 $4.82
SL Long 2021-06-17 1 days 7 hours PancakeSwap v2 WBNB BUSD $988.25 $-65.44 -6.62% $362.124298 $338.144864 2 $4.78
Long 2021-06-23 2 days PancakeSwap v2 WBNB BUSD $981.71 $16.30 1.66% $291.126932 $295.960697 2 $4.96
Long 2021-06-28 7 days 8 hours PancakeSwap v2 WBNB BUSD $983.34 $27.49 2.80% $291.107056 $299.244760 2 $4.99
SL Long 2021-07-06 13 days 13 hours PancakeSwap v2 WBNB BUSD $986.09 $-70.57 -7.16% $303.592229 $281.864219 2 $4.76
Long 2021-07-21 6 days PancakeSwap v2 WBNB BUSD $979.03 $76.01 7.76% $281.103343 $302.928082 2 $5.09
Long 2021-07-28 2 days 16 hours PancakeSwap v2 WBNB BUSD $986.63 $-10.54 -1.07% $314.068716 $310.712694 2 $4.91
Long 2021-07-31 2 days 16 hours PancakeSwap v2 WBNB BUSD $985.58 $29.68 3.01% $320.402097 $330.052144 2 $5.01
Long 2021-08-05 20 days PancakeSwap v2 WBNB BUSD $988.55 $393.82 39.84% $335.930303 $469.760403 2 $5.94
Long 2021-08-25 16 hours PancakeSwap v2 WBNB BUSD $1,027.93 $-45.33 -4.41% $504.104050 $481.872026 2 $5.03
Long 2021-08-27 1 days 8 hours PancakeSwap v2 WBNB BUSD $1,023.39 $-13.18 -1.29% $490.480501 $484.165021 2 $5.09
SL Long 2021-09-02 5 days 15 hours PancakeSwap v2 WBNB BUSD $1,022.08 $-132.40 -12.95% $490.290089 $426.779574 2 $4.78
SL Long 2021-09-12 16 hours PancakeSwap v2 WBNB BUSD $1,008.84 $-63.58 -6.30% $418.700474 $392.314311 2 $4.89
Long 2021-09-14 2 days 16 hours PancakeSwap v2 WBNB BUSD $1,002.48 $15.71 1.57% $410.275108 $416.703772 2 $5.06
SL Long 2021-09-22 1 days 18 hours PancakeSwap v2 WBNB BUSD $1,004.05 $-64.79 -6.45% $370.382371 $346.483247 2 $4.86
SL Long 2021-09-27 1 days 10 hours PancakeSwap v2 WBNB BUSD $997.57 $-57.57 -5.77% $350.933113 $330.680962 2 $4.85
Long 2021-09-29 5 days 8 hours PancakeSwap v2 WBNB BUSD $991.81 $211.11 21.29% $345.338743 $418.846512 2 $5.49
SL Long 2021-10-05 5 days 14 hours PancakeSwap v2 WBNB BUSD $1,012.93 $-67.29 -6.64% $434.383414 $405.525634 2 $4.90
Long 2021-10-12 4 days PancakeSwap v2 WBNB BUSD $1,006.20 $77.79 7.73% $433.200612 $466.690179 2 $5.23
Long 2021-10-18 8 days 16 hours PancakeSwap v2 WBNB BUSD $1,013.98 $22.74 2.24% $470.968497 $481.529337 2 $5.13
Long 2021-10-28 12 days PancakeSwap v2 WBNB BUSD $1,016.25 $316.80 31.17% $486.977493 $638.783670 2 $5.88
SL Long 2021-11-10 14 hours PancakeSwap v2 WBNB BUSD $1,047.93 $-81.66 -7.79% $644.800017 $594.552646 2 $5.04
Long 2021-11-13 2 days 16 hours PancakeSwap v2 WBNB BUSD $1,039.76 $11.69 1.12% $628.458162 $635.524483 2 $5.23
Long 2021-11-19 6 days 16 hours PancakeSwap v2 WBNB BUSD $1,040.93 $49.50 4.76% $578.807010 $606.329578 2 $5.34
SL Long 2021-11-27 13 hours PancakeSwap v2 WBNB BUSD $1,045.88 $-58.44 -5.59% $610.200605 $576.102552 2 $5.09
SL Long 2021-11-29 5 days 4 hours PancakeSwap v2 WBNB BUSD $1,040.04 $-67.60 -6.50% $611.834604 $572.067640 2 $5.04
Long 2021-12-07 2 days 16 hours PancakeSwap v2 WBNB BUSD $1,033.28 $-20.44 -1.98% $589.098986 $577.447081 2 $5.12
SL Long 2021-12-12 1 days 7 hours PancakeSwap v2 WBNB BUSD $1,031.23 $-57.63 -5.59% $567.745867 $536.019452 2 $5.02
Long 2021-12-16 10 days PancakeSwap v2 WBNB BUSD $1,025.47 $9.61 0.94% $534.409175 $539.416630 2 $5.16
Long 2021-12-27 1 days 8 hours PancakeSwap v2 WBNB BUSD $1,026.43 $-4.34 -0.42% $547.446509 $545.130514 2 $5.13

Finishing notes#

Print out a line to signal the notebook finished the execution successfully.

[17]:
print("All ok")
All ok