AI News HubLIVE
In-site rewrite5 min read

I built TradingSpy: local, privacy-first AI trading assistant(First Open Source)

TradingSpy is an open-source local AI trading research workstation that integrates market heatmaps, news catalysts, strategy generation, Backtrader backtesting, and transparent agent runs in one Docker app. It is privacy-first, with all data stored locally, no external accounts, and no cloud dependency. Supports multiple LLM providers and a broad range of financial data sources, suitable for traders and developers for strategy research, backtesting, and signal analysis.

SourceHacker News AIAuthor: mrhustlex

Notifications You must be signed in to change notification settings

Fork 0

Star 0

BranchesTags

Open more actions menu

Folders and files

NameName

Last commit message

Last commit date

Latest commit

History

28 Commits

28 Commits

.github

.github

backend

backend

docs/images

docs/images

frontend

frontend

scripts

scripts

searxng

searxng

.dockerignore

.dockerignore

.env.example

.env.example

.gitignore

.gitignore

CHANGELOG.md

CHANGELOG.md

CODE_OF_CONDUCT.md

CODE_OF_CONDUCT.md

CONTRIBUTING.md

CONTRIBUTING.md

LICENSE

LICENSE

README.md

README.md

SECURITY.md

SECURITY.md

SUPPORT.md

SUPPORT.md

docker-compose.yml

docker-compose.yml

package.json

package.json

Repository files navigation

Local-first AI trading research: market heatmaps, news catalysts, strategy generation, Backtrader backtests, and transparent agent runs in one Docker app.

TradingSpy is an open-source research workstation for traders and builders who want to ask questions, inspect market context, generate strategy ideas, and test them against real historical candles without wiring together five separate tools.

It is not a broker and it does not place trades. It is a local research environment for analysis, backtesting, and strategy iteration. Fully open-source, zero data privacy concerns, and free of charge.

What Could You Do with TradingSpy?

Trading Companion — Chat with your market data, strategies, news, heatmaps, and backtest history.

Strategy Researcher — Research to find the best trading strategies until it beats the baseline strategy.

Trading Trend Prediction — Leverage calculation and LLM with the support and resistance lines to simulate expected stock trend.

Trading Signal Analysis — The tool analyzes the real-time movement, incorporates peer stocks, insider trading information, and trading indicators.

Key Design

TradingSpy is designed with a hybrid approach: traditional data visualisation for quick, deterministic results combined with loop-engineering-powered agents as a trading companion.

Features

Feature What it does

Market Intelligence Real-time quotes, sector heatmaps, industry performance, insider activity, news search, and fundamentals — all in one query.

AI Strategy Generation Describe a trading thesis in plain English; get a working Backtrader strategy with syntax and runtime validation.

Automated Backtesting Every generated strategy is backtested against downloaded candles with configurable parameter sweeps.

Benchmark Comparison Every result is compared to buy-and-hold and any saved strategy. Underperformers are rejected automatically.

Loop Engineering Set a goal ("beat buy-and-hold", "find undervalued semiconductors") and the agent iterates until it succeeds — no babysitting required.

Transparent Agent Runs Every tool call, validation failure, rejection reason, and accepted result is logged and visible in the Task Center.

Multi-Provider LLM Google AI Studio, Mistral, OpenRouter, NVIDIA, LiteLLM, Ollama (local), AWS Bedrock, GCP Vertex AI, and Azure OpenAI.

OpenAI-Compatible API Use TradingSpy as a backend for scripts, other agents, or custom integrations via /v1/chat/completions.

Local-First Architecture All data stored under backend/data/. No external accounts, no telemetry, no cloud dependency.

Agents

Agent Example Prompt What it does

Strategy Race Generate until it beats buy and hold for QQQ. Use daily candles.

Improve EMA_Trend for TQQQ using daily candles. Generate until it beats EMA_Trend, not buy and hold. Generates strategies based on selected modes (tick data, research papers, etc.) from the AI Strategy Studio. Improves or compares strategies over rounds — can use a previous accepted version or selected baseline, generate candidates, backtest them, and accept only versions that beat the target benchmark.

Signal Analysis Predict the next move for btc-usd for daily interval Reads recent bars and support/resistance levels to predict the price trend.

Stock Screening Scan AI stocks until you find 10 which are good enough on fundamentals Uses the fundamental scanner to search for undervalued stocks. Screens a universe for valuation/growth/profitability candidates, enriches passing names with market context, news, options, and insider summaries. Can continue with a wider universe.

Chat Give me a daily market brief with breadth, strongest and weakest industries, important news, and earnings. Pulls data from yfinance to summarize daily market information.

Background Runs

If the request involves long-running work, the UI creates a background run through /api/agent/runs. Background runs are stored locally, visible in the Task Center, and support:

Method Endpoint Purpose

GET /api/agent/runs List recent runs

GET /api/agent/runs/{run_id} Poll full state

POST /api/agent/runs/{run_id}/stop Request cancellation

POST /api/agent/runs/{run_id}/continue Continue a completed or stopped run

DELETE /api/agent/runs/{run_id} Delete a single run

DELETE /api/agent/runs Clean all records

For strategy workflows, the agent is deliberately conservative: it validates generated code before backtesting, rejects zero-trade results instead of treating 0% ROI as meaningful, and reports validation failures and runtime errors as part of the public run log. It supports custom agent instructions, answer budget, run detail, sequential/parallel execution, and custom battle parameters.

For insider buy/sell questions, the assistant uses deterministic tool-backed responses. It reports only returned records, separates open-market buys/sells from grants or awards, and says so if the feed is unavailable instead of filling gaps from memory.

Market Overview UI

Not every question needs an agent. TradingSpy ships a full market dashboard for quick, deterministic results.

Component Details

Sector Heatmap Color-coded grid of 25+ industry proxy ETFs grouped by sector. 16 time periods (1 min – max + YTD), extended hours toggle, search/filter, custom groups, and an Explain button that sends the heatmap to the AI assistant for analysis. Two display modes: industry ETFs or watchlist stocks.

Indices Banner Top-of-page bar showing S&P 500, Dow Jones, NASDAQ 100, and Russell 2000 with live prices and percentage changes.

Industry Movements Tracks individual stock price changes across 12 time windows (1 min to 1 year) for 68+ major US stocks. Universe presets: High Cap, Semis, Software/AI, Leverage.

Watchlist & Intelligence Auto-sync watchlists, real-time batch quotes, deep-dive panel (company info, technicals, news, insider activity), and embedded candlestick charts.

Data Sources and Markets Supported

Data Sources

Source What it provides

Yahoo Finance Price quotes, OHLCV candles (daily, intraday, extended-hours), fundamentals, insider transactions, analyst recommendations, earnings dates, options chains, sector/industry metadata, screener queries. Primary data backbone.

SearXNG Privacy-respecting metasearch for web and news — financial news, analyst opinions, macro events, catalyst research. Runs locally via Docker or standalone.

DuckDuckGo Fallback web search when SearXNG is unavailable. HTML scraping + instant answer API.

arXiv Academic papers on quantitative finance and algorithmic trading. Abstract and full-text PDF reading.

Backtrader Local backtesting engine for strategy execution, parameter optimization, and benchmark comparison.

Supported Markets

Any Yahoo Finance-compatible symbol works. Coverage varies by symbol and upstream source.

Market Examples Suffix

United States AAPL, NVDA, QQQ, SPY —

London AZN.L, HSBA.L .L

Hong Kong 0700.HK .HK

Japan 7203.T .T

India RELIANCE.NS .NS

Canada SHOP.TO .TO

Australia BHP.AX .AX

Germany / France / UK / Eurozone ^GDAXI, ^FCHI, ^FTSE, ^STOXX50E ^ prefix

China 000001.SS .SS

Crypto BTC-USD, ETH-USD -USD

Commodities GC=F (Gold), CL=F (Oil) =F

Global Index Coverage

Region Indices

United States S&P 500, Dow Jones, NASDAQ 100, Russell 2000, VIX

Europe STOXX 50, FTSE 100, DAX, CAC 40

Asia Nikkei 225, Hang Seng, Shanghai Composite, ASX 200

Commodities Gold Futures, Crude Oil

