Big refactoring
Some checks failed
Deploy / lint (push) Failing after 21s
Deploy / test (push) Has been skipped
Deploy / deploy (push) Has been skipped

This commit is contained in:
Dennis Thiessen
2026-03-03 15:20:18 +01:00
parent 181cfe6588
commit 0a011d4ce9
55 changed files with 6898 additions and 544 deletions

View File

@@ -0,0 +1,27 @@
{
"enabled": true,
"name": "Code Quality Analyzer",
"description": "Analyzes modified source code files for potential improvements including code smells, design patterns, best practices, readability, maintainability, and performance optimizations",
"version": "1",
"when": {
"type": "fileEdited",
"patterns": [
"*.py",
"*.ts",
"*.tsx",
"*.js",
"*.jsx",
"*.java",
"*.go",
"*.rs",
"*.cpp",
"*.c",
"*.h",
"*.cs"
]
},
"then": {
"type": "askAgent",
"prompt": "Analyze the modified code for potential improvements. Check for: 1) Code smells and anti-patterns, 2) Opportunities to apply design patterns, 3) Best practices violations, 4) Readability improvements, 5) Maintainability concerns, 6) Performance optimization opportunities. Provide specific, actionable suggestions while ensuring functionality remains intact."
}
}

View File

@@ -0,0 +1,19 @@
{
"enabled": true,
"name": "Update Docs on Code Change",
"description": "Monitors Python source files and prompts agent to update README.md or docs folder when code changes are saved",
"version": "1",
"when": {
"type": "fileEdited",
"patterns": [
"*.py",
"requirements.txt",
"pyproject.toml",
"alembic.ini"
]
},
"then": {
"type": "askAgent",
"prompt": "A source file was just modified. Review the changes and update the documentation in README.md to reflect any new features, API changes, configuration updates, or important implementation details. Keep the documentation clear, accurate, and up-to-date."
}
}

View File

