Skip to content

Repository files navigation


Tradix — Backtest the Market

Blazing-Fast Vectorized Backtesting Engine

StrategiesIndicatorsTwo Lines

PyPIPythonLicenseTests


Quick Start · Why Tradix? · Features · Installation · API Reference · 한국어


Tradix is a high-performance backtesting engine built for quantitative traders and researchers. Powered by pure NumPy vectorization, it runs 1,000 parameter optimizations in under a second. No boilerplate, no configuration files, no data pipeline setup — just install and backtest.

The library ships with 33 battle-tested strategies, 60+ technical indicators, and a built-in data feed that auto-downloads from global exchanges including KRX (Korea Exchange). Whether you're prototyping a Golden Cross on Samsung Electronics or stress-testing a multi-factor portfolio against Black Swan scenarios, Tradix handles the entire pipeline: data → signals → execution → analytics → visualization.

Two lines.backtest · show — that's the entire workflow.

fromtradiximportbacktest, goldenCrossresult=backtest("AAPL", goldenCross())
result.show()

◈ Quick Start

pip install tradix
fromtradiximportbacktest, goldenCrossresult=backtest("005930", goldenCross())
result.show()
result.show(style="bloomberg")

backtest() auto-downloads price data via FinanceDataReader, applies the strategy with realistic commission and slippage modeling, and returns a comprehensive result object. Pass any ticker symbol — US stocks, Korean stocks, ETFs, indices, and crypto are all supported out of the box.

=== Backtest Result ===
Strategy: GoldenCross
Period: 2020-01-02 ~ 2024-12-30
Initial: 10,000,000 KRW
Final: 14,230,000 KRW
Return: +42.30%
Sharpe: 1.23
Max DD: -12.45%
Trades: 18
Win Rate: 61.1%

◈ Why Tradix?

Most backtesting frameworks require hundreds of lines of boilerplate — data loaders, strategy classes, broker configs, result parsers. Tradix eliminates all of that. Here's how it compares:

DimensionTradixBacktraderZiplinebt
Zero-config backtest
2-line API
Vectorized engine
1K optimizations < 1s
Built-in data feed
33 preset strategies
Terminal dashboard
Korean market native
Walk-forward analysis
Strategy DNA analysis

Three pillars.numpy · pandas · scipy — that's the entire foundation. No C extensions, no binary dependencies, no compilation step.


◈ Features

Core Engine

The heart of Tradix is a dual-engine architecture: an event-driven engine for complex strategies with bar-by-bar logic, and a vectorized engine for lightning-fast batch operations. Both engines share the same indicator library and produce identical results.

FeatureDescription
Vectorized EngineNumPy-powered core, 100x faster than event-driven loops
60+ IndicatorsSMA, EMA, RSI, MACD, Bollinger, ATR, Ichimoku, Supertrend, StochRSI, KDJ, and more
33 Preset StrategiesTrend, momentum, oscillator, volatility, multi-indicator, buy & hold, DCA
Strategy BuilderDeclarative method chaining — no subclassing needed
Walk-ForwardBuilt-in overfitting prevention with time-series cross-validation
OptimizationGrid search and random search with any metric
Multi-AssetBacktest across multiple symbols with rebalancing
Realistic SimulationCommission, slippage, fill logic, position sizing
OCO / Bracket / Trailing StopAdvanced order types for automated stop-loss and take-profit management
Multi-Source Data Feeds

Connect to global markets without writing a single data loader. Tradix ships with three data feed backends — FinanceDataReader for Korean/US/JP equities, Yahoo Finance for global ETFs and indices, and CCXT for 100+ cryptocurrency exchanges. All feeds share the same interface and include Parquet caching for offline replay.

FeatureDescription
FinanceDataReaderKRX, US, JP stocks with auto-caching
Yahoo FinanceGlobal equities, ETFs, indices, crypto pairs via yfinance
CCXT (100+ Exchanges)Binance, Bybit, Upbit, Coinbase — 1m to 1w candles with auto-pagination
Parquet CacheOffline-first with configurable expiration
Unified InterfaceAll feeds implement the same DataFeed API
Advanced Analytics

Go beyond simple returns. Tradix provides institutional-grade analytics that dissect every aspect of your strategy — from 12-dimensional DNA fingerprinting to Black Swan resilience scoring. Understand not just how much your strategy made, but why it works and when it might fail.

