# Stock Listing Application — Generated Backend

## Overview

This is a **FastAPI-based backend** for the Stock Listing Application, a web-based platform that provides users with a comprehensive view of available stocks and shares in the market with search, filtering, and watchlist capabilities.

The system supports **4 user roles** (anonymous, registered, data_manager, administrator) and manages **9 core entities** across 4 functional modules:

- **Stock Management** — Sectors, Exchanges, Stocks, and Stock History
- **User Management** — Users and User Activities
- **Watchlist Management** — Watchlists and Watchlist Items
- **System Configuration** — Application-wide settings

This generated backend includes:

- ✅ Full CRUD endpoints for all entities
- ✅ Advanced search, filtering, and pagination for stocks
- ✅ Detail endpoints with eager-loaded relationships
- ✅ Batch operations (bulk import, cascading deletes)
- ✅ User registration and authentication workflows
- ✅ Activity tracking and watchlist management
- ✅ Business rule validation and data integrity checks
- ✅ Auto-generated OpenAPI documentation

## Requirements

- **Python 3.11+**
- **uv** (fast Python package installer and resolver)
- **PostgreSQL** (recommended for production; SQLite for development)

## Install uv

Install `uv` using the official installer:

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

After installation, restart your terminal or run:

```bash
source $HOME/.cargo/env
```

Verify installation:

```bash
uv --version
```

## Install Dependencies

Clone or navigate to the project directory, then install dependencies:

```bash
uv sync
```

This will create a virtual environment and install all required packages including:

- `fastapi` — Web framework
- `uvicorn` — ASGI server
- `sqlalchemy` — ORM
- `pydantic` — Data validation
- `python-jose` — JWT handling
- `passlib` — Password hashing
- `python-multipart` — File upload support

## Run the Backend

Start the development server with auto-reload:

```bash
uv run uvicorn main:app --reload
```

The API will be available at:

- **Base URL:** `http://localhost:8000`
- **Interactive Docs:** `http://localhost:8000/docs`
- **ReDoc:** `http://localhost:8000/redoc`

## API Docs

Once the server is running, visit **`http://localhost:8000/docs`** for the interactive Swagger UI where you can:

- Browse all available endpoints
- Test API calls directly from the browser
- View request/response schemas
- Authenticate and test protected endpoints

### Key Endpoint Categories

| Category | Endpoints | Description |
|----------|-----------|-------------|
| **Stocks** | `/stocks`, `/stocks/{id}`, `/stocks/{id}/details`, `/stocks/{id}/history`, `/stocks/search`, `/stocks/bulk-import` | Stock listing, search, filtering, details with relationships, historical data, bulk import |
| **Sectors** | `/sectors`, `/sectors/{id}` | Industry sector management |
| **Exchanges** | `/exchanges`, `/exchanges/{id}` | Stock exchange management |
| **Users** | `/users`, `/users/register`, `/users/login`, `/users/logout`, `/users/{id}/activities` | User registration, authentication, profile, activity tracking |
| **Watchlists** | `/watchlists`, `/watchlists/{id}`, `/watchlists/{id}/details`, `/watchlists/{id}/add-stock`, `/watchlists/{id}/remove-stock/{stock_id}` | Watchlist CRUD, stock management within watchlists |
| **User Activities** | `/user-activities`, `/user-activities/log` | Activity tracking (view, search, favorite) |
| **System Config** | `/system-configurations`, `/system-configurations/{id}` | Application settings management |

## OpenAPI JSON

Download the OpenAPI specification:

```bash
curl http://localhost:8000/openapi.json -o openapi.json
```

This JSON file can be imported into tools like Postman, Insomnia, or used to generate client SDKs.

## Project Files

```
.
├── main.py                      # FastAPI application entry point
├── models.py                    # SQLAlchemy ORM models
├── schemas.py                   # Pydantic request/response schemas
├── database.py                  # Database connection and session management
├── auth.py                      # Authentication and authorization utilities
├── enums.py                     # Enum definitions (UserRole, StockStatus, etc.)
├── crud.py                      # CRUD operations and business logic
├── dependencies.py              # Dependency injection (get_db, get_current_user)
├── config.py                    # Configuration settings
├── pyproject.toml               # Project dependencies and metadata
├── .env.example                 # Environment variables template
└── README.md                    # This file
```

## Example Workflow

### 1. Register a New User

```bash
curl -X POST "http://localhost:8000/users/register" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "investor@example.com",
    "password": "SecurePass123",
    "first_name": "John",
    "last_name": "Investor"
  }'
```

**Response:**
```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "investor@example.com",
  "first_name": "John",
  "last_name": "Investor",
  "role": "REGISTERED",
  "status": "ACTIVE",
  "registration_date": "2024-01-15T10:30:00Z"
}
```

### 2. Login and Get Access Token

```bash
curl -X POST "http://localhost:8000/users/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "investor@example.com",
    "password": "SecurePass123"
  }'
```

**Response:**
```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "user": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "investor@example.com",
    "role": "REGISTERED"
  }
}
```

### 3. Search for Stocks

```bash
curl -X GET "http://localhost:8000/stocks/search?q=AAPL" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
```

**Response:**
```json
{
  "results": [
    {
      "id": "123e4567-e89b-12d3-a456-426614174000",
      "ticker_symbol": "AAPL",
      "company_name": "Apple Inc.",
      "current_price": 178.25,
      "sector": "Technology",
      "exchange": "NASDAQ"
    }
  ],
  "total": 1
}
```

### 4. Get Stock Details with Relationships

```bash
curl -X GET "http://localhost:8000/stocks/123e4567-e89b-12d3-a456-426614174000/details" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
```

**Response:**
```json
{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "ticker_symbol": "AAPL",
  "company_name": "Apple Inc.",
  "current_price": 178.25,
  "opening_price": 176.50,
  "closing_price": 178.00,
  "high_price": 179.30,
  "low_price": 176.20,
  "volume": 52341000,
  "market_cap": 2750000000000,
  "sector": {
    "id": "tech-001",
    "name": "Technology",
    "description": "Technology and software companies",
    "icon_url": "https://example.com/icons/tech.png"
  },
  "exchange": {
    "id": "nasdaq-001",
    "name": "NASDAQ",
    "code": "NASDAQ",
    "country": "US",
    "currency": "USD"
  },
  "status": "ACTIVE",
  "last_updated": "2024-01-15T16:00:00Z"
}
```

### 5. Create a Watchlist

```bash
curl -X POST "http://localhost:8000/watchlists" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Tech Stocks",
    "description": "My favorite technology companies",
    "is_default": false
  }'
```

### 6. Add Stock to Watchlist

```bash
curl -X POST "http://localhost:8000/watchlists/watchlist-id-here/add-stock" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "stock_id": "123e4567-e89b-12d3-a456-426614174000",
    "notes": "Strong buy candidate"
  }'
```

### 7. Get Watchlist with All Stocks

```bash
curl -X GET "http://localhost:8000/watchlists/watchlist-id-here/details" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
```

**Response:**
```json
{
  "id": "watchlist-id-here",
  "name": "Tech Stocks",
  "description": "My favorite technology companies",
  "is_default": false,
  "watchlist_items": [
    {
      "id": "item-001",
      "stock": {
        "ticker_symbol": "AAPL",
        "company_name": "Apple Inc.",
        "current_price": 178.25,
        "sector": {
          "name": "Technology"
        },
        "exchange": {
          "name": "NASDAQ"
        }
      },
      "notes": "Strong buy candidate",
      "added_date": "2024-01-15T11:00:00Z"
    }
  ]
}
```

## Next Steps

This generated backend provides a solid foundation. To prepare for production, consider:

### 1. **Database Persistence**
   - Configure PostgreSQL connection in `.env`
   - Run Alembic migrations for schema management
   - Set up database backups and replication

### 2. **Authentication & Authorization**
   - Implement JWT token refresh mechanism
   - Add role-based access control (RBAC) middleware
   - Implement rate limiting for login attempts
   - Add OAuth2 providers (Google, GitHub)

### 3. **Code Organization**
   - Split `main.py` into separate routers (`stocks.py`, `users.py`, `watchlists.py`)
   - Move business logic to service layer (`services/stock_service.py`)
   - Separate models into domain modules (`models/stock.py`, `models/user.py`)
   - Create repository pattern for data access

### 4. **Testing**
   - Add unit tests with `pytest`
   - Create integration tests for API endpoints
   - Add test fixtures and factories
   - Set up CI/CD pipeline with automated testing

### 5. **Production Readiness**
   - Add logging and monitoring (Sentry, DataDog)
   - Implement caching (Redis) for frequently accessed data
   - Add background tasks (Celery) for bulk imports and price updates
   - Configure CORS for frontend integration
   - Set up Docker containerization
   - Add health check endpoints
   - Implement API versioning

### 6. **Business Logic Enhancements**
   - Implement all validation rules from business requirements
   - Add scheduled jobs for stock price updates
   - Implement email notifications for watchlist alerts
   - Add real-time WebSocket support for live price updates
   - Create analytics dashboard endpoints

### 7. **Documentation**
   - Add detailed docstrings to all functions
   - Create API usage guide with more examples
   - Document deployment procedures
   - Add architecture diagrams

---

**Generated by FastAPI Backend Generator** | For questions or issues, refer to the FastAPI documentation at https://fastapi.tiangolo.com