@@ -1,80 +1,5 @@
{
"mcpServers": {
"context7": {
"gallery": true,
"command": "npx",
"args": [
"-y",
"@upstash/context7-mcp@latest"
],
"env": {
"HTTP_PROXY": "http://aproxy.corproot.net:8080",
"HTTPS_PROXY": "http://aproxy.corproot.net:8080"
},
"type": "stdio"
},
"aws.mcp": {
"command": "uvx",
"timeout": 100000,
"transport": "stdio",
"args": [
"mcp-proxy-for-aws@latest",
"https://aws-mcp.us-east-1.api.aws/mcp"
],
"env": {
"AWS_PROFILE": "409330224121_sc-ps-standard-admin",
"AWS_REGION": "eu-central-2",
"HTTP_PROXY": "http://aproxy.corproot.net:8080",
"HTTPS_PROXY": "http://aproxy.corproot.net:8080",
"SSL_CERT_FILE": "/Users/taathde3/combined-ca-bundle.pem",
"REQUESTS_CA_BUNDLE": "/Users/taathde3/combined-ca-bundle.pem"
},
"disabled": false,
"autoApprove": []
},
"aws.eks.mcp": {
"command": "uvx",
"timeout": 100000,
"transport": "stdio",
"args": [
"mcp-proxy-for-aws@latest",
"https://eks-mcp.eu-central-1.api.aws/mcp",
"--service",
"eks-mcp"
],
"env": {
"AWS_PROFILE": "409330224121_sc-ps-standard-admin",
"AWS_REGION": "eu-central-2",
"HTTP_PROXY": "http://aproxy.corproot.net:8080",
"HTTPS_PROXY": "http://aproxy.corproot.net:8080",
"SSL_CERT_FILE": "/Users/taathde3/combined-ca-bundle.pem",
"REQUESTS_CA_BUNDLE": "/Users/taathde3/combined-ca-bundle.pem"
},
"disabled": false,
"autoApprove": []
},
"aws.ecs.mcp": {
"command": "uvx",
"timeout": 100000,
"transport": "stdio",
"args": [
"mcp-proxy-for-aws@latest",
"https://ecs-mcp.us-east-1.api.aws/mcp",
"--service",
"ecs-mcp"
],
"env": {
"AWS_PROFILE": "409330224121_sc-ps-standard-admin",
"AWS_REGION": "eu-central-2",
"HTTP_PROXY": "http://aproxy.corproot.net:8080",
"HTTPS_PROXY": "http://aproxy.corproot.net:8080",
"SSL_CERT_FILE": "/Users/taathde3/combined-ca-bundle.pem",
"REQUESTS_CA_BUNDLE": "/Users/taathde3/combined-ca-bundle.pem"
},
"disabled": false,
"autoApprove": []
},
"iaws.support.agent": {
"command": "uvx",
"args": [

View File

@@ -0,0 +1 @@
{"specId": "71b6e4c6-56fa-4d43-b1ca-c4a89e8c8b5e", "workflowType": "requirements-first", "specType": "feature"}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,222 @@
# Requirements Document
## Introduction
The Intelligent Trade Recommendation System enhances the Signal Dashboard platform by providing clear, actionable trading recommendations with confidence scoring, multiple price targets, and probability estimates. The system addresses critical gaps in the current trade setup generation: contradictory signal detection, single-target limitations, and lack of directional guidance for non-professional traders.
The system analyzes multi-dimensional signals (sentiment, technical, momentum, S/R positioning) to recommend both LONG and SHORT directions with confidence scores, identifies multiple S/R-based price targets with probability estimates, and detects signal conflicts to prevent contradictory recommendations.
## Glossary
- **Trade_Recommendation_Engine**: The core system component that analyzes signals and generates directional recommendations with confidence scores
- **Direction_Analyzer**: Component that evaluates LONG vs SHORT direction based on signal alignment
- **Target_Generator**: Component that identifies multiple S/R levels as price targets
- **Probability_Estimator**: Component that calculates likelihood of reaching each target
- **Signal_Conflict_Detector**: Component that identifies contradictions between sentiment, technical, and momentum signals
- **Recommendation_Summary**: User-facing output containing recommended action, confidence, reasoning, and risk level
- **S/R_Level**: Support/Resistance level with strength score and price
- **Signal_Alignment**: Degree of agreement between sentiment, technical, momentum, and fundamental dimensions
- **Confidence_Score**: Percentage (0-100%) indicating likelihood of success for a directional recommendation
- **Target_Probability**: Percentage likelihood of price reaching a specific target level
- **ATR**: Average True Range, volatility measure used for stop-loss calculation
- **R:R_Ratio**: Risk-to-Reward ratio comparing potential profit to potential loss
- **Composite_Score**: Weighted aggregate score (0-100) from all dimensions
- **Dimension_Score**: Individual score for technical, sr_quality, sentiment, fundamental, or momentum dimension
## Requirements
### Requirement 1: Bidirectional Trade Setup Generation
**User Story:** As a trader, I want to see both LONG and SHORT trade setups for each ticker, so that I can evaluate opportunities in both directions regardless of market conditions.
#### Acceptance Criteria
1. WHEN the Trade_Recommendation_Engine analyzes a ticker, THE Trade_Recommendation_Engine SHALL generate both a LONG setup and a SHORT setup
2. THE Trade_Recommendation_Engine SHALL calculate separate entry prices, stop losses, and targets for each direction
3. WHEN generating a LONG setup, THE Trade_Recommendation_Engine SHALL use resistance levels as targets and support levels for stop-loss calculation
4. WHEN generating a SHORT setup, THE Trade_Recommendation_Engine SHALL use support levels as targets and resistance levels for stop-loss calculation
5. THE Trade_Recommendation_Engine SHALL store both setups in the TradeSetup model with distinct direction fields
### Requirement 2: Direction Confidence Scoring
**User Story:** As a non-professional trader, I want to see confidence scores for LONG vs SHORT directions, so that I can understand which direction has higher probability of success.
#### Acceptance Criteria
1. THE Direction_Analyzer SHALL calculate a confidence score (0-100%) for the LONG direction
2. THE Direction_Analyzer SHALL calculate a confidence score (0-100%) for the SHORT direction
3. WHEN sentiment is bullish AND technical score is above 60 AND momentum score is above 60, THE Direction_Analyzer SHALL assign LONG confidence above 70%
4. WHEN sentiment is bearish AND technical score is below 40 AND momentum score is below 40, THE Direction_Analyzer SHALL assign SHORT confidence above 70%
5. WHEN signal dimensions contradict each other, THE Direction_Analyzer SHALL reduce confidence scores for both directions below 60%
6. THE Direction_Analyzer SHALL store confidence scores in the TradeSetup model for each direction
### Requirement 3: Multiple Price Target Identification
**User Story:** As a trader, I want multiple price targets at different S/R levels, so that I can implement staged profit-taking and proper risk management.
#### Acceptance Criteria
1. WHEN generating targets for a LONG setup, THE Target_Generator SHALL identify 3 to 5 resistance levels above the entry price
2. WHEN generating targets for a SHORT setup, THE Target_Generator SHALL identify 3 to 5 support levels below the entry price
3. THE Target_Generator SHALL classify targets as Conservative (nearest), Moderate (mid-range), or Aggressive (furthest)
4. THE Target_Generator SHALL calculate the R:R ratio for each target level
5. WHEN fewer than 3 S/R levels exist in the target direction, THE Target_Generator SHALL use the available levels and flag the setup as having limited targets
6. THE Target_Generator SHALL order targets by distance from entry price
### Requirement 4: Target Probability Estimation
**User Story:** As a trader, I want to know the probability of reaching each price target, so that I can set realistic expectations and plan my exits.
#### Acceptance Criteria
1. THE Probability_Estimator SHALL calculate a target probability percentage (0-100%) for each price target
2. WHEN calculating probability, THE Probability_Estimator SHALL consider S/R level strength score (higher strength increases probability)
3. WHEN calculating probability, THE Probability_Estimator SHALL consider distance from entry (closer targets receive higher probability)
4. WHEN calculating probability, THE Probability_Estimator SHALL consider signal alignment (aligned signals increase probability by 10-20%)
5. WHEN calculating probability, THE Probability_Estimator SHALL consider ATR (higher volatility increases probability for distant targets)
6. THE Probability_Estimator SHALL assign Conservative targets probability above 60%
7. THE Probability_Estimator SHALL assign Moderate targets probability between 40% and 70%
8. THE Probability_Estimator SHALL assign Aggressive targets probability below 50%
### Requirement 5: Signal Conflict Detection
**User Story:** As a trader, I want to be warned when signals contradict each other, so that I can avoid high-risk trades with mixed indicators.
#### Acceptance Criteria
1. THE Signal_Conflict_Detector SHALL compare sentiment classification (bearish/neutral/bullish) with technical score direction
2. WHEN sentiment is bearish AND technical score is above 60, THE Signal_Conflict_Detector SHALL flag a sentiment-technical conflict
3. WHEN sentiment is bullish AND technical score is below 40, THE Signal_Conflict_Detector SHALL flag a sentiment-technical conflict
4. THE Signal_Conflict_Detector SHALL compare momentum score with technical score
5. WHEN momentum score and technical score differ by more than 30 points, THE Signal_Conflict_Detector SHALL flag a momentum-technical conflict
6. THE Signal_Conflict_Detector SHALL store conflict flags in the TradeSetup model
7. WHEN conflicts are detected, THE Signal_Conflict_Detector SHALL reduce confidence scores by 15-25%
### Requirement 6: Recommendation Summary Generation
**User Story:** As a non-professional trader, I want a clear recommendation summary with action, confidence, and reasoning, so that I can make informed trading decisions without analyzing raw data.
#### Acceptance Criteria
1. THE Recommendation_Summary SHALL include a recommended action field with values: "LONG (High Confidence)", "LONG (Moderate Confidence)", "SHORT (High Confidence)", "SHORT (Moderate Confidence)", or "NEUTRAL (Conflicting Signals)"
2. WHEN LONG confidence is above 70% AND LONG confidence exceeds SHORT confidence by 20%, THE Recommendation_Summary SHALL recommend "LONG (High Confidence)"
3. WHEN SHORT confidence is above 70% AND SHORT confidence exceeds LONG confidence by 20%, THE Recommendation_Summary SHALL recommend "SHORT (High Confidence)"
4. WHEN confidence scores differ by less than 20%, THE Recommendation_Summary SHALL recommend "NEUTRAL (Conflicting Signals)"
5. THE Recommendation_Summary SHALL include reasoning text explaining the recommendation based on signal alignment
6. THE Recommendation_Summary SHALL include a risk level assessment: Low (all signals aligned), Medium (minor conflicts), or High (major conflicts)
7. THE Recommendation_Summary SHALL display the composite score alongside the recommendation
### Requirement 7: Trade Setup API Enhancement
**User Story:** As a frontend developer, I want the trade setup API to return enhanced recommendation data, so that I can display confidence scores, multiple targets, and probabilities in the UI.
#### Acceptance Criteria
1. WHEN the trade setup API endpoint is called for a ticker, THE API SHALL return both LONG and SHORT setups
2. THE API SHALL include confidence_score field for each setup
3. THE API SHALL include a targets array with 3-5 target objects for each setup
4. WHEN returning target objects, THE API SHALL include price, distance_from_entry, rr_ratio, probability, and classification (Conservative/Moderate/Aggressive) fields
5. THE API SHALL include conflict_flags array listing detected signal conflicts
6. THE API SHALL include recommendation_summary object with action, reasoning, and risk_level fields
7. THE API SHALL return setups ordered by confidence score (highest first)
### Requirement 8: Historical S/R Strength Integration
**User Story:** As a system, I want to use historical S/R level strength in probability calculations, so that targets at stronger levels receive higher probability estimates.
#### Acceptance Criteria
1. THE Probability_Estimator SHALL retrieve the strength score from the SRLevel model for each target
2. WHEN an S/R level has strength score above 80, THE Probability_Estimator SHALL increase target probability by 10-15%
3. WHEN an S/R level has strength score below 40, THE Probability_Estimator SHALL decrease target probability by 10-15%
4. THE Probability_Estimator SHALL normalize strength scores to a 0-1 scale before applying to probability calculation
5. WHEN an S/R level has been tested multiple times historically, THE Probability_Estimator SHALL increase its weight in probability calculation
### Requirement 9: Volatility-Adjusted Target Selection
**User Story:** As a trader, I want target selection to account for volatility, so that targets are realistic given the ticker's typical price movement.
#### Acceptance Criteria
1. THE Target_Generator SHALL retrieve the current ATR value for the ticker
2. WHEN ATR is high (above 5% of current price), THE Target_Generator SHALL include more distant S/R levels as valid targets
3. WHEN ATR is low (below 2% of current price), THE Target_Generator SHALL limit targets to S/R levels within 3x ATR distance
4. THE Target_Generator SHALL calculate target distance as a multiple of ATR
5. THE Target_Generator SHALL exclude S/R levels that are less than 1x ATR from entry price
### Requirement 10: Recommendation Persistence and History
**User Story:** As a trader, I want to track how recommendations change over time, so that I can evaluate the system's accuracy and learn from past recommendations.
#### Acceptance Criteria
1. THE Trade_Recommendation_Engine SHALL store each generated recommendation with a timestamp
2. THE Trade_Recommendation_Engine SHALL preserve previous recommendations when generating new ones
3. THE API SHALL provide an endpoint to retrieve recommendation history for a ticker
4. WHEN retrieving history, THE API SHALL return recommendations ordered by timestamp (newest first)
5. THE API SHALL include actual_outcome field indicating whether targets were reached (to be updated post-trade)
### Requirement 11: Frontend Recommendation Display
**User Story:** As a trader, I want to see recommendations clearly displayed in the ticker detail page, so that I can quickly understand the suggested action and targets.
#### Acceptance Criteria
1. THE Ticker_Detail_Page SHALL display the recommendation summary prominently at the top
2. THE Ticker_Detail_Page SHALL show LONG and SHORT setups side-by-side with confidence scores
3. THE Ticker_Detail_Page SHALL display targets in a table with columns: Classification, Price, Distance, R:R, Probability
4. WHEN signal conflicts exist, THE Ticker_Detail_Page SHALL display a warning badge with conflict details
5. THE Ticker_Detail_Page SHALL highlight the recommended direction with visual emphasis (border, background color)
6. THE Ticker_Detail_Page SHALL display risk level with color coding: green (Low), yellow (Medium), red (High)
### Requirement 12: Scanner Integration with Recommendations
**User Story:** As a trader, I want the scanner to show recommended direction and confidence, so that I can quickly filter for high-confidence opportunities.
#### Acceptance Criteria
1. THE Scanner_Page SHALL display a "Recommended Action" column showing the recommended direction and confidence level
2. THE Scanner_Page SHALL allow filtering by recommended action (LONG High, LONG Moderate, SHORT High, SHORT Moderate, NEUTRAL)
3. THE Scanner_Page SHALL allow filtering by minimum confidence score
4. THE Scanner_Page SHALL display the highest-probability target for each setup in the table
5. WHEN a user clicks a setup row, THE Scanner_Page SHALL navigate to the ticker detail page with the recommendation expanded
### Requirement 13: Admin Configuration for Recommendation Thresholds
**User Story:** As an admin, I want to configure confidence score thresholds and probability calculation weights, so that I can tune the recommendation system based on market conditions.
#### Acceptance Criteria
1. THE Admin_Settings_Page SHALL provide inputs for high confidence threshold (default: 70%)
2. THE Admin_Settings_Page SHALL provide inputs for moderate confidence threshold (default: 50%)
3. THE Admin_Settings_Page SHALL provide inputs for signal alignment weight in probability calculation (default: 15%)
4. THE Admin_Settings_Page SHALL provide inputs for S/R strength weight in probability calculation (default: 20%)
5. THE Admin_Settings_Page SHALL provide inputs for distance penalty factor in probability calculation (default: 0.1)
6. WHEN admin saves settings, THE Settings_Service SHALL update the configuration in the Settings model
7. THE Trade_Recommendation_Engine SHALL retrieve current thresholds from Settings before generating recommendations
### Requirement 14: Recommendation Calculation Performance
**User Story:** As a system, I want recommendation generation to complete within acceptable time limits, so that users receive timely updates without delays.
#### Acceptance Criteria
1. WHEN generating recommendations for a single ticker, THE Trade_Recommendation_Engine SHALL complete within 500 milliseconds
2. WHEN the scheduled job generates recommendations for all tickers, THE Trade_Recommendation_Engine SHALL process at least 10 tickers per second
3. THE Trade_Recommendation_Engine SHALL use database query optimization to retrieve all required dimension scores in a single query
4. THE Trade_Recommendation_Engine SHALL cache S/R levels for each ticker to avoid repeated database queries
5. WHEN recommendation generation fails for a ticker, THE Trade_Recommendation_Engine SHALL log the error and continue processing remaining tickers
### Requirement 15: Recommendation Data Model Extension
**User Story:** As a developer, I want the TradeSetup model extended to store recommendation data, so that all recommendation information persists in the database.
#### Acceptance Criteria
1. THE TradeSetup model SHALL include a confidence_score field (Float, 0-100)
2. THE TradeSetup model SHALL include a targets field (JSON array of target objects)
3. THE TradeSetup model SHALL include a conflict_flags field (JSON array of strings)
4. THE TradeSetup model SHALL include a recommended_action field (String: LONG_HIGH, LONG_MODERATE, SHORT_HIGH, SHORT_MODERATE, NEUTRAL)
5. THE TradeSetup model SHALL include a reasoning field (Text)
6. THE TradeSetup model SHALL include a risk_level field (String: Low, Medium, High)
7. THE TradeSetup model SHALL maintain backward compatibility with existing entry_price, stop_loss, target, and rr_ratio fields for the primary target

30
.kiro/steering/product.md Normal file
View File

@@ -0,0 +1,30 @@
# Product Overview
Signal Dashboard is an investing-signal platform for NASDAQ stocks that surfaces optimal trading opportunities through multi-dimensional scoring.
## Core Philosophy
Don't predict price. Find the path of least resistance, key support/resistance zones, and asymmetric risk:reward setups.
## Key Features
- Multi-dimensional scoring engine (technical, S/R quality, sentiment, fundamental, momentum)
- Risk:Reward scanner with ATR-based stops (default 3:1 threshold)
- Support/Resistance detection with strength scoring and merge-within-tolerance
- Sentiment analysis with time-decay weighted scoring (Gemini 2.0 Flash with search grounding)
- Auto-populated watchlist (top-10 by composite score) + manual entries (cap: 20)
- Interactive candlestick chart with S/R overlays
- JWT auth with admin role and user access control
- Scheduled jobs: OHLCV collection, sentiment polling, fundamentals fetch, R:R scanning
## Data Providers
- Alpaca: OHLCV price data
- Gemini 2.0 Flash: Sentiment analysis via search grounding
- Financial Modeling Prep: Fundamental data (P/E, revenue growth, earnings surprise, market cap)
## User Roles
- Admin: Full access including user management, job control, data cleanup, system settings
- User: Access to watchlist, scanner, rankings, ticker details (when has_access=true)
- Registration: Configurable via admin settings

View File

@@ -0,0 +1,87 @@
# Project Structure
## Backend Architecture
```
app/
├── main.py # FastAPI app, lifespan, router registration
├── config.py # Pydantic settings from .env
├── database.py # Async SQLAlchemy engine + session factory
├── dependencies.py # DI: DB session, auth guards (require_access, require_admin)
├── exceptions.py # Custom exception hierarchy (ValidationError, NotFoundError, etc.)
├── middleware.py # Global error handler → JSON envelope
├── cache.py # LRU cache with per-ticker invalidation
├── scheduler.py # APScheduler job definitions
├── models/ # SQLAlchemy ORM models
├── schemas/ # Pydantic request/response schemas
├── services/ # Business logic layer
├── providers/ # External data provider integrations
└── routers/ # FastAPI route handlers
```
## Frontend Architecture
```
frontend/src/
├── App.tsx # Route definitions
├── main.tsx # React entry point
├── api/ # Axios API client modules (one per resource)
├── components/
│ ├── admin/ # User table, job controls, settings, data cleanup
│ ├── auth/ # Protected route wrapper
│ ├── charts/ # Canvas candlestick chart
│ ├── layout/ # App shell, sidebar, mobile nav
│ ├── rankings/ # Rankings table, weights form
│ ├── scanner/ # Trade table
│ ├── ticker/ # Sentiment panel, fundamentals, indicators, S/R overlay
│ ├── ui/ # Badge, toast, skeleton, score card, confirm dialog
│ └── watchlist/ # Watchlist table, add ticker form
├── hooks/ # React Query hooks (one per resource)
├── lib/ # Types, formatting utilities
├── pages/ # Page components (Login, Register, Watchlist, Ticker, Scanner, Rankings, Admin)
├── stores/ # Zustand auth store
└── styles/ # Global CSS with glassmorphism classes
```
## Key Patterns
### Backend
- **Layered architecture**: Router → Service → Model
- **Dependency injection**: FastAPI Depends() for DB session and auth
- **Exception handling**: Custom exceptions caught by global middleware, returned as JSON envelope
- **API envelope**: All responses wrapped in `{ status: "success"|"error", data: any, error?: string }`
- **Cascade deletes**: Ticker deletion cascades to all related data (OHLCV, sentiment, fundamentals, S/R, scores, trades, watchlist)
- **Async everywhere**: All DB operations use async/await with asyncpg
### Frontend
- **API client**: Axios interceptors for JWT injection and envelope unwrapping
- **Server state**: TanStack React Query with query keys per resource
- **Client state**: Zustand for auth (token, user, login/logout)
- **Error handling**: ApiError class, toast notifications for mutations
- **Protected routes**: ProtectedRoute wrapper checks auth, redirects to /login
- **Glassmorphism**: Frosted glass panels, gradient text, ambient glow, mesh gradient background
## Database Models
All models inherit from `Base` (SQLAlchemy declarative base):
- `Ticker`: Registry of tracked symbols (cascade delete parent)
- `OHLCVRecord`: Price data (open, high, low, close, volume)
- `SentimentScore`: Sentiment analysis results with time-decay
- `FundamentalData`: P/E, revenue growth, earnings surprise, market cap
- `SRLevel`: Support/Resistance levels with strength scoring
- `DimensionScore`: Individual dimension scores (technical, sr_quality, sentiment, fundamental, momentum)
- `CompositeScore`: Weighted composite score
- `TradeSetup`: Detected R:R setups (long/short, entry, stop, target)
- `WatchlistEntry`: User watchlist entries (auto/manual)
- `User`: Auth and access control
- `Settings`: System-wide configuration
## Testing
- Backend tests: `tests/unit/` and `tests/property/`
- Frontend tests: `frontend/src/**/*.test.tsx`
- Fixtures in `tests/conftest.py`
- Hypothesis strategies for property-based testing

86
.kiro/steering/tech.md Normal file
View File

@@ -0,0 +1,86 @@
# Tech Stack
## Backend
- Python 3.12+
- FastAPI with Uvicorn
- SQLAlchemy 2.0 (async) with asyncpg
- PostgreSQL database
- Alembic for migrations
- APScheduler for scheduled jobs
- JWT auth (python-jose, passlib with bcrypt)
- Pydantic for validation and settings
## Frontend
- React 18 with TypeScript
- Vite 5 (build tool)
- TanStack React Query v5 (server state)
- Zustand (client state, auth)
- React Router v6 (SPA routing)
- Axios with JWT interceptor
- Tailwind CSS 3 with custom glassmorphism design system
- Canvas 2D for candlestick charts
## Testing
- Backend: pytest, pytest-asyncio, Hypothesis (property-based testing)
- Frontend: Vitest
- Test database: In-memory SQLite (no PostgreSQL needed for tests)
## Common Commands
### Backend
```bash
# Setup
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
# Database
createdb stock_data_backend
alembic upgrade head
# Run
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
# Test
pytest tests/ -v
```
### Frontend
```bash
cd frontend
# Setup
npm install
# Run dev server (proxies /api/v1/ to backend)
npm run dev
# Build
npm run build
# Test
npm test # Single run
npm run test:watch # Watch mode
```
## Environment Variables
Required in `.env`:
- `DATABASE_URL`: PostgreSQL connection string (postgresql+asyncpg://...)
- `JWT_SECRET`: Random secret for JWT signing
- `ALPACA_API_KEY`, `ALPACA_API_SECRET`: For OHLCV data
- `GEMINI_API_KEY`: For sentiment analysis
- `FMP_API_KEY`: For fundamental data
See `.env.example` for full list with defaults.
## API Documentation
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- All endpoints under `/api/v1/`