FeatureDescription
Strategy DNA12-dimensional strategy fingerprinting
Black Swan DefenseExtreme event resilience scoring (0-100)
Health ScoreOverfitting risk, parameter stability diagnostics
What-If SimulatorCommission, slippage, capital sensitivity analysis
Drawdown SimulatorHistorical worst-case scenario generation
Seasonality AnalyzerMonthly, weekday, quarterly pattern discovery
Correlation MatrixMulti-strategy correlation and clustering
Trading JournalAuto trade diary with MFE/MAE analytics
Strategy LeaderboardMulti-strategy ranking with badge system
Innovative Analytics

Tradix pushes the boundary of what a backtesting library can do. Monte Carlo simulations with 10,000 paths estimate your ruin probability. Fractal analysis reveals whether your market is trending or mean-reverting. Regime detection identifies hidden market states so you can adapt your strategy dynamically.

FeatureDescription
Monte Carlo10K-path bootstrap with ruin probability and confidence bands
Fractal AnalysisHurst exponent for market character classification
Regime DetectorGMM-based probabilistic regime detection with transition matrix
Information TheoryShannon entropy, mutual information for signal quality
Portfolio Stress6 crisis scenarios (crash, volatility spike, rate shock, etc.)
Terminal UI — TradingView-Inspired

No browser needed. Tradix renders professional trading dashboards directly in your terminal using Rich and Plotext. Choose from three display styles inspired by TradingView, Bloomberg Terminal, and hedge fund reports. The interactive Textual dashboard provides a full 5-view experience with keyboard navigation.

FeatureDescription
3 Display StylesModern (TradingView), Bloomberg (dense 4-quadrant), Minimal (hedge fund)
14 Chart TypesEquity, drawdown, candlestick, returns, seasonality, heatmap, DNA, rolling metrics, and more
Plotly CandlestickInteractive OHLCV chart with volume, SMA/EMA overlays, and trade markers
Rolling MetricsTime-varying Sharpe, Sortino, and volatility visualization
Interactive Dashboard5-view Textual app with keyboard navigation
CLItradix backtest, tradix chart, tradix compare, tradix optimize, tradix list
Korean Market

Tradix is the first backtesting engine built with native Korean market support. Transaction tax (0.18%), brokerage fees, and KRX stock name mapping are all built-in. You can even write your entire strategy in Korean — function names, variable names, and output are all available in 한국어.

FeatureDescription
Native SupportBuilt-in transaction tax (0.18%), brokerage fees, KRX stock mapping
Korean APIFull Korean function names: 백테스트("삼성전자", 골든크로스())

◈ Installation

Using uv (Recommended)

uv is the fastest Python package manager.

uv init my-backtest &&cd my-backtest
uv add tradix
uv add "tradix[full]"# + Plotly, statsmodels, scikit-learn
uv add "tradix[yahoo]"# + Yahoo Finance global data
uv add "tradix[crypto]"# + CCXT 100+ crypto exchanges
uv add "tradix[tui]"# + Textual interactive dashboard

Using pip

pip install tradix # Core (NumPy + Pandas + Rich)
pip install "tradix[full]"# + Plotly, statsmodels, scikit-learn
pip install "tradix[yahoo]"# + Yahoo Finance global data
pip install "tradix[crypto]"# + CCXT 100+ crypto exchanges
pip install "tradix[tui]"# + Textual interactive dashboard

From source

git clone https://github.com/eddmpython/tradix.git
cd tradix
uv sync --dev
uv run pytest

Requirements: Python 3.9+ · NumPy · Pandas · Rich · Plotext · Typer


◈ Usage

Tradix offers multiple levels of abstraction. Start with the 2-line easy API, graduate to the declarative strategy builder for custom logic, or drop down to the full event-driven engine when you need bar-by-bar control.

Declarative Strategy Builder

fromtradiximportQuickStrategy, backtest, sma, rsi, crossover, crossunderstrategy= (
QuickStrategy("MomentumRSI")
.buyWhen(crossover(sma(10), sma(30)))
.buyWhen(rsi(14) <30)
.sellWhen(crossunder(sma(10), sma(30)))
.sellWhen(rsi(14) >70)
.stopLoss(5)
.takeProfit(15)
)
result=backtest("AAPL", strategy)
result.show()

Parameter Optimization

