A Production-Ready, Kubernetes-Native Algorithmic Trading System
This framework allows developers to build, backtest, and deploy automated trading strategies as Kubernetes CronJobs. It handles the "boring stuff"βdata ingestion, technical analysis, database persistence, and portfolio trackingβso you can focus on the alpha.
- Batteries Included: 150+ Technical Indicators (RSI, MACD, etc.) ready out of the box.
- Infrastructure as Code: Native Helm charts for easy scaling on K8s.
- Data Consistency: Built-in caching and PostgreSQL persistence for trade history and market data.
- Backtesting to Production: One class handles local testing, hyperparameter optimization, and live execution.
The system is designed to be lightweight and stateless. Each "Bot" is a containerized instance triggered by a schedule.
- Ingestion: Fetches data from Yahoo Finance (with DB caching).
- Analysis: Enriches data with the
talibrary (Technical Analysis). - Execution:
BotClassmanages the state of your portfolio in PostgreSQL. - Monitoring: Real-time performance tracking via the included Dashboard.
- Python 3.12+ (We recommend uv for speed)
- Docker (for local DB)
# Start PostgreSQL
docker run -d --name pg-trading -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=tradingbot -p 5432:5432 postgres:17-alpine
# Install project
uv sync
export POSTGRES_URI="postgresql://postgres:pass@localhost:5432/tradingbot"
Create a simple RSI Mean Reversion bot in seconds:
from tradingbot.utils.botclass import Bot
class RSIBot(Bot):
def __init__(self):
super().__init__("RSIBot", "AAPL", interval="1m", period="1d")
def decisionFunction(self, row):
if row["momentum_rsi"] < 30: return 1 # Buy
if row["momentum_rsi"] > 70: return -1 # Sell
return 0
if __name__ == "__main__":
bot = RSIBot()
bot.run() # Single iterationBacktest your strategy before going live:
bot = RSIBot()
results = bot.local_backtest(initial_capital=10000.0)
print(f"Sharpe Ratio: {results['sharpe_ratio']:.2f}")
print(f"Yearly Return: {results['yearly_return']:.2%}")Optimize hyperparameters automatically:
class RSIBot(Bot):
# Define search space
param_grid = {
"rsi_buy": [25, 30, 35],
"rsi_sell": [65, 70, 75],
}
def __init__(self, rsi_buy=30.0, rsi_sell=70.0, **kwargs):
super().__init__("RSIBot", "AAPL", interval="1m", period="1d", **kwargs)
self.rsi_buy = rsi_buy
self.rsi_sell = rsi_sell
def decisionFunction(self, row):
if row["momentum_rsi"] < self.rsi_buy: return 1
if row["momentum_rsi"] > self.rsi_sell: return -1
return 0
# Optimize and backtest
bot = RSIBot()
bot.local_development() # Finds best params, then backtestsKey Features:
- Data pre-fetching: Historical data fetched once, reused for all parameter combinations
- Database caching: Data persisted to DB, subsequent runs are instant
- Parallel execution: Uses multiple CPU cores automatically
The framework includes a built-in visualization suite to track your bots' performance.
Overview Dashboard shows:
- Current Worth, Total Return %, Annualized Return %
- Sharpe Ratio, Sortino Ratio, Max Drawdown %
- Volatility, Total Trades, Start Date
Bot Detail Page includes:
- Portfolio value charts, daily returns distribution
- Monthly returns heatmap, drawdown visualization
- Current holdings table, complete trade history
The dashboard is deployed automatically with the Helm chart. See Deployment for setup.
The system treats every bot as a CronJob. Define your schedule in values.yaml and deploy:
1. Create Kubernetes Secret:
# Create .env file with:
# POSTGRES_PASSWORD=yourpassword
# POSTGRES_URI=postgresql://postgres:yourpassword@psql-service:5432/postgres
# OPENROUTER_API_KEY=yourkey (if using AI bots)
# BASIC_AUTH_PASSWORD=yourpassword (for dashboard)
# Create namespace
kubectl create namespace tradingbots-2025
# Create secret
kubectl create secret generic tradingbot-secrets \
--from-env-file=.env \
--namespace=tradingbots-20252. Configure Bots:
# helm/tradingbots/values.yaml
bots:
- name: rsibot
schedule: "*/5 * * * 1-5" # Every 5 mins, Mon-Fri3. Deploy:
helm upgrade --install tradingbots \
./helm/tradingbots \
--create-namespace \
--namespace tradingbots-2025PostgreSQL is automatically deployed via Helm (if postgresql.enabled: true in values.yaml).
For detailed guides, see:
- Deployment Overview - Complete deployment options
- Kubernetes Deployment - Cluster setup
- Helm Charts - Configuration details
1. Simple (Recommended): decisionFunction(row)
For strategies based on single-row technical indicators:
def decisionFunction(self, row):
if row["momentum_rsi"] < 30: return 1
if row["momentum_rsi"] > 70: return -1
return 02. Medium Complexity: Override makeOneIteration()
For external APIs or custom data processing:
def makeOneIteration(self):
fear_greed = get_fear_greed_index() # External API
if fear_greed >= 70: self.buy("QQQ")
return 13. Complex: Portfolio Optimization For multi-asset strategies and rebalancing:
def makeOneIteration(self):
data = self.getYFDataMultiple(["QQQ", "GLD", "TLT"])
weights = optimize_portfolio(data) # Your optimization
self.rebalancePortfolio(weights)
return 0| Method | Description |
|---|---|
getYFDataWithTA() |
Fetches OHLCV + 150 indicators. |
decisionFunction(row) |
Logic applied to every candle. Return -1, 0, 1. |
makeOneIteration() |
Override for custom logic. |
local_backtest() |
Simulates strategy performance on historical data. |
local_development() |
Optimize hyperparameters + backtest. |
buy(symbol) / sell(symbol) |
Automated portfolio and DB logging. |
rebalancePortfolio(weights) |
Rebalance to target weights. |
Portfolio is stored as JSON in the database:
portfolio = {
"USD": 10000.0, # Cash
"QQQ": 5.5, # Holdings (quantity, not value)
"AAPL": 10.0, # More holdings
}Access via: bot.dbBot.portfolio.get("USD", 0)
Access over 150 indicators via the row object:
- Trend:
trend_macd,trend_adx,trend_ichimoku_a,trend_sma_fast,trend_sma_slow - Momentum:
momentum_rsi,momentum_stoch,momentum_ao,momentum_roc,momentum_ppo - Volatility:
volatility_bbh(Bollinger High),volatility_bbl(Bollinger Low),volatility_atr - Volume:
volume_vwap,volume_obv,volume_mfi
See Technical Analysis Guide for complete list.
Online Documentation: justinguese.github.io/python_tradingbot_framework/
- Quick Start Guide - Complete local development workflow with PostgreSQL setup, bot creation at different abstraction levels, backtesting, and hyperparameter tuning
- Installation - System requirements and dependency installation
- Creating a Bot - Detailed bot creation patterns and examples
- Deployment Overview - Kubernetes vs local deployment options
- Kubernetes Deployment - Cluster setup and configuration
- Helm Charts - Bot scheduling and Helm configuration
- Technical Analysis - Complete indicator reference
- Portfolio Management - Advanced portfolio operations
- Local Development - Development workflows
- Bot API - Complete Bot class documentation
- Data Service - Data fetching and caching
- Portfolio Manager - Trading operations
- eurusdtreebot.py - Decision tree-based strategy for EUR/USD
- feargreedbot.py - Uses Fear & Greed Index API for market sentiment
- swingtitaniumbot.py - Swing trading strategy
- xauzenbot.py - Gold (XAU) trading bot
- sharpeportfoliooptweekly.py - Portfolio optimization with Sharpe ratio
- aihedgefundbot.py - AI-driven portfolio rebalancing
- gptbasedstrategytabased.py - GPT-based strategy with technical analysis
See Example Bots for implementation details.

