A production-grade, multi-backend library for trading analytics with technical indicators, data sampling tools, multi-asset factor analysis, and live execution on Binance.
- Multi-Backend Support: Pandas, Polars, and PyArrow engines
- 35+ Technical Indicators: Comprehensive collection of technical indicators
- Data Sampling Tools: Information-driven bars and time-based aggregation
- Multi-Asset Factor Analysis: Cross-sectional ranking and portfolio construction
- Portfolio Backtesting: Realistic backtesting with transaction costs and rebalancing
- Transaction Cost Models: 9 calibrated cost models (spread, slippage, market impact)
- Live Execution Module: Production-ready Binance testnet/live trading execution
- Comprehensive Logging & Metrics: Structured logging, CSV summaries, SQLite persistence
- Commission Tracking: Automatic commission calculation (simulated for testnet, real for live)
- Portfolio Snapshots: Historical tracking of portfolio and position evolution
- Safety Guards: Circuit breakers, risk monitoring with audit trail
- Performance Metrics: API latency tracking and execution monitoring
- S3/MinIO Integration: Load data directly from Delta Lake on S3-compatible storage
- Type-Safe: Full type hints throughout the codebase (Pydantic for cost models)
- Explicit Error Handling: No silent failures - all errors are explicit
- Backend-Agnostic: Write once, run on any backend
- Extensible: Easy to add custom indicators, samplers, and cost models
- Installation - Installation guide and quick start
- Architecture - System design and principles
- Indicators - Technical indicators and sampling tools
- Factors - Multi-asset factor analysis and backtesting
- Transaction Cost Models - Comprehensive cost modeling guide
- Cost Models API - API reference for all cost models
from tools import setup_logging
# Use default configuration
logger = setup_logging()
logger.info("Trading started")
# Customize configuration
logger = setup_logging(
console_level=logging.INFO,
file_level=logging.DEBUG,
log_dir="logs",
log_file="my_strategy.log",
error_log_file="my_strategy_errors.log"
)Features:
- Console output (INFO level by default)
- Rotating file log (DEBUG level, 10MB max, 5 backups)
- Separate error log (ERROR level, 5MB max, 3 backups)
- Consistent formatting across all modules
- No need to configure logging in each script
from tools.indicators import SMA, RSI, IndicatorExecutor
import pandas as pd
# Create sample data
df = pd.DataFrame({'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]})
# Compute indicators
executor = IndicatorExecutor()
result = executor.compute_multiple([SMA(period=5), RSI(period=5)], df)
print(result)from tools.factors.portfolio.backtest import PortfolioBacktest
from tools.factors.portfolio.cost_models import (
TransactionCostModel,
TieredSpread,
KyleLambdaImpact,
)
# Compose realistic cost model
cost_model = TransactionCostModel(
spread=TieredSpread(
small_order_bps=0.5, # <1% daily volume
medium_order_bps=2.5, # 1-10% daily volume
large_order_bps=9.0, # >10% daily volume
),
market_impact=KyleLambdaImpact(
lambda_params={'BTCUSDT': 0.00032, 'ETHUSDT': 0.00045},
),
)
# Run backtest with realistic costs
backtest = PortfolioBacktest(
rebalancing_freq='1D',
cost_model=cost_model,
initial_capital=100_000,
)
results = backtest.run(prices, weights, volumes)
print(f"Cost drag: {results['summary']['transaction_costs_pct']:.2f}%")from tools.execution import BinanceExchange, ExecutionEngine, SafetyGuard
from tools.portfolio import PortfolioManager
from tools.core.models import MarketOrder, OrderSide
# Connect to Binance testnet
exchange = BinanceExchange(
api_key="your_testnet_key",
api_secret="your_testnet_secret",
testnet=True
)
engine = ExecutionEngine(exchange)
# Check account balances
balances = exchange.get_account_balance()
# Submit typed orders
order1 = MarketOrder(symbol="BTCUSDT", side=OrderSide.BUY, quantity=0.001)
order2 = MarketOrder(symbol="ETHUSDT", side=OrderSide.BUY, quantity=0.01)
result1 = engine.submit_order(order1)
result2 = engine.submit_order(order2)
# Check results
if result1.is_filled:
print(f"✓ BTC order filled at ${result1.average_price:.2f}")
# Track portfolio locally
portfolio = PortfolioManager(
initial_balance=10000,
symbols=["BTCUSDT", "ETHUSDT"]
)
# Add safety controls
guard = SafetyGuard(
initial_balance=10000,
max_drawdown=0.20, # Stop if down 20% from initial capital
max_trades_per_hour=20,
drawdown_from_peak=False, # Calculate from initial, not peak (default)
restore_state=True # Restore circuit breaker state from DB (default)
)
# Check if trading is allowed
can_trade, reason = guard.can_trade("BTCUSDT")
if not can_trade:
print(f"Trading blocked: {reason}")
# Reset circuit breaker if needed
guard.reset(reason="Issue resolved")The SafetyGuard supports two drawdown calculation modes:
Mode 1: From Initial Balance (Default, drawdown_from_peak=False)
- Portfolio: $1000 → $1200 → $960
- Drawdown: (1000 - 960) / 1000 = 4.0%
- Recommended for most strategies - less sensitive to volatility
Mode 2: From Peak Balance (drawdown_from_peak=True)
- Portfolio: $1000 → $1200 → $960
- Drawdown: (1200 - 960) / 1200 = 20.0%
- More conservative - triggers on intraday volatility
The circuit breaker state persists across restarts via SQLite database.
from tools.execution import FactorStrategy
# Spot trading (no leverage, no shorting)
strategy = FactorStrategy(
symbols=["BTCUSDT", "ETHUSDT", "BNBUSDT"],
rsi_period=14,
max_leverage=1.0, # Constrain sum(|weights|) <= 1.0
allow_short=False, # Filter out short positions
)
# Futures/margin trading (with leverage and shorting)
strategy_futures = FactorStrategy(
symbols=["BTCUSDT", "ETHUSDT", "BNBUSDT"],
rsi_period=14,
max_leverage=2.0, # Allow 2x leverage
allow_short=True, # Allow short positions
)Leverage Constraint Behavior:
| Configuration | Original Weights | After Constraints | Notes |
|---|---|---|---|
max_leverage=1.0allow_short=False |
BTC: +0.5 ETH: -0.5 |
BTC: +0.5 ETH: 0.0 |
Shorts filtered, total = 0.5 |
max_leverage=1.0allow_short=True |
BTC: +0.5 ETH: -0.5 |
BTC: +0.5 ETH: -0.5 |
Total = 1.0 (no scaling) |
max_leverage=0.8allow_short=True |
BTC: +0.5 ETH: -0.5 |
BTC: +0.4 ETH: -0.4 |
Scaled by 0.8/1.0 = 0.8 |
MIT
- kedro-crypto-ind - Pandas-based indicator implementations
- auto-trader - Multi-backend architecture patterns