Find optimal strategy parameters by sweeping across a parameter grid. Tradix runs all combinations using the vectorized engine — 1,000 combinations finish in under a second.

fromtradiximportvoptimizebest=voptimize(
"005930",
"goldenCross",
fast=(5, 20, 5),
slow=(20, 60, 10),
metric="sharpeRatio"
)
print(f"Best: fast={best['best']['params']['fast']}, slow={best['best']['params']['slow']}")
print(f"Sharpe: {best['best']['metric']:.2f}")

Vectorized Mode (100x Faster)

Skip the event loop entirely. The vectorized engine processes the entire price history as NumPy arrays, delivering results in microseconds.

fromtradiximportvbacktestresult=vbacktest("005930", "goldenCross", fast=10, slow=30)
print(f"Return: {result.totalReturn:+.2f}%")
print(f"Sharpe: {result.sharpeRatio:.2f}")
print(f"Max DD: {result.maxDrawdown:.2f}%")

Korean API (한국어 API)

Every function, every strategy, every output — available in native Korean. No wrappers, no translation layers. First-class Korean market citizen.

fromtradiximport백테스트, 골든크로스결과=백테스트("삼성전자", 골든크로스())
결과.보기()
결과.차트()
More Examples — Class-based strategy, walk-forward, multi-asset, risk

Class-Based Strategy

fromtradiximportStrategy, Bar, BacktestEnginefromtradix.datafeedimportFinanceDataReaderFeedclassDualMomentum(Strategy):
definitialize(self):
self.fastPeriod=10self.slowPeriod=30defonBar(self, bar: Bar):
fast=self.sma(self.fastPeriod)
slow=self.sma(self.slowPeriod)
iffastisNoneorslowisNone:
returniffast>slowandnotself.hasPosition(bar.symbol):
self.buy(bar.symbol)
eliffast<slowandself.hasPosition(bar.symbol):
self.closePosition(bar.symbol)
data=FinanceDataReaderFeed("005930", "2020-01-01", "2024-12-31")
engine=BacktestEngine(data, DualMomentum(), initialCash=10_000_000)
result=engine.run()
result.show()

Walk-Forward Analysis

fromtradiximportStrategy, Bar, WalkForwardAnalyzer, ParameterSpacefromtradix.datafeedimportFinanceDataReaderFeeddefcreateStrategy(params):
classMySma(Strategy):
definitialize(self):
self.fast=params["fast"]
self.slow=params["slow"]
defonBar(self, bar: Bar):
f, s=self.sma(self.fast), self.sma(self.slow)
iffands:
iff>sandnotself.hasPosition(bar.symbol):
self.buy(bar.symbol)
eliff<sandself.hasPosition(bar.symbol):
self.closePosition(bar.symbol)
returnMySma()
data=FinanceDataReaderFeed("005930", "2020-01-01", "2024-12-31")
space=ParameterSpace()
space.addInt("fast", 5, 20, step=5)
space.addInt("slow", 20, 60, step=10)
wfa=WalkForwardAnalyzer(
data=data,
strategyFactory=createStrategy,
parameterSpace=space,
inSampleMonths=12,
outOfSampleMonths=3,
)
result=wfa.run()
print(f"Robustness: {result.robustnessRatio:.1%}")

Multi-Asset Portfolio

fromtradiximportMultiAssetEngine, MultiAssetStrategyclassEqualWeight(MultiAssetStrategy):
defonBars(self, bars):
self.rebalance({
"005930": 0.4,
"000660": 0.3,
"035420": 0.3,
})
engine=MultiAssetEngine(strategy=EqualWeight())
result=engine.run()
result.show()

Risk Simulation

importpandasaspdfromtradiximportbacktest, goldenCrossfromtradix.riskimportRiskSimulator, VaRMethodresult=backtest("005930", goldenCross())
returns=pd.DataFrame({"returns": pd.Series(result.equityCurve).pct_change().dropna()})
simulator=RiskSimulator()
simulator.fit(returns)
var95, cvar95=simulator.calcVaR(confidence=0.95, method=VaRMethod.HISTORICAL)
print(f"95% VaR: {var95:.2%}")
print(f"CVaR: {cvar95:.2%}")
mc=simulator.monteCarloSimulation(horizon=252, nSim=10000)

◈ Strategies

33 production-ready strategies organized by trading style. Each strategy is a callable that returns a configured strategy object — no subclassing, no boilerplate. Pass parameters to customize, or use the defaults.

