← Back to defeatbeta-api

How to Deploy & Use defeatbeta-api

Defeat Beta API: Deployment & Usage Guide

1. Prerequisites

Before installing Defeat Beta API, ensure you have the following:

System Requirements

  • Operating System: macOS, Linux, or Windows with WSL/Docker
  • Python: Version 3.9 or higher
  • Package Manager: pip (Python package installer)

Windows-Specific Requirements

Since the cache_httpfs DuckDB extension is not supported natively on Windows, you must choose one of these options:

  • Option 1 (Recommended): Windows Subsystem for Linux (WSL 2)
  • Option 2: Docker Desktop with Linux containers

Optional (for Advanced Features)

  • Hugging Face Account: For accessing the yahoo-finance-data dataset (automatic, but having an account may provide higher rate limits)
  • OpenAI API Key: If using LLM-powered analysis features (earnings call transcript analysis, quarterly forecasts, etc.)
  • JupyterLab: For interactive notebook environments

2. Installation

Standard Installation (macOS / Linux)

pip install defeatbeta-api

Windows Installation

Option 1: Using WSL (Recommended)

  1. Install WSL 2 following Microsoft's official guide
  2. Open your WSL terminal (Ubuntu, Debian, etc.)
  3. Install Python and pip if not already present:
    sudo apt update
    sudo apt install python3 python3-pip
    
  4. Install the package:
    pip install defeatbeta-api
    

Option 2: Using Docker

  1. Install Docker Desktop
  2. Run a Python container with the package installed:
    docker run -it python:latest pip install defeatbeta-api
    
  3. For persistent usage, create a Dockerfile:
    FROM python:3.11-slim
    RUN pip install defeatbeta-api
    WORKDIR /app
    

Verification

Test your installation:

python -c "import defeatbeta_api; print('Defeat Beta API installed successfully')"

3. Configuration

Environment Variables

Create a .env file in your project root or set these environment variables:

# OpenAI API Configuration (required for LLM features)
OPENAI_API_KEY=sk-your-openai-api-key-here
OPENAI_BASE_URL=https://api.openai.com/v1  # Optional: for custom endpoints

# Hugging Face Configuration (optional, for authenticated access)
HF_TOKEN=your-huggingface-token-here

# Cache Configuration (optional)
DEFEATBETA_CACHE_DIR=~/.defeatbeta_cache  # Default cache location
DEFEATBETA_CACHE_TTL=86400  # Cache time-to-live in seconds (default: 24 hours)

API Key Setup for LLM Features

If you plan to use LLM-powered analysis:

  1. OpenAI API Key:

    • Sign up at platform.openai.com
    • Create an API key in your dashboard
    • Set the OPENAI_API_KEY environment variable
  2. Hugging Face Token (optional but recommended):

    • Create account at huggingface.co
    • Generate a token in your account settings
    • Set the HF_TOKEN environment variable for higher rate limits

Python Configuration

For programmatic configuration, create a configuration file:

# config.py
from defeatbeta_api.client.openai_conf import OpenAIConfiguration

# Configure OpenAI client
OpenAIConfiguration.api_key = "your-api-key"
OpenAIConfiguration.base_url = "https://api.openai.com/v1"  # Optional
OpenAIConfiguration.model = "gpt-4"  # Default is "gpt-4o-mini"

4. Build & Run

Basic Usage

import defeatbeta_api
from defeatbeta_api.data.ticker import Ticker

# Initialize with a ticker symbol
ticker = Ticker('TSLA')

# Fetch price data
price_data = ticker.price()
print(f"Fetched {len(price_data)} rows of price data")

# Get financial metrics
metrics = ticker.quarterly_gross_margin()
print(metrics.head())

Development Setup (from Source)

If you want to contribute or modify the source code:

  1. Clone the repository:

    git clone https://github.com/defeat-beta/defeatbeta-api.git
    cd defeatbeta-api
    
  2. Install in development mode:

    pip install -e .
    
  3. Install development dependencies:

    pip install -r requirements-dev.txt  # If available
    

Running in JupyterLab

For interactive analysis, use the provided JupyterLab environment:

  1. Install JupyterLab:

    pip install jupyterlab
    
  2. Launch JupyterLab:

    jupyter lab
    
  3. Open the tutorial notebook: notebooks/06_tutorial_dcf.ipynb

Or use the Binder link directly: JupyterLab

MCP Server Setup

To use the Model Context Protocol server:

  1. Ensure you have the MCP client installed (Claude Desktop, Cursor, etc.)
  2. Configure your MCP client to use the Defeat Beta API server
  3. See the MCP documentation for detailed setup instructions

5. Deployment

Deployment Platforms

Based on the Python/DuckDB tech stack, consider these deployment options:

Option 1: Cloud Functions (Serverless)

  • AWS Lambda: Package with dependencies using Docker or Lambda layers
  • Google Cloud Functions: Native Python 3.9+ support
  • Azure Functions: Python runtime available

Example AWS Lambda deployment:

# Create deployment package
pip install defeatbeta-api -t ./package
cd package
zip -r ../defeatbeta-api-lambda.zip .

Option 2: Containerized Deployment (Recommended)

Create a Dockerfile for production:

FROM python:3.11-slim

WORKDIR /app

# Install system dependencies for DuckDB
RUN apt-get update && apt-get install -y \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Install Python package
RUN pip install defeatbeta-api

# Copy application code
COPY . .

# Set environment variables
ENV PYTHONUNBUFFERED=1

# Run your application
CMD ["python", "your_script.py"]

Build and run:

docker build -t defeatbeta-api .
docker run -e OPENAI_API_KEY=your_key defeatbeta-api

Option 3: Traditional Server

  • Requirements: Python 3.9+, 2GB+ RAM (for DuckDB caching)
  • Recommended: Ubuntu 20.04+ or Debian 11+
  • Setup:
    # Install system dependencies
    sudo apt update
    sudo apt install python3-pip python3-venv
    
    # Create virtual environment
    python3 -m venv venv
    source venv/bin/activate
    
    # Install package
    pip install defeatbeta-api
    
    # Run your application
    python your_app.py
    

Scaling Considerations

  • Cache Management: The DuckDB cache_httpfs extension caches data locally. Ensure sufficient disk space (1GB+ recommended)
  • Rate Limiting: Hugging Face datasets have rate limits. Consider:
    • Using authenticated access with HF_TOKEN
    • Implementing request throttling in high-volume applications
    • Setting appropriate DEFEATBETA_CACHE_TTL values

Monitoring

  • Logging: The package uses Python's standard logging module
  • Metrics: Monitor cache hit rates and API response times
  • Health Checks: Implement endpoint health checks for production deployments

6. Troubleshooting

Common Issues and Solutions

Issue 1: Windows Installation Fails

Error: cache_httpfs extension not supported Solution: Use WSL or Docker as described in the Installation section

Issue 2: Import Errors

Error: ModuleNotFoundError: No module named 'defeatbeta_api' Solutions:

  1. Verify installation:
    pip list | grep defeatbeta-api
    
  2. Reinstall the package:
    pip uninstall defeatbeta-api
    pip install defeatbeta-api
    
  3. Check Python path:
    python -c "import sys; print(sys.path)"
    

Issue 3: Hugging Face Rate Limiting

Error: HTTPError: 429 Too Many Requests Solutions:

  1. Add authentication:
    export HF_TOKEN=your_token_here
    
  2. Increase caching TTL:
    export DEFEATBETA_CACHE_TTL=2592000  # 30 days
    
  3. Implement retry logic in your code

Issue 4: LLM Features Not Working

Error: OpenAI API errors or missing LLM analysis Solutions:

  1. Verify API key is set:
    echo $OPENAI_API_KEY
    
  2. Check OpenAI configuration:
    from defeatbeta_api.client.openai_conf import OpenAIConfiguration
    print(OpenAIConfiguration.api_key)
    
  3. Ensure you have sufficient credits in your OpenAI account

Issue 5: Performance Issues

Symptoms: Slow data retrieval Solutions:

  1. Check cache directory:
    echo $DEFEATBETA_CACHE_DIR
    ls -la ~/.defeatbeta_cache/
    
  2. Clear cache if corrupted:
    rm -rf ~/.defeatbeta_cache/
    
  3. Increase cache size (DuckDB configuration):
    import duckdb
    conn = duckdb.connect()
    conn.execute("PRAGMA cache_size='2GB'")
    

Issue 6: Missing Financial Data

Error: Specific metrics (e.g., PS Ratio, ROIC) not available Solutions:

  1. Check if the ticker symbol is correct
  2. Verify the data exists in the Hugging Face dataset:
    from defeatbeta_api import HuggingFaceClient
    client = HuggingFaceClient()
    # Check available data
    
  3. Some metrics may not be available for all companies or time periods

Issue 7: DCF Analysis Errors

Error: Excel file generation fails Solutions:

  1. Ensure xlwings is properly installed:
    pip install xlwings
    
  2. On macOS/Linux, ensure Excel is installed if using desktop automation
  3. Consider using the CSV output option if available

Getting Help

Debug Mode

Enable verbose logging for troubleshooting:

import logging
logging.basicConfig(level=logging.DEBUG)

# Or set environment variable
# export DEFEATBETA_LOG_LEVEL=DEBUG