Skip to content

FinnSven/TradingAnalytics

Repository files navigation

Trading Analytics API

A production-grade financial trading analytics API built through agentic development with Claude Code. Combines real-time market data, mathematical technical indicators, AI-powered analysis, and portfolio management into a clean REST API.

How This Was Built

This project was developed using Claude Code as the primary development tool -- not as a code-completion assistant, but as an agentic coding partner that I directed through architectural decisions and implementation.

What I (human) decided:

  • Architecture: Two-project structure separating business logic from the API surface
  • Domain model design: What types represent (quotes, indicators, signals, portfolios) and how they relate
  • Which technical indicators to implement and their mathematical specifications (RSI with Wilder's smoothing, MACD with dual EMA, Bollinger Bands with %B and bandwidth)
  • API surface design: Endpoint structure, batch limits, parameter defaults
  • Claude prompt engineering: The structured JSON prompts that drive AI analysis quality
  • Integration choices: Alpha Vantage for data, Claude API for AI, SignalR for real-time

What Claude Code built under my direction:

  • Indicator calculation implementations from mathematical specifications
  • HTTP client wiring and JSON response parsing
  • Controller boilerplate following the established pattern
  • Test scaffolding for indicator and portfolio logic
  • Dockerfile and docker-compose configuration

The point isn't that AI wrote the code -- it's that I orchestrated a production system through clear architectural decisions and let the AI handle implementation details efficiently.

Architecture

TradingAnalytics/
├── src/
│   ├── TradingAnalytics.Core/           # Business logic (no framework dependencies)
│   │   ├── AI/                          # Claude API integration
│   │   ├── MarketData/                  # Alpha Vantage provider
│   │   ├── Models/                      # Domain models (records + classes)
│   │   ├── News/                        # News provider & sentiment analysis
│   │   ├── Portfolio/                   # Portfolio analysis & metrics
│   │   └── TechnicalAnalysis/           # Indicator engine
│   │       └── Indicators/              # RSI, MACD, Bollinger, SMA, EMA
│   └── TradingAnalytics.Api/            # ASP.NET Core API
│       ├── Controllers/                 # REST endpoints
│       └── Hubs/                        # SignalR real-time streaming
├── tests/
│   └── TradingAnalytics.Tests/          # xUnit + FluentAssertions
├── Dockerfile
├── docker-compose.yml
└── CLAUDE.md                            # Agent-readable project context

Why this structure:

  • Core has zero ASP.NET dependencies -- it's a pure library. You could wrap it in a gRPC service, a CLI tool, or a background worker without touching the business logic.
  • Indicators implement ITechnicalIndicator -- adding a new indicator means one class, zero changes to existing code.
  • Services use IHttpClientFactory for proper HTTP lifecycle management.
  • All AI responses parse into strongly-typed records with graceful fallback when Claude returns unexpected JSON.

Technical Indicators

Indicator Implementation Signals
RSI Wilder's smoothing (14-period default) Overbought (>70), Oversold (<30), StrongBuy (<20), StrongSell (>80)
MACD Dual EMA (12/26/9 default) Bullish/bearish crossovers, trend continuation
Bollinger Bands SMA + 2*StdDev (20-period default) %B position, bandwidth squeeze, band bounces
SMA Arithmetic mean Price crossover signals
EMA Exponential weighting Crossovers with trend strength detection

The indicator engine aggregates individual signals into an overall signal with trend determination and support/resistance levels calculated via pivot points.

API Endpoints

Quotes

GET  /api/quotes/{symbol}          # Current quote
POST /api/quotes/batch             # Multiple quotes (max 10)
GET  /api/quotes/{symbol}/history  # Historical OHLCV (max 365 days)
GET  /api/quotes/health            # Provider status

Technical Analysis

GET  /api/analysis/{symbol}/technical          # All indicators + trend + signal
GET  /api/analysis/{symbol}/indicator/{name}   # Single indicator
GET  /api/analysis/{symbol}/ai                 # Claude AI analysis
GET  /api/analysis/{symbol}/full               # Combined technical + AI
GET  /api/analysis/indicators                  # Available indicator names

Trading Signals

GET  /api/signals/{symbol}         # AI-powered signal with entry/stop/target
POST /api/signals/batch            # Signals for multiple symbols (max 5)
GET  /api/signals/{symbol}/quick   # Technical-only signal (no AI call)

Portfolio

POST /api/portfolio/analyze        # Holdings analysis with metrics
POST /api/portfolio/insights       # AI portfolio insights
POST /api/portfolio/full           # Both analysis + AI insights

Sentiment

GET  /api/sentiment/{symbol}       # News sentiment analysis
GET  /api/sentiment/{symbol}/news  # Raw news articles
GET  /api/sentiment/market         # Market-wide sentiment
POST /api/sentiment/analyze        # Analyze custom article

Real-Time (SignalR)

/hubs/quotes  # WebSocket endpoint for live quote streaming

Testing

40 unit tests covering the core business logic:

  • RSI Calculator (8 tests): Signal boundaries, value ranges, custom periods, edge cases
  • MACD Calculator (7 tests): Crossover detection, histogram values, insufficient data
  • Bollinger Bands (7 tests): Band relationships, bandwidth vs volatility, %B positioning
  • Technical Analysis Service (8 tests): Signal aggregation, trend detection, support/resistance, mocked data provider
  • Portfolio Metrics (10 tests): Diversification scoring, sector concentration, beta/volatility estimates, gain/loss calculations, graceful API failure fallback
dotnet test

Running

Local Development

# Set API keys
export AlphaVantage__ApiKey=your_alpha_vantage_key
export Claude__ApiKey=your_claude_api_key

# Run
dotnet run --project src/TradingAnalytics.Api

# Swagger UI available at http://localhost:5000

Docker

ALPHA_VANTAGE_API_KEY=your_key CLAUDE_API_KEY=your_key docker-compose up --build

# API at http://localhost:8080

Example Requests

# Technical analysis
curl http://localhost:8080/api/analysis/AAPL/technical?days=90

# Trading signal
curl http://localhost:8080/api/signals/MSFT

# Portfolio analysis
curl -X POST http://localhost:8080/api/portfolio/analyze \
  -H "Content-Type: application/json" \
  -d '{"holdings": [
    {"symbol": "AAPL", "shares": 100, "averageCost": 150.00},
    {"symbol": "MSFT", "shares": 50, "averageCost": 300.00},
    {"symbol": "GOOGL", "shares": 25, "averageCost": 140.00}
  ]}'

# Sentiment
curl http://localhost:8080/api/sentiment/NVDA

Configuration

{
  "AlphaVantage": {
    "ApiKey": "YOUR_KEY"
  },
  "Claude": {
    "ApiKey": "YOUR_KEY",
    "Model": "claude-sonnet-4-20250514"
  }
}

API keys can be set via environment variables (AlphaVantage__ApiKey, Claude__ApiKey) or appsettings.json.

Stack

  • .NET 8, ASP.NET Core
  • SignalR for WebSocket streaming
  • Claude API for AI analysis
  • Alpha Vantage for market data
  • xUnit + FluentAssertions + NSubstitute for testing
  • Docker with multi-stage build

Author

Jamie Hussey -- Senior Backend Developer, Gothenburg

About

AI-powered financial trading analytics API - .NET 8, Claude API, SignalR, technical indicators

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors