Skip to content

Examples

Interactive example

The chart below is produced by the strategy on the Strategy tab, run against the bundled daily GOOG dataset - no data files and no API keys. The Results tab shows the exact performance metrics from that run. Scroll to zoom, drag to pan, and toggle series from the legend.

from tradetropy import BacktestEngine, Strategy
from tradetropy.datasets import load_goog_1d
from tradetropy.signal import Signal
from tradetropy.ta import SMA


class SmaCross(Strategy):
    """Go long on a fast/slow SMA crossover, flatten on the crossunder."""

    def init(self):
        self.goog = self.subscribe_ohlc('GOOG', '1d', window_size=200)
        self.fast = self.add_indicator(self.goog.close, SMA(10))
        self.slow = self.add_indicator(self.goog.close, SMA(30))
        self.signal = Signal('partial')

    def on_data(self):
        if self.signal.crossover(self.fast, self.slow):
            if not self.sesh.positions('GOOG'):
                self.sesh.buy('GOOG', volume=10)
        elif self.signal.crossunder(self.fast, self.slow):
            for pos in self.sesh.positions('GOOG'):
                self.sesh.position_close(pos.ticket)


bt = BacktestEngine.by_klines(SmaCross(), data=(load_goog_1d(),))
bt.run()
print(bt.stats)
Start                     2020-01-02 00:00:00+00:00
End                       2021-03-11 00:00:00+00:00
Duration                          434 days 00:00:00
Exposure Time [%]                           46.7742
Equity Final [$]                            10237.2
Equity Peak [$]                             10244.0
Return [%]                                    2.372
Return (Ann.) [%]                            1.9925
Volatility (Ann.) [%]                        1.9296
Sharpe Ratio                                 1.0336
Sortino Ratio                                 1.649
Calmar Ratio                                  1.448
Max. Drawdown [%]                           -1.3761
Avg. Drawdown [%]                            -0.264
Max. Drawdown Duration             90 days 00:00:00
Avg. Drawdown Duration      14 days 18:56:50.526000
# Trades                                          4
# Trades Long                                     4
# Trades Short                                    0
Win Rate [%]                                   75.0
Best Trade [%]                              12.8583
Worst Trade [%]                             -5.1689
Avg. Trade [%]                               4.7942
Max. Trade Duration                76 days 00:00:00
Avg. Trade Duration                50 days 18:00:00
Profit Factor                                4.2129
Expectancy [%]                               4.7942
SQN                                           1.284
Total Commissions [$]                           0.0

More runnable scripts

Runnable scripts live in the examples/ directory. They all use the bundled datasets, so they run with no data files or API keys:

python examples/sma_cross.py
Script What it shows
sma_cross.py A basic SMA-crossover backtest on BTCUSD 1-minute candles.
multi_timeframe.py Subscribing to 1m/5m/15m of one symbol; the engine resamples internally.
multi_symbol.py A multi-symbol backtest (BTCUSD + ADAUSD) side by side.
volume_profile.py Trading the developing Volume Profile value area.
large_trades.py Order flow: following large trades on MESU26 futures ticks.
orderflow_l2.py L2 Deep Trades over a recorded order book via ReplayEngine.
live_pool_demo.py Running several live strategies under LivePool (network-free).

The order-flow L2 script opens an interactive replay chart in the browser; the others print performance metrics to the console.