{"id":45374417,"url":"https://github.com/JustinGuese/python_tradingbot_framework","last_synced_at":"2026-02-26T00:01:01.299Z","repository":{"id":340612833,"uuid":"1130994412","full_name":"JustinGuese/python_tradingbot_framework","owner":"JustinGuese","description":"Python algorithmic trading bot framework for Kubernetes: backtesting, hyperparameter optimization, 150+ technical analysis indicators (RSI, MACD, Bollinger Bands, ADX), portfolio management, PostgreSQL integration, Helm deployment, CronJob scheduling. Minimal overhead, production-ready, Yahoo Finance data.","archived":false,"fork":false,"pushed_at":"2026-02-25T17:01:37.000Z","size":3639,"stargazers_count":25,"open_issues_count":0,"forks_count":12,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-02-25T20:30:57.083Z","etag":null,"topics":["helm","kubernetes","python","quant","quantitative-finance","quantitative-trading","stocks-trading","trading","trading-algorithms","trading-strategies","trading-strategy","tradingbot"],"latest_commit_sha":null,"homepage":"https://justinguese.github.io/python_tradingbot_framework/","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JustinGuese.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-01-09T10:10:55.000Z","updated_at":"2026-02-25T17:01:47.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/JustinGuese/python_tradingbot_framework","commit_stats":null,"previous_names":["justinguese/python_tradingbot_framework"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/JustinGuese/python_tradingbot_framework","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JustinGuese%2Fpython_tradingbot_framework","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JustinGuese%2Fpython_tradingbot_framework/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JustinGuese%2Fpython_tradingbot_framework/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JustinGuese%2Fpython_tradingbot_framework/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JustinGuese","download_url":"https://codeload.github.com/JustinGuese/python_tradingbot_framework/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JustinGuese%2Fpython_tradingbot_framework/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29845137,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-25T22:37:40.667Z","status":"ssl_error","status_checked_at":"2026-02-25T22:37:25.960Z","response_time":61,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["helm","kubernetes","python","quant","quantitative-finance","quantitative-trading","stocks-trading","trading","trading-algorithms","trading-strategies","trading-strategy","tradingbot"],"created_at":"2026-02-21T16:00:21.181Z","updated_at":"2026-02-26T00:01:01.292Z","avatar_url":"https://github.com/JustinGuese.png","language":"Jupyter Notebook","funding_links":[],"categories":["Backtest + live trading","Python"],"sub_categories":["General purpose","Trading \u0026 Backtesting"],"readme":"# 🤖 Trading Bot Framework\n\n**A Production-Ready, Kubernetes-Native Algorithmic Trading System**\n\nkubectl create secret generic tradingbot-secrets --from-env-file=.env --namespace=tradingbots-2025 --dry-run=client -o yaml | kubectl apply -f -\n\n![Trading Bot Framework](docs/overview.png)\n\nThis 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.\n\n## 🚀 Why this Framework?\n\n* **Batteries Included**: 150+ Technical Indicators (RSI, MACD, etc.) ready out of the box.\n* **Infrastructure as Code**: Native Helm charts for easy scaling on K8s.\n* **Data Consistency**: Built-in caching and PostgreSQL persistence for trade history and market data.\n* **Backtesting to Production**: One class handles local testing, hyperparameter optimization, and live execution.\n\n\n## 🛠 System Architecture\n\nThe system is designed to be lightweight and stateless. Each \"Bot\" is a containerized instance triggered by a schedule.\n\n1. **Ingestion**: Fetches data from Yahoo Finance (with DB caching).\n2. **Analysis**: Enriches data with the `ta` library (Technical Analysis).\n3. **Execution**: `BotClass` manages the state of your portfolio in PostgreSQL.\n4. **Monitoring**: Real-time performance tracking via the included Dashboard.\n\n\n## ⚡ Quick Start\n\n### 1. Requirements\n\n* **Python 3.12+** (We recommend [uv](https://github.com/astral-sh/uv) for speed)\n* **Docker** (for local DB)\n\n### 2. Launch Local Environment\n\n```bash\n# Start PostgreSQL\ndocker run -d --name pg-trading -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=tradingbot -p 5432:5432 postgres:17-alpine\n\n# Install project\nuv sync\nexport POSTGRES_URI=\"postgresql://postgres:pass@localhost:5432/tradingbot\"\n\n```\n\n### 3. Your First Strategy\n\nCreate a simple RSI Mean Reversion bot in seconds:\n\n```python\nfrom tradingbot.utils.botclass import Bot\n\nclass RSIBot(Bot):\n    def __init__(self):\n        super().__init__(\"RSIBot\", \"AAPL\", interval=\"1m\", period=\"1d\")\n    \n    def decisionFunction(self, row):\n        if row[\"momentum_rsi\"] \u003c 30: return 1  # Buy\n        if row[\"momentum_rsi\"] \u003e 70: return -1 # Sell\n        return 0\n\nif __name__ == \"__main__\":\n    bot = RSIBot()\n    bot.run() # Single iteration\n```\n\n### 4. Local Development \u0026 Testing\n\n**Backtest your strategy** before going live:\n\n```python\nbot = RSIBot()\nresults = bot.local_backtest(initial_capital=10000.0)\nprint(f\"Sharpe Ratio: {results['sharpe_ratio']:.2f}\")\nprint(f\"Yearly Return: {results['yearly_return']:.2%}\")\n```\n\n**Optimize hyperparameters** automatically:\n\n```python\nclass RSIBot(Bot):\n    # Define search space\n    param_grid = {\n        \"rsi_buy\": [25, 30, 35],\n        \"rsi_sell\": [65, 70, 75],\n    }\n    \n    def __init__(self, rsi_buy=30.0, rsi_sell=70.0, **kwargs):\n        super().__init__(\"RSIBot\", \"AAPL\", interval=\"1m\", period=\"1d\", **kwargs)\n        self.rsi_buy = rsi_buy\n        self.rsi_sell = rsi_sell\n    \n    def decisionFunction(self, row):\n        if row[\"momentum_rsi\"] \u003c self.rsi_buy: return 1\n        if row[\"momentum_rsi\"] \u003e self.rsi_sell: return -1\n        return 0\n\n# Optimize and backtest\nbot = RSIBot()\nbot.local_development()  # Finds best params, then backtests\n```\n\n**Key Features**:\n- Data pre-fetching: Historical data fetched once, reused for all parameter combinations\n- Database caching: Data persisted to DB, subsequent runs are instant\n- Parallel execution: Uses multiple CPU cores automatically\n\n\n## 📈 Dashboard \u0026 Monitoring\n\nThe framework includes a built-in visualization suite to track your bots' performance.\n\n![Portfolio Overview](docs/overview.png)\n\n**Overview Dashboard** shows:\n- Current Worth, Total Return %, Annualized Return %\n- Sharpe Ratio, Sortino Ratio, Max Drawdown %\n- Volatility, Total Trades, Start Date\n\n![Bot Detail Page](docs/detailpage.png)\n\n**Bot Detail Page** includes:\n- Portfolio value charts, daily returns distribution\n- Monthly returns heatmap, drawdown visualization\n- Current holdings table, complete trade history\n\nThe dashboard is deployed automatically with the Helm chart. See [Deployment](#-deployment) for setup.\n\n\n## 🏗 Deployment\n\n### Production (Kubernetes)\n\nThe system treats every bot as a **CronJob**. Define your schedule in `values.yaml` and deploy:\n\n**1. Create Kubernetes Secret**:\n\n```bash\n# Create .env file with:\n# POSTGRES_PASSWORD=yourpassword\n# POSTGRES_URI=postgresql://postgres:yourpassword@psql-service:5432/postgres\n# OPENROUTER_API_KEY=yourkey (if using AI bots)\n# BASIC_AUTH_PASSWORD=yourpassword (for dashboard)\n\n# Create namespace\nkubectl create namespace tradingbots-2025\n\n# Create secret\nkubectl create secret generic tradingbot-secrets \\\n  --from-env-file=.env \\\n  --namespace=tradingbots-2025\n```\n\n**2. Configure Bots**:\n\n```yaml\n# helm/tradingbots/values.yaml\nbots:\n  - name: rsibot\n    schedule: \"*/5 * * * 1-5\" # Every 5 mins, Mon-Fri\n```\n\n**3. Deploy**:\n\n```bash\nhelm upgrade --install tradingbots \\\n  ./helm/tradingbots \\\n  --create-namespace \\\n  --namespace tradingbots-2025\n```\n\n**PostgreSQL** is automatically deployed via Helm (if `postgresql.enabled: true` in `values.yaml`).\n\n**For detailed guides**, see:\n- [Deployment Overview](docs/deployment/overview.md) - Complete deployment options\n- [Kubernetes Deployment](docs/deployment/kubernetes.md) - Cluster setup\n- [Helm Charts](docs/deployment/helm.md) - Configuration details\n\n\n## 🧰 Developer Reference\n\n### Bot Implementation Levels\n\n**1. Simple (Recommended)**: `decisionFunction(row)`\nFor strategies based on single-row technical indicators:\n\n```python\ndef decisionFunction(self, row):\n    if row[\"momentum_rsi\"] \u003c 30: return 1\n    if row[\"momentum_rsi\"] \u003e 70: return -1\n    return 0\n```\n\n**2. Medium Complexity**: Override `makeOneIteration()`\nFor external APIs or custom data processing:\n\n```python\ndef makeOneIteration(self):\n    fear_greed = get_fear_greed_index()  # External API\n    if fear_greed \u003e= 70: self.buy(\"QQQ\")\n    return 1\n```\n\n**3. Complex**: Portfolio Optimization\nFor multi-asset strategies and rebalancing:\n\n```python\ndef makeOneIteration(self):\n    data = self.getYFDataMultiple([\"QQQ\", \"GLD\", \"TLT\"])\n    weights = optimize_portfolio(data)  # Your optimization\n    self.rebalancePortfolio(weights)\n    return 0\n```\n\n### Key Methods\n\n| Method | Description |\n| --- | --- |\n| `getYFDataWithTA()` | Fetches OHLCV + 150 indicators. |\n| `decisionFunction(row)` | Logic applied to every candle. Return `-1, 0, 1`. |\n| `makeOneIteration()` | Override for custom logic. |\n| `local_backtest()` | Simulates strategy performance on historical data. |\n| `local_development()` | Optimize hyperparameters + backtest. |\n| `buy(symbol)` / `sell(symbol)` | Automated portfolio and DB logging. |\n| `rebalancePortfolio(weights)` | Rebalance to target weights. |\n| `run_ai(system_prompt, user_message)` | Runs AI with tools (main LLM); returns model response. Requires `OPENROUTER_API_KEY`. |\n| `run_ai_simple(system_prompt, user_message)` | Single-turn, no tools (cheap LLM); for summarization, extraction, classification. |\n| `run_ai_simple_with_fallback(system_prompt, user_message, sanity_check=..., fallback_to_main=True)` | Cheap LLM first; validates output; retries with main LLM if sanity check fails. |\n\n### AI Tools (LangChain + OpenRouter)\n\nTwo LLMs: **main** (OPENROUTER_MAIN_MODEL, default `deepseek/deepseek-v3.2`) for tool-using flows; **cheap** (OPENROUTER_CHEAP_MODEL, default `openai/gpt-oss-120b`) for simple single-turn text tasks. Set `OPENROUTER_API_KEY` (required); optionally set the two model env vars.\n\n**With tools (main LLM):**\n\n```python\nresponse = bot.run_ai(\n    system_prompt=\"You are a trading assistant.\",\n    user_message=\"Summarize my recent trades and portfolio.\"\n)\nprint(response)  # Model response as string\n```\n\n**Simple tasks, no tools (cheap LLM):** summarization, extraction, classification, rewriting:\n\n```python\nsummary = bot.run_ai_simple(\n    system_prompt=\"You summarize in one sentence.\",\n    user_message=\"Summarize: ...\"\n)\n```\n\n**Cheap-first with fallback:** Try cheap LLM first, validate output for sanity, and retry with main LLM if the result fails. Use for simple tasks when you want to save cost but guarantee sane results:\n\n```python\nresult = bot.run_ai_simple_with_fallback(\n    system_prompt=\"You classify sentiment.\",\n    user_message=\"Classify as buy/hold/sell: ...\",\n    sanity_check=None,   # optional; default rejects empty/refusal/error prefix\n    fallback_to_main=True,\n)\n```\n\n**Tools available to the model (when using run_ai):**\n\n1. **get_market_data(symbol, period)** – Market data (OHLCV), default last two weeks.\n2. **get_portfolio_status()** – Current portfolio worth (USD) and holdings.\n3. **get_recent_trades(limit)** – Recent trades; for sells, profit of the closed trade is shown.\n4. **get_stock_news(symbol, limit)** – Recent news for a symbol (title, link, publisher, published_at) from the database.\n5. **get_stock_earnings(symbol, limit)** – Recent earnings dates and EPS (estimate, reported, surprise %) for a symbol from the database.\n6. **get_stock_insider_trades(symbol, limit)** – Recent insider transactions (insider, type, shares, value) for a symbol from the database.\n\nSee [AI Tools Guide](docs/guides/ai-tools.md) and [AITools API](docs/api/aitools.md) for details.\n\n### Portfolio Structure\n\nPortfolio is stored as JSON in the database:\n\n```python\nportfolio = {\n    \"USD\": 10000.0,      # Cash\n    \"QQQ\": 5.5,          # Holdings (quantity, not value)\n    \"AAPL\": 10.0,        # More holdings\n}\n```\n\nAccess via: `bot.dbBot.portfolio.get(\"USD\", 0)`\n\n### Available Indicators\n\nAccess over 150 indicators via the `row` object:\n\n* **Trend**: `trend_macd`, `trend_adx`, `trend_ichimoku_a`, `trend_sma_fast`, `trend_sma_slow`\n* **Momentum**: `momentum_rsi`, `momentum_stoch`, `momentum_ao`, `momentum_roc`, `momentum_ppo`\n* **Volatility**: `volatility_bbh` (Bollinger High), `volatility_bbl` (Bollinger Low), `volatility_atr`\n* **Volume**: `volume_vwap`, `volume_obv`, `volume_mfi`\n\nSee [Technical Analysis Guide](docs/guides/technical-analysis.md) for complete list.\n\n\n## 📖 Documentation\n\n**Online Documentation**: [justinguese.github.io/python_tradingbot_framework/](https://justinguese.github.io/python_tradingbot_framework/)\n\n### Getting Started\n* [Quick Start Guide](docs/getting-started/quick-start.md) - Complete local development workflow with PostgreSQL setup, bot creation at different abstraction levels, backtesting, and hyperparameter tuning\n* [Installation](docs/getting-started/installation.md) - System requirements and dependency installation\n* [Creating a Bot](docs/getting-started/creating-a-bot.md) - Detailed bot creation patterns and examples\n\n### Deployment\n* [Deployment Overview](docs/deployment/overview.md) - Kubernetes vs local deployment options\n* [Kubernetes Deployment](docs/deployment/kubernetes.md) - Cluster setup and configuration\n* [Helm Charts](docs/deployment/helm.md) - Bot scheduling and Helm configuration\n\n### Guides\n* [Technical Analysis](docs/guides/technical-analysis.md) - Complete indicator reference\n* [Portfolio Management](docs/guides/portfolio-management.md) - Advanced portfolio operations\n* [Local Development](docs/guides/local-development.md) - Development workflows\n* [AI Tools](docs/guides/ai-tools.md) - LangChain + OpenRouter tools; cheap-first with fallback and sanity checks\n\n### API Reference\n* [Bot API](docs/api/bot.md) - Complete Bot class documentation\n* [Data Service](docs/api/data-service.md) - Data fetching and caching\n* [Portfolio Manager](docs/api/portfolio-manager.md) - Trading operations\n* [AITools API](docs/api/aitools.md) - `run_ai_with_tools`, `run_ai_simple`, `run_ai_simple_with_fallback`\n\n## 🎯 Example Bots\n\n* **eurusdtreebot.py** - Decision tree-based strategy for EUR/USD\n* **feargreedbot.py** - Uses Fear \u0026 Greed Index API for market sentiment\n* **swingtitaniumbot.py** - Swing trading strategy\n* **xauzenbot.py** - Gold (XAU) trading bot\n* **sharpeportfoliooptweekly.py** - Portfolio optimization with Sharpe ratio\n* **aihedgefundbot.py** - AI-driven portfolio rebalancing\n* **deepseektoolbot.py** - AI with tools (research + submit weights); cheap LLM sanity-check and main-LLM retry\n* **gptbasedstrategytabased.py** - GPT-based strategy with technical analysis\n\nSee [Example Bots](docs/examples/example-bots.md) for implementation details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FJustinGuese%2Fpython_tradingbot_framework","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FJustinGuese%2Fpython_tradingbot_framework","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FJustinGuese%2Fpython_tradingbot_framework/lists"}