Trend Following (9)
StrategyDescription
goldenCross()SMA crossover (fast/slow)
emaCross()EMA crossover
tripleEma()Triple EMA crossover
trendFollowing()ADX-filtered trend following with trailing stop
superTrend()Supertrend indicator reversal
ichimokuCloud()Ichimoku cloud breakout
parabolicSar()Parabolic SAR reversal
donchianBreakout()Donchian channel breakout
breakout()Channel breakout (Turtle Trading)
Momentum & Oscillator (8)
StrategyDescription
rsiOversold()RSI reversal (oversold/overbought)
macdCross()MACD histogram crossover
stochasticCross()Stochastic K/D crossover
williamsReversal()Williams %R reversal
cciBreakout()CCI overbought/oversold breakout
rsiDivergence()RSI divergence detection
momentumCross()Momentum zero-line crossover
rocBreakout()Rate of Change breakout
Volatility (5)
StrategyDescription
bollingerBreakout()Bollinger band breakout
bollingerSqueeze()Bollinger squeeze expansion
keltnerChannel()Keltner channel breakout
volatilityBreakout()ATR-based volatility breakout
meanReversion()Bollinger mean reversion
Multi-Indicator (5)
StrategyDescription
tripleScreen()Elder's triple screen system
dualMomentum()Absolute + relative momentum
macdRsiCombo()MACD + RSI combined signal
trendMomentum()Trend + momentum filter
bollingerRsi()Bollinger + RSI combined
Special (6)
StrategyDescription
gapTrading()Gap up/down trading
pyramiding()Pyramiding position building
swingTrading()Swing high/low trading
scalpingMomentum()Short-term momentum scalping
buyAndHold()Passive buy and hold
dollarCostAverage()Dollar cost averaging

◈ Indicators

60+ technical indicators implemented in pure NumPy. Each indicator is available as both a standalone function and a strategy-builder condition. All calculations are vectorized — even complex indicators like Ichimoku Cloud run in microseconds.

CategoryIndicators
Moving Averagessmaemawmahmatemademavwmaalma
MomentumrsimacdstochasticrocmomentumcciwilliamsRcmostochasticRsikdjawesomeOscillatorultimateOscillator
VolatilityatrbollingerkeltnerdonchianbollingerPercentBbollingerWidth
VolumeobvvwapmfiadlchaikinemvforceIndexnvipvivrocpvtklingerOscillator
TrendadxsupertrendpsarichimokutrixdpolinearRegression
PricepivotPointsfibonacciRetracementzigzagelderRaytwap
OtherulcerpercentChangehighestlowest

◈ Performance

Tradix is built for speed. The vectorized engine processes entire price histories as contiguous NumPy arrays, eliminating Python loop overhead. Benchmarked on 10 years of daily data (2,458 bars):

OperationTime
SMA calculation0.006ms
RSI calculation0.009ms
MACD calculation0.040ms
Full backtest (single)0.132ms
1,000 param optimization0.02s

◈ Terminal UI

Professional trading dashboards rendered directly in your terminal. No browser, no GUI toolkit, no Jupyter dependency. Tradix uses Rich for styled tables and panels, Plotext for ASCII charts, and optionally Textual for a full interactive experience.

Display Styles

result.show() # Modern — TradingView metric cardsresult.show(style="bloomberg") # Bloomberg — dense 4-quadrant layoutresult.show(style="minimal") # Minimal — clean hedge fund report

CLI

tradix backtest AAPL -s goldenCross --dashboard
tradix backtest AAPL -s bollingerSqueeze --style bloomberg
tradix chart AAPL -n 60
tradix compare AAPL -s goldenCross,rsiOversold
tradix optimize AAPL -s goldenCross
tradix list

Charts (12 Types)

fromtradix.tui.chartsimport (
plotEquityCurve, plotDrawdown, plotCandlestick, plotReturns,
plotSeasonality, plotMonthlyHeatmap, plotRollingMetrics,
plotTradeScatter, plotTradeMarkers, plotCorrelationBars,
plotStrategyDna, plotDashboard,
)
plotEquityCurve(result, smaPeriods=[20, 60])
plotDrawdown(result)
plotCandlestick(df, smaPeriods=[5, 20])
plotDashboard(result, lang="ko")

Interactive Dashboard