Crypto Bitcoin, Ethereum

LLM Providers Supported

Provider Environment variable Example default model

Google AI Studio GOOGLE_AI_STUDIO_API_KEY gemini-2.5-flash

Mistral MISTRAL_API_KEY mistral-large-latest

OpenRouter OPENROUTER_API_KEY openai/gpt-4o-mini

NVIDIA NVIDIA_API_KEY nvidia/llama-3.1-405b-instruct

LiteLLM LITELLM_API_KEY, LITELLM_BASE_URL Your proxy's model ID

Ollama (local) OLLAMA_BASE_URL; no API key required qwen2.5-coder:7b

Additional providers: AWS Bedrock, GCP Vertex AI, and Azure OpenAI are supported via the LiteLLM proxy. Point LITELLM_BASE_URL at your proxy and configure provider credentials there.

Keys may be stored in .env/backend/.env or entered in the app's Settings page. Never commit a real key. See .env.example for every supported setting.

Quick Start

  1. Clone and configure

git clone https://github.com/mrhustlex/TradingSpy-TradingAgentService.git cd TradingSpy cp .env.example .env

Add at least one provider key to .env:

GOOGLE_AI_STUDIO_API_KEY=your-gemini-key DEFAULT_PROVIDER=google_ai_studio DEFAULT_MODEL=gemini-2.5-flash

Or use Ollama (no API key required):

ollama pull qwen2.5-coder:7b

DEFAULT_PROVIDER=ollama DEFAULT_MODEL=qwen2.5-coder:7b OLLAMA_BASE_URL=http://host.docker.internal:11434/v1

You can also configure providers later in the app's Settings page.

  1. Run

docker compose up -d --build

Service URL

App http://localhost:3000

Backend API http://localhost:8000

API docs http://localhost:8000/docs

SearXNG http://localhost:8080

  1. Stop

docker compose down

Runtime data remains under backend/data/. Pull updates and rebuild with git pull && docker compose up -d --build.

Manual Development

Backend

cd backend python3.11 -m venv .venv source .venv/bin/activate pip install -r requirements.txt uvicorn main:app --reload --host 0.0.0.0 --port 8000

Use Python 3.11. The pinned data-science dependencies are not reliable with Python 3.13.

Frontend

cd frontend npm ci npm run dev

Open http://localhost:5173.

Optional: SearXNG for web/news search

npm run dev:searxng # start npm run stop:searxng # stop

This starts only SearXNG at localhost:8080. Alternatively, docker compose up -d searxng.

Architecture

flowchart LR User["User / Browser"] --> Frontend["React Frontend localhost:3000"] Frontend --> Backend["FastAPI Backend localhost:8000"] Backend --> ChatAgent["Tool-Using Chat Assistant short research + tool checks"] Backend --> WorkflowAgent["Background Workflow Agents strategy_create / strategy_race / market_review / fundamental_screener"] Backend --> RemoteAgents["Remote Agent Outputs OpenAI-compatible / ACP / A2A"] Backend --> Backtest["Backtrader Engine backtests + optimization"] Backend --> Market["Market Intelligence yfinance + heatmaps + news"] Backend --> Store["Local Data TinyDB + candles + strategies"] Backend --> Search["SearXNG localhost:8080"] ChatAgent --> LLM["Validated LLM Providers Google AI Studio / Mistral / OpenRouter / LiteLLM"] WorkflowAgent --> LLM RemoteAgents --> ChatAgent RemoteAgents --> WorkflowAgent

Loading

Local Data

All runtime data is stored locally and ignored by Git:

backend/data/ ├── db.json ├── system_settings.json ├── market_data/local_user/ ├── strategies/local_user/ ├── results/local_user/ ├── optimization_history/ └── temp_datas/

Back these up separately if the results matter to you.

Reproducibility

What Deterministic?

Saved strategy against same candles, dates, capital, commission, parameters Yes

LLM-generated strategy code No — non-deterministic across runs

Live quotes, fundamentals, insider records, heatmaps, news No — changes over time

Model aliases and upstream provider behavior May change — use explicit model IDs when comparing

Backtest performance Depends on period and assumptions — not

[truncated for AI cost control]