# 🤖 AI Market Simulation

An **agentic AI-driven financial market simulation** where autonomous AI traders react to AI-generated news in a fictional stock universe.

![Python](https://img.shields.io/badge/Python-3.11+-blue)
![React](https://img.shields.io/badge/React-18+-61DAFB)
![Gemini](https://img.shields.io/badge/AI-Gemini%201.5-orange)
![License](https://img.shields.io/badge/License-MIT-green)

## 🌟 Overview

This project simulates a complete financial market ecosystem powered by AI:

- **🎭 Narrative AI**: Generates realistic financial news that drives market sentiment
- **🤖 Trading Agents**: Autonomous AI traders with distinct personalities (Momentum, Value, Hedge)
- **📊 Real-time Visualization**: Live price charts, news feed, and agent activity
- **🎓 Educational**: Built-in "Professor Mode" explains financial concepts

### The "Schrödinger's Market" Architecture

The simulation only runs when observers are connected, keeping AI costs near **$0** during development:
- **Client connects** → Simulation wakes up
- **All clients disconnect** → Simulation pauses (no API calls)

## 🚀 Quick Start

### Prerequisites

- Python 3.11+
- Node.js 18+
- Gemini API Key ([Get one free](https://aistudio.google.com/))

### 1. Clone & Setup

```bash
git clone https://github.com/yourusername/AI-Market-Simulation.git
cd AI-Market-Simulation

# Create Python virtual environment
python3 -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# Install backend dependencies
pip install -r requirements.txt

# Setup environment
cp .env.example .env
# Edit .env and add your GEMINI_API_KEY
```

### 2. Start the Backend

```bash
# From project root, with venv activated
uvicorn backend.server:app --reload --port 8000
```

### 3. Start the Frontend

```bash
# In a new terminal
cd frontend
npm install
npm run dev
```

### 4. Open the App

Navigate to `http://localhost:5173` and watch the AI market come alive!

## 🏗️ Architecture

```
AI-Market-Simulation/
├── backend/
│   ├── world_state.py    # Market state & history
│   ├── ai_agents.py      # AI trading agents (Gemini)
│   └── server.py         # FastAPI + WebSocket server
├── frontend/
│   ├── src/
│   │   ├── App.jsx       # Main React application
│   │   └── index.css     # Tailwind styles
│   └── package.json
├── requirements.txt
└── README.md
```

## 🤖 The AI Agents

### 🎭 Market Narrator
- **Role**: Generates news and events
- **Doesn't trade**, creates "weather" for other agents
- Produces headlines like: *"Omegacorp announces breakthrough in Quantum AI"*

### 🚀 FOMO_Bot_9000 (Momentum)
- **Strategy**: Follows trends aggressively
- **Personality**: Enthusiastic, uses rocket emojis
- *"Price is pumping! Can't miss this move! 🚀"*

### 📊 Warren_Bot (Value)
- **Strategy**: Contrarian, sells high IV
- **Personality**: Patient, analytical
- *"Fear creates opportunity for the patient investor."*

### 🛡️ RiskManager_Alpha (Hedge)
- **Strategy**: Buys puts for protection
- **Personality**: Cautious, risk-focused
- *"Tail risk elevated. Adding downside protection."*

## 💰 Cost Estimation

Using **Gemini 1.5 Flash** (free tier):
- **Rate limit**: 15 requests/minute
- **Daily limit**: 1,500 requests
- **Estimated cost**: **$0** for portfolio demos

| Scenario | API Calls | Cost |
|----------|-----------|------|
| 10 min demo | ~200 | $0 |
| 1 hour active | ~1,200 | $0 |
| 24/7 (if needed) | ~$2/day | Paid tier |

## 🎓 Educational Features

Click any metric to open **Professor Mode**:

- **Delta**: Rate of change vs underlying
- **Gamma**: Acceleration of delta
- **Theta**: Time decay
- **Vega**: Sensitivity to volatility
- **Black-Scholes**: The foundational pricing model

## 🛠️ Development

### Backend Only (No AI)

The simulation runs with rule-based fallbacks when no API key is set:

```bash
# Start without AI
unset GEMINI_API_KEY
uvicorn backend.server:app --reload
```

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `GEMINI_API_KEY` | Your Gemini API key | Required |
| `TICK_INTERVAL` | Seconds between ticks | 3.0 |
| `NEWS_INTERVAL` | Ticks between news | 5 |
| `TRADE_INTERVAL` | Ticks between trades | 2 |

## 📡 API Endpoints

### REST

- `GET /` - Health check
- `GET /api/state` - Current market state
- `GET /api/agents` - Agent information
- `POST /api/reset` - Reset simulation

### WebSocket

Connect to `ws://localhost:8000/ws` for real-time updates:

```javascript
// Message types received
{ type: "init", data: {...} }   // Initial state
{ type: "state", data: {...} }  // State updates
{ type: "news", data: {...} }   // New AI-generated news
{ type: "trade", data: {...} }  // Agent trade executed
```

## 🚀 Deployment

### Backend (Railway/Render)

```bash
# Procfile
web: uvicorn backend.server:app --host 0.0.0.0 --port $PORT
```

### Frontend (Vercel)

```bash
cd frontend
npm run build
# Deploy dist/ folder
```

## 📚 Inspiration & References

- [Options Modelling](https://github.com/jamesmawm/Options-Modelling)
- [Options Calculator](https://github.com/YuChenAmberLu/Options-Calculator)
- [Option Matrix](https://github.com/AnthonyBradford/optionmatrix)

## 📄 License

MIT License - Feel free to use for your portfolio!

---

**Built by [Jeeve Singh](https://linkedin.com/in/jeeve-singh/)** | Financial AI Demo 2025