pip install tradix[tui]
fromtradix.tui.dashboardimportlaunchDashboardlaunchDashboard(result)

◈ Advanced Analytics

Tradix includes a full suite of institutional-grade analytics. Each analyzer takes a backtest result and returns a structured report with scores, metrics, and actionable insights.

fromtradiximport (
StrategyDnaAnalyzer, BlackSwanAnalyzer, StrategyHealthAnalyzer,
WhatIfSimulator, DrawdownSimulator, SeasonalityAnalyzer,
CorrelationAnalyzer, TradingJournal, StrategyLeaderboard,
)
result=backtest("005930", goldenCross())
dna=StrategyDnaAnalyzer().analyze(result)
printStrategyDna(dna)
health=StrategyHealthAnalyzer().analyze(result)
printHealthScore(health)
blackSwan=BlackSwanAnalyzer().analyze(result)
printBlackSwanScore(blackSwan)
fromtradiximport (
MonteCarloStressAnalyzer, FractalAnalyzer, RegimeDetector,
InformationTheoryAnalyzer, PortfolioStressAnalyzer,
)
mc=MonteCarloStressAnalyzer().analyze(result, paths=10000)
print(f"Ruin probability: {mc.ruinProbability:.2%}")
fractal=FractalAnalyzer().analyze(result)
print(f"Hurst: {fractal.hurstExponent:.3f}{fractal.marketCharacter}")
regime=RegimeDetector().analyze(result)
print(f"Current regime: {regime.currentRegime}")

◈ API Reference

Core Functions
FunctionDescription
backtest(symbol, strategy)Run a backtest with a preset or custom strategy
vbacktest(symbol, strategy, **params)Run a vectorized backtest
voptimize(symbol, strategy, **ranges)Grid search parameter optimization
BacktestEngine(data, strategy)Event-driven backtest engine
VectorizedEngine(initialCash)Vectorized backtest engine
QuickStrategy(name)Declarative strategy builder
Strategy Builder Methods
MethodDescription
.buyWhen(condition)Add buy condition
.sellWhen(condition)Add sell condition
.stopLoss(pct)Set stop loss percentage
.takeProfit(pct)Set take profit percentage
.trailingStop(pct)Set trailing stop percentage
Condition Builders
FunctionReturns
sma(period)SMA indicator
ema(period)EMA indicator
rsi(period)RSI indicator
macd(fast, slow, signal)MACD indicator
bollinger(period, std)Bollinger Bands
atr(period)ATR indicator
price()Current price
crossover(fast, slow)Crossover condition
crossunder(fast, slow)Crossunder condition

Indicators support comparison operators: sma(10) > sma(30), rsi(14) < 30


◈ Architecture

Tradix follows a modular architecture. Each subsystem is independently importable, so you can use just the indicators, just the risk engine, or the full pipeline.

tradix/
├── engine.py # Core backtest engine
├── multiAssetEngine.py # Multi-asset portfolio engine
├── strategy/ # Strategy base + 60+ indicators + ensemble
├── easy/ # 2-line API, presets, Korean API
├── vectorized/ # Vectorized engine + indicators (Pure NumPy)
├── datafeed/ # Data feeds (FinanceDataReader + Parquet cache)
├── broker/ # Commission, slippage, fill simulation
├── risk/ # Position sizing, VaR, Monte Carlo
├── optimize/ # Grid / random search optimizer
├── walkforward/ # Walk-forward analysis
├── analytics/ # Strategy DNA, Black Swan, Health Score, etc.
├── portfolio/ # Portfolio tracking + optimization
├── quant/ # Factor analysis, statistical arbitrage
├── signals/ # Signal prediction + adaptive signals
├── advisor/ # Market regime + strategy recommendation
├── entities/ # Bar, Order, Position, Trade
├── events/ # Event system
├── tui/ # Terminal UI (Rich + Plotext + Textual)
├── cli.py # Typer CLI
└── tests/ # 87 tests

◈ Contributing

Contributions are welcome. Fork the repo, create a feature branch, and submit a pull request.

git clone https://github.com/eddmpython/tradix.git
cd tradix
uv sync --dev
uv run pytest

◈ Support

If Tradix helps your trading research, consider supporting the project:

Buy Me A Coffee


◈ License

MIT — Use freely in personal and commercial projects.


Trade smarter. Backtest faster.


About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages