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)
- Install WSL 2 following Microsoft's official guide
- Open your WSL terminal (Ubuntu, Debian, etc.)
- Install Python and pip if not already present:
sudo apt update sudo apt install python3 python3-pip - Install the package:
pip install defeatbeta-api
Option 2: Using Docker
- Install Docker Desktop
- Run a Python container with the package installed:
docker run -it python:latest pip install defeatbeta-api - 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:
-
OpenAI API Key:
- Sign up at platform.openai.com
- Create an API key in your dashboard
- Set the
OPENAI_API_KEYenvironment variable
-
Hugging Face Token (optional but recommended):
- Create account at huggingface.co
- Generate a token in your account settings
- Set the
HF_TOKENenvironment 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:
-
Clone the repository:
git clone https://github.com/defeat-beta/defeatbeta-api.git cd defeatbeta-api -
Install in development mode:
pip install -e . -
Install development dependencies:
pip install -r requirements-dev.txt # If available
Running in JupyterLab
For interactive analysis, use the provided JupyterLab environment:
-
Install JupyterLab:
pip install jupyterlab -
Launch JupyterLab:
jupyter lab -
Open the tutorial notebook:
notebooks/06_tutorial_dcf.ipynb
Or use the Binder link directly:
MCP Server Setup
To use the Model Context Protocol server:
- Ensure you have the MCP client installed (Claude Desktop, Cursor, etc.)
- Configure your MCP client to use the Defeat Beta API server
- 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_httpfsextension 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_TTLvalues
- Using authenticated access with
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:
- Verify installation:
pip list | grep defeatbeta-api - Reinstall the package:
pip uninstall defeatbeta-api pip install defeatbeta-api - Check Python path:
python -c "import sys; print(sys.path)"
Issue 3: Hugging Face Rate Limiting
Error: HTTPError: 429 Too Many Requests
Solutions:
- Add authentication:
export HF_TOKEN=your_token_here - Increase caching TTL:
export DEFEATBETA_CACHE_TTL=2592000 # 30 days - Implement retry logic in your code
Issue 4: LLM Features Not Working
Error: OpenAI API errors or missing LLM analysis Solutions:
- Verify API key is set:
echo $OPENAI_API_KEY - Check OpenAI configuration:
from defeatbeta_api.client.openai_conf import OpenAIConfiguration print(OpenAIConfiguration.api_key) - Ensure you have sufficient credits in your OpenAI account
Issue 5: Performance Issues
Symptoms: Slow data retrieval Solutions:
- Check cache directory:
echo $DEFEATBETA_CACHE_DIR ls -la ~/.defeatbeta_cache/ - Clear cache if corrupted:
rm -rf ~/.defeatbeta_cache/ - 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:
- Check if the ticker symbol is correct
- Verify the data exists in the Hugging Face dataset:
from defeatbeta_api import HuggingFaceClient client = HuggingFaceClient() # Check available data - Some metrics may not be available for all companies or time periods
Issue 7: DCF Analysis Errors
Error: Excel file generation fails Solutions:
- Ensure
xlwingsis properly installed:pip install xlwings - On macOS/Linux, ensure Excel is installed if using desktop automation
- Consider using the CSV output option if available
Getting Help
- Documentation: See the example guide for detailed usage
- GitHub Issues: Check existing issues or create new ones at github.com/defeat-beta/defeatbeta-api
- Changelog: Review the CHANGELOG.rst for recent updates and fixes
Debug Mode
Enable verbose logging for troubleshooting:
import logging
logging.basicConfig(level=logging.DEBUG)
# Or set environment variable
# export DEFEATBETA_LOG_LEVEL=DEBUG