Get up and running with RLX Backtester in minutes
Install RLX Backtester using pip. The package includes both the Python API and the pre-compiled Rust core.
pip install rlxbtPython Version
RLX requires Python 3.10 or higher. We recommend using a virtual environment.
Verify the installation:
import rlxbt
print(rlxbt.__version__)Let's run a simple backtest using pre-calculated signals. This is the fastest way to test RLX.
import pandas as pd
from rlxbt import TradingEngine
# Load your OHLCV data with signals
df = pd.read_csv("data.csv")
# Ensure timestamp is in Unix seconds
df['timestamp'] = pd.to_datetime(df['time']).astype('int64') // 10**9
# Create the trading engine
engine = TradingEngine(
initial_capital=100000.0,
commission=0.001, # 0.1% commission
slippage=0.0
)
# Run backtest (signal column: 1=Long, -1=Short, 0=Flat)
result = engine.run_with_signals(df, signal_column="signal")
# View results
print(f"Total Return: {result.total_return:.2%}")
print(f"Sharpe Ratio: {result.metrics['sharpe_ratio']:.2f}")
print(f"Max Drawdown: {result.metrics['max_drawdown']:.2%}")
print(f"Total Trades: {result.total_trades}")Performance
RLX processes ~4.5 million bars per second with full event-driven simulation.
RLX expects OHLCV data with specific columns. Here's the required format:
| Column | Type | Description |
|---|---|---|
| timestamp | int | Unix timestamp in seconds |
| open | float | Opening price |
| high | float | Highest price |
| low | float | Lowest price |
| close | float | Closing price |
| volume | float | Trading volume |
Example CSV:
timestamp,open,high,low,close,volume,signal
1609459200,29000.0,29500.0,28800.0,29200.0,1000.0,1
1609462800,29200.0,29300.0,29000.0,29100.0,800.0,1
1609466400,29100.0,29400.0,29050.0,29350.0,1200.0,0
...For production use, you need a valid license key. Get yours at /pricing.
from rlxbt import TradingEngine
# Pass license key directly
engine = TradingEngine(
initial_capital=100000.0,
license_key="rlx_pro_xxxxxxxxxxxx_xxxx"
)
# Or set via environment variable
# export RLX_LICENSE_KEY="rlx_pro_xxxxxxxxxxxx_xxxx"Development Mode
Builds compiled with --features offline_license don't require a license key.
Create a custom strategy by subclassing Strategy:
import pandas as pd
from rlxbt import Strategy, Backtester
class SMAStrategy(Strategy):
def __init__(self, short_period=10, long_period=50):
super().__init__()
self.short = short_period
self.long = long_period
def generate_signals(self, data: pd.DataFrame) -> pd.DataFrame:
# Calculate moving averages
short_ma = data['close'].rolling(self.short).mean()
long_ma = data['close'].rolling(self.long).mean()
# Generate signals
signals = pd.DataFrame(index=data.index)
signals['signal'] = 0
signals.loc[short_ma > long_ma, 'signal'] = 1 # Long
signals.loc[short_ma < long_ma, 'signal'] = -1 # Short
return signals
# Run backtest
strategy = SMAStrategy(short_period=20, long_period=50)
backtester = Backtester(initial_capital=100000.0)
result = backtester.run(strategy, df) The BacktestResult object contains comprehensive metrics:
total_return — Total percentage return total_trades — Number of completed trades winning_trades — Profitable trades count losing_trades — Losing trades count sharpe_ratio — Risk-adjusted return sortino_ratio — Downside risk-adjusted max_drawdown — Peak-to-trough decline calmar_ratio — Return / Max drawdown # Access all metrics
for key, value in result.metrics.items():
print(f"{key}: {value}")
# Access trade history
for trade in result.trades[:5]:
print(f"Entry: {trade.entry_time}, PnL: ${trade.pnl:.2f}")
# Equity curve for visualization
equity = result.equity_curve # List[float]
timestamps = result.equity_curve_timestamps # List[int]Now that you've run your first backtest, explore more advanced features: