Algorithmic Trading Analytics Platform built with kdb+/q and Python.
A modular platform for developing, backtesting, and analyzing algorithmic trading strategies. Focuses on high-performance time-series analytics using kdb+/q with Python for data fetching and complex algorithms.
Paper and live trading support planned.
Technical analysis is considered to be the study of historical market data, primarily price and volume, to forecast future price movements1,2,3,4. It goes againt the efficient market hypothesis which states that all known information is already reflected in prices. Technical analysts and quants believe that price movements are not entirely random and that correlations, patterns, trends, and indicators can provide insights into future price action.
Algorithmic trading utilizes computer algorithms to take advantage of small market inefficiencies (like ask/bid spread or book vs market value) and to execute trades based on predefined criteria5,6. It allows traders to capitalize on market opportunities with speed, precision and consistency that human traders cannot match.
In the long rung the average expected return on wealth (r) is around ~6% and the growth (or return) of economy (g) is around ~3% 7,8. So, in the long run you should be a banker and not an economist. Sadly, and rather disappointingly, in the long run we are all dead. All in all, if your trading strategies on average return less than ~6%, you probably shouldnβt quit your day job.
- π Backtesting Engine β Event-driven backtesting framework with realistic execution simulation
- π Technical Indicators β Comprehensive library of indicators (SMA, EMA, RSI, MACD, Bollinger Bands, etc.)
- π― Strategy Library β Pre-built strategies (Momentum, Mean Reversion, RSI, Bollinger Bands)
- β‘ kdb+/q Analytics β High-performance time-series operations
- π REST API β FastAPI server for programmatic access
- π» Web Dashboard β Minimal, effective UI for strategy analysis
- π Data Feeds β Yahoo Finance integration (extensible to other sources)
- Python 3.10+
- kdb+/q (KDB-X Community Edition)
- PyKX
- Clone the repository
git clone https://github.com/jouniverse/algo-trader.git
cd algo-trader- Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies
pip install -r requirements.txt- Configure environment
cp config/.env.example config/.env
# Edit config/.env with your API keysNOTE: Add a file ./config/API_KEYS.txt with your API keys if needed. Currently only FRED API key is required for economic data.
Start the API server:
# Using script
./scripts/start_api.sh
# Or manually
export PYTHONPATH=$PYTHONPATH:$(pwd)/src
uvicorn src.python.api.server:app --reload --port 8000Open the dashboard:
Open src/ui/index.html in your browser, or serve it:
python -m http.server 3000 --directory src/uiNavigate to http://localhost:3000
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Web Dashboard β
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββ
β FastAPI Server β
β REST API + WebSocket endpoints β
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββΌβββββββββββββββββββββββ
β β β
βββββββββΌββββββββ βββββββββββΌβββββββββ ββββββββββΌβββββββββ
β Backtest β β Analytics β β Strategies β
β Engine β β Library β β β
βββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββ
β Data Layer β
β kdb+/q (HDB) + Python (feedhandlers) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
algo-trader/
βββ src/
β βββ python/
β β βββ api/ # FastAPI server
β β βββ backtest/ # Backtesting engine
β β βββ feedhandlers/ # Data source connectors
β β βββ strategies/ # Trading strategies
β β βββ utils/ # Utilities (PyKX bridge)
β β
β βββ q/
β β βββ analytics/ # kdb+/q analytics
β β β βββ indicators.q # Technical indicators
β β β βββ performance.q # Performance metrics
β β βββ tick/ # Ticker plant (future)
β βββ ui/ # Web dashboard
β
βββ config/ # Configuration files
βββ scripts/ # Startup scripts
βββ data/ # Data storage (HDB, RDB)
βββ examples/ # Example usage scripts
βββ tickers/ # Ticker lists
βββ freezer/ # Development sketches
βββ notes/ # Project documentation
from src.python.feedhandlers import YFinanceFeed
from src.python.backtest import BacktestEngine, BacktestConfig
from src.python.strategies import MomentumStrategy
# Fetch data
feed = YFinanceFeed()
data = feed.get_ohlcv('AAPL', interval='1d')
# Configure backtest
config = BacktestConfig(
initial_capital=100000,
commission=0.001,
slippage=0.0005
)
# Create strategy
strategy = MomentumStrategy(fast_period=10, slow_period=30)
# Run backtest
engine = BacktestEngine(config)
engine.load_data(data)
engine.set_strategy(strategy)
results = engine.run()
print(f"Total Return: {results['metrics']['total_return']:.2%}")
print(f"Sharpe Ratio: {results['metrics']['sharpe_ratio']:.2f}")
print(f"Max Drawdown: {results['metrics']['max_drawdown']:.2%}")/ Load indicators
\l src/q/analytics/indicators.q
/ Calculate technical indicators
prices: 100 + sums 100?1.0 - 0.5 / Random walk
sma20: sma[20; prices] / 20-period SMA
rsi14: rsi[14; prices] / 14-period RSI
bb: bollinger[20; 2; prices] / Bollinger Bands
/ Performance metrics
\l src/q/analytics/performance.q
returns: .perf.returns[prices]
summary: .perf.summary[returns; 0.02; 252] / 2% rf rate, daily data# Get quote
curl http://localhost:8000/api/quote/AAPL
# Get OHLCV data
curl "http://localhost:8000/api/ohlcv/AAPL?period=1y&interval=1d"
# Run backtest
curl -X POST http://localhost:8000/api/backtest \
-H "Content-Type: application/json" \
-d '{
"symbol": "AAPL",
"strategy": "momentum",
"period": "1y",
"initial_capital": 100000,
"params": {"fast_period": 10, "slow_period": 30}
}'| Strategy | Type | Description | Parameters |
|---|---|---|---|
| Buy & Hold | Baseline | Buy at start, hold until end (benchmark) | None |
| Momentum | Trend | Dual MA crossover | fast_period, slow_period, ma_type |
| MACD | Trend | MACD line crossing signal line | fast_period, slow_period, signal_period |
| RSI | Mean Reversion | Overbought/oversold reversals | period, oversold, overbought |
| Trend Following | Trend | Multi-timeframe MA filter | short_period, medium_period, long_period |
| Bollinger Bands | Mean Reversion | Trade on band touches | period, std_dev |
| Mean Reversion | Mean Reversion | Z-score based reversion | lookback, z_threshold, exit_threshold |
| Pairs Trading | Statistical Arb | Spread z-score trading | lookback, entry_z, exit_z |
π See TRADING_STRATEGIES.md for detailed strategy documentation.
sma[n;x]β Simple Moving Averageema[n;x]β Exponential Moving Averagewma[n;x]β Weighted Moving Averagedema[n;x]β Double EMAtema[n;x]β Triple EMA
rsi[n;x]β Relative Strength Indexmacd[x;fast;slow;sig]β MACDstochastic[n;k;d;h;l;c]β Stochastic Oscillatorroc[n;x]β Rate of Changemomentum[n;x]β Momentum
bollinger[n;k;x]β Bollinger Bandsatr[n;h;l;c]β Average True Rangehvol[n;periods;x]β Historical Volatility
adx[n;h;l;c]β Average Directional Indexpsar[af;maxAf;h;l]β Parabolic SAR
Dashboard Metrics (UI):
| Metric | Description |
|---|---|
| Total Return | Cumulative return over the backtest period |
| Sharpe Ratio | Risk-adjusted return (higher = better risk/reward) |
| Max Drawdown | Largest peak-to-trough decline (risk measure) |
| Win Rate | Percentage of profitable trades |
| Trades | Total number of round-trip trades |
| Profit Factor | Gross profit / Gross loss (>1 = profitable) |
Additional Metrics (available in code):
| Metric | Description |
|---|---|
| Annualized Return | CAGR adjusted for time |
| Sortino Ratio | Downside risk-adjusted return |
| Calmar Ratio | Return / Max Drawdown |
| VaR (95%) | Value at Risk at 95% confidence |
| Expectancy | Expected value per trade |
The web dashboard displays several visualizations and data tables. Here's how to interpret them:
All strategies use daily close prices for:
- Signal generation β Indicators (SMA, RSI, etc.) are calculated on close prices
- Order execution β Market orders fill at the close price (with optional slippage)
- P&L calculation β Unrealized and realized P&L based on close prices
The equity curve shows your portfolio value over time:
- Smooth sections β Cash only (no position held)
- Volatile sections β Active position with daily P&L fluctuations
- Upward/downward swings β Daily price movements affecting unrealized P&L
The "spikes" you see are real β they show the volatility of holding positions. A large daily price movement creates a large swing in portfolio value.
The trade table shows completed round-trip trades (enter β exit):
| Column | Description |
|---|---|
| Exit Date | When the position was closed |
| Side | Direction of entry (BUY = long position) |
| Days | Holding period in trading days |
| Qty | Number of shares traded |
| Entry | Average entry price |
| Exit | Exit/close price |
| P&L | Profit or loss in dollars |
| Return | Percentage return on the trade |
Note: The trade list is paginated (15 per page). Use the pagination controls to view all trades.
When available, FRED data shows economic conditions during your backtest period:
| Indicator | Relevance |
|---|---|
| VIX | Market volatility/fear gauge |
| Fed Funds Rate | Monetary policy environment |
| 10Y Treasury | Interest rate environment |
| S&P 500 | Broad market performance |
These help contextualize your strategy's performance (e.g., did it work during high volatility?).
Strategies determine their own holding periods based on signals:
- Buy & Hold β Holds entire period (one trade)
- Momentum/MACD β Holds until signal reversal (days to weeks)
- RSI/Bollinger β Mean reversion, typically shorter holds
- Trend Following β Can hold for extended periods in strong trends
The "Days" column in Trade History shows actual holding duration per trade.
Default Buy-and-Hold vs Mean Reversion strategy on COKE ticker (2yrs period): 8.45% vs 11.10% total return.
| Source | Type | Status |
|---|---|---|
| Yahoo Finance | Historical OHLCV, Quotes | β Implemented |
| FRED | Economic Data | β Implemented |
| EOD Data (or other) | EOD Prices | π§ Planned |
| Alpha Vantage (or other) | Real-time Data | π§ Planned |
The app currently runs as pure Python for simplicity and rapid development:
| Component | Implementation | Notes |
|---|---|---|
| Data Fetching | Python (yfinance) | β Working |
| Backtesting | Python | β Working |
| Strategies | Python | β Working |
| API Server | Python (FastAPI) | β Working |
| Web UI | HTML/JS | β Working |
| kdb+/q Analytics | q scripts (ready) | π§ Not yet integrated |
| PyKX Bridge | Python (ready) | π§ Not yet integrated |
kdb+/q Integration Roadmap:
- Store historical data in HDB for fast queries
- Use q analytics for large-scale indicator calculations
- Ticker plant for real-time data streaming
- PyKX for Python β kdb+ communication
- Core backtesting engine
- Technical indicators library (Python + q)
- 8 trading strategies
- REST API
- Web dashboard
- FRED economic data integration
- kdb+/q data storage integration
- Monte Carlo simulation
- Walk-forward optimization
- Portfolio-level backtesting
- Paper trading simulation
- Broker integration for live trading (Alpaca, IBKR)
- Bug Fixing?
This project is licensed under the MIT License - see the LICENSE file for details.
1 Andrew Lo & Jasmina Hasanhodzic, The Evolution of Technical Analysis: Financial Prediction from Babylonian Tablets to Bloomberg Terminals, (2010), Bloomberg Press 2 John J. Murphy, Technical Analysis of the Financial Markets, (1999), New York Institute of Finance 3 George Szpiro, Pricing the Future: Finance, Physics, and the 300-year Journey to the Black-Scholes Equation, (2011), Basic Books 4 Burton G. Malkiel, A Random Walk Down Wall Street, (1973), W.W. Norton & Company 5 Ernest P. Chan, Algorithmic Trading: Winning Strategies and Their Rationale, (2013), Wiley 6 Marcos Lopez de Prado, Advances in Financial Machine Learning, (2018), Wiley 7 Thomas Piketty, Capital in the Twenty-First Century, (2014), Harvard University Press 8 Oscar JordΓ et al., The Rate of Return on Everything, 1870β2015, The Quarterly Journal of Economics, Volume 134, Issue 3, August 2019, Pages 1225-1298, https://doi.org/10.1093/qje/qjz012


