# AI Analysis Feature Setup

## Overview

The AI Analysis feature uses Claude (Anthropic) API to provide intelligent trading insights for options flow data. It analyzes the flow characteristics, fetches latest stock data from Yahoo Finance, and provides concise recommendations.

## Setup

### 1. Get Anthropic API Key

1. Go to https://console.anthropic.com/
2. Sign up or log in
3. Navigate to API Keys section
4. Create a new API key
5. Copy the API key

### 2. Add API Key to Environment

Add the following to your `backend/.env` file:

```env
ANTHROPIC_API_KEY=your_api_key_here
```

### 3. Restart Backend Server

After adding the API key, restart your backend server:

```bash
cd backend
npm run dev
```

## Usage

### In the Frontend

1. Open any options flow row in the dashboard
2. Expand the row to see details
3. Scroll to the bottom to find the "🤖 AI ANALYSIS" section
4. Click "Get AI Analysis" button
5. Wait for Claude AI to analyze the flow (usually 2-5 seconds)
6. Review the analysis including:
   - Assessment (BULLISH/BEARISH/NEUTRAL)
   - Recommendation (ENTER/WAIT/AVOID)
   - Key Factors
   - Risk Level
   - Time Horizon

### API Endpoints

#### GET /api/options/ai-analysis?symbol=SMCI

Analyzes the latest flow for a given symbol.

#### POST /api/options/ai-analysis

Analyzes a specific flow data object.

**Request Body:**
```json
{
  "flowData": {
    "symbol_norm": "SMCI",
    "rocketScore": 2.0,
    "bull_total": 100000,
    "bear_total": 120000,
    ...
  }
}
```

**Response:**
```json
{
  "success": true,
  "analysis": {
    "assessment": "BEARISH",
    "summary": "Institutional put flow suggests bearish sentiment...",
    "keyFactors": ["High put premium", "Tape not aligned", "Low score"],
    "recommendation": "WAIT",
    "reasoning": "Flow suggests bearish but price action not confirming...",
    "riskLevel": "MEDIUM",
    "timeHorizon": "INTRADAY"
  },
  "yahooData": {
    "currentPrice": 33.80,
    "previousClose": 33.50,
    "changePercent": 0.90
  },
  "timestamp": "2025-12-11T10:30:00Z"
}
```

## Features

- **Automatic Yahoo Finance Integration**: Fetches latest stock price data automatically
- **Context-Aware Analysis**: Considers flow characteristics, tape alignment, catalysts, and price action
- **Concise Recommendations**: Provides clear ENTER/WAIT/AVOID signals
- **Risk Assessment**: Evaluates risk level (LOW/MEDIUM/HIGH)
- **Time Horizon**: Suggests appropriate time frame (INTRADAY/SWING/POSITION)

## Cost Considerations

- Claude API pricing: ~$0.003 per request (for claude-3-5-sonnet)
- Each analysis uses ~500 tokens
- Typical cost: < $0.01 per analysis

## Troubleshooting

### "ANTHROPIC_API_KEY environment variable is not set"

- Make sure you've added the API key to `backend/.env`
- Restart the backend server after adding the key

### "Failed to fetch Yahoo Finance data"

- This is a warning, not an error
- AI analysis will still work without Yahoo Finance data
- The analysis will be based solely on options flow data

### Analysis takes too long

- Normal response time: 2-5 seconds
- If it takes longer, check your internet connection
- The API has rate limits, so avoid rapid successive requests

## Future Enhancements

- Cache analysis results to reduce API calls
- Batch analysis for multiple symbols
- Historical analysis comparison
- Custom prompt templates
- Integration with more data sources

