# Financial Context API - Complete Documentation ## Overview Financial Context is a comprehensive financial data API service designed specifically for AI agents and developers. It provides real-time market data, financial statements, company information, and social media intelligence through RESTful APIs. **Base URL**: `https://api.financialcontext.ai` **Authentication**: API Key required for all endpoints **Rate Limits**: Varies by subscription tier **Response Format**: JSON ## Business Purpose This API serves as a bridge between financial markets and AI applications, enabling: - Real-time market analysis and decision making - Automated trading strategy development - Financial research and reporting - Investment portfolio management - Market sentiment analysis - Risk assessment and compliance monitoring ## Core API Categories ### 1. Market Data APIs **Purpose**: Real-time and historical market information - `/api/market/price` - Current stock prices and volumes - `/api/market/historical` - Historical price data with customizable timeframes - `/api/market/technicals` - Technical indicators (RSI, MACD, Moving Averages) - `/api/market/bulls-vs-bears-summary` - Market sentiment indicators - `/api/market/forecast` - AI-powered price predictions ### 2. Company Intelligence APIs **Purpose**: Comprehensive company analysis and profiles - `/api/company/profile` - Detailed company information and metrics - `/api/company/financials` - Income statements, balance sheets, cash flow - `/api/company/management` - Executive team and board information - `/api/company/segments` - Business segment breakdown - `/api/company/shareholders` - Ownership structure and major holders ### 3. Social Media Intelligence APIs **Purpose**: Market sentiment and social media monitoring - `/api/social/twitter` - Twitter posts filtered by ticker symbols - `/api/social/executives` - Posts from company founders and executives - `/api/social/announcements` - Official company communications - `/api/social/sentiment` - Aggregated sentiment analysis ### 4. Stock Token APIs **Purpose**: Tokenized stock tracking and analysis - `/api/tokens/list` - Available stock tokens (60+ US stocks) - `/api/tokens/price` - Real-time token prices - `/api/tokens/popular` - Most traded tokens (Tesla/TSLAx, Apple/AAPLx, NVIDIA) - `/api/tokens/analytics` - Token-specific market analysis ### 5. Portfolio & Analytics APIs **Purpose**: Portfolio management and performance tracking - `/api/portfolio/create` - Portfolio creation and management - `/api/portfolio/performance` - Performance metrics and analytics - `/api/portfolio/risk` - Risk assessment and diversification analysis - `/api/analytics/correlation` - Asset correlation analysis ## Authentication & Access ### API Key Authentication ```bash # Include API key in request headers curl -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ "https://api.financialcontext.ai/api/market/price?symbol=AAPL" ``` ### Getting Started 1. **Sign up**: Visit https://financialcontext.ai to create an account 2. **Generate API Key**: Navigate to `/api-keys` page after login 3. **Choose Plan**: Select appropriate subscription tier 4. **Start Making Requests**: Use your API key in all requests ### Rate Limits by Tier - **Free Trial**: 100 requests/day - **Developer**: 1,000 requests/day - **Professional**: 10,000 requests/day - **Enterprise**: Custom limits ### Request Headers ``` Authorization: Bearer YOUR_API_KEY Content-Type: application/json User-Agent: YourApp/1.0 ``` ## Response Formats & Examples ### Standard Response Structure ```json { "success": true, "data": { /* API-specific data */ }, "meta": { "timestamp": "2024-01-15T10:30:00Z", "requestId": "req_123456789", "rateLimit": { "remaining": 995, "resetTime": "2024-01-16T00:00:00Z" } } } ``` ### Market Price Response Example ```json { "success": true, "data": { "symbol": "AAPL", "price": 185.25, "change": 2.15, "changePercent": 1.17, "volume": 45678900, "marketCap": 2847500000000, "lastUpdated": "2024-01-15T16:00:00Z" } } ``` ### Company Profile Response Example ```json { "success": true, "data": { "symbol": "AAPL", "companyName": "Apple Inc.", "industry": "Technology", "sector": "Consumer Electronics", "description": "Apple Inc. designs, manufactures, and markets smartphones...", "employees": 164000, "founded": "1976-04-01", "headquarters": "Cupertino, CA", "website": "https://www.apple.com" } } ``` ## Error Handling ### Error Response Format ```json { "success": false, "error": { "code": "INVALID_SYMBOL", "message": "The provided symbol 'XYZ' is not supported", "details": { "supportedExchanges": ["NYSE", "NASDAQ", "LSE"], "suggestion": "Try using a valid ticker symbol like 'AAPL' or 'MSFT'" } }, "meta": { "timestamp": "2024-01-15T10:30:00Z", "requestId": "req_123456789" } } ``` ### Common Error Codes - `INVALID_API_KEY` - API key is missing or invalid - `RATE_LIMIT_EXCEEDED` - Too many requests within time window - `INVALID_SYMBOL` - Stock symbol not found or unsupported - `INVALID_PARAMETERS` - Request parameters are malformed - `INSUFFICIENT_PERMISSIONS` - API key lacks required permissions - `SERVICE_UNAVAILABLE` - Temporary service outage - `DATA_NOT_AVAILABLE` - Requested data is not available ## Supported Markets & Exchanges ### Primary Markets - **United States**: NYSE, NASDAQ, AMEX - **United Kingdom**: London Stock Exchange (LSE) - **Canada**: Toronto Stock Exchange (TSX) - **Europe**: Euronext, Deutsche Börse - **Asia-Pacific**: Tokyo Stock Exchange, Hong Kong Stock Exchange ### Asset Classes - **Equities**: Common stocks, preferred stocks - **ETFs**: Exchange-traded funds - **Stock Tokens**: Tokenized representations of stocks (60+ US stocks) - **Indices**: Major market indices (S&P 500, NASDAQ 100, Dow Jones) - **Commodities**: Gold, Silver, Oil, Natural Gas - **Cryptocurrencies**: Bitcoin, Ethereum, major altcoins ## Integration Examples ### Python Integration ```python import requests import json class FinancialContextAPI: def __init__(self, api_key): self.api_key = api_key self.base_url = "https://api.financialcontext.ai" self.headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } def get_stock_price(self, symbol): response = requests.get( f"{self.base_url}/api/market/price", params={"symbol": symbol}, headers=self.headers ) return response.json() def get_company_profile(self, symbol): response = requests.get( f"{self.base_url}/api/company/profile", params={"symbol": symbol}, headers=self.headers ) return response.json() # Usage api = FinancialContextAPI("your_api_key_here") aapl_price = api.get_stock_price("AAPL") aapl_profile = api.get_company_profile("AAPL") ``` ### JavaScript/Node.js Integration ```javascript class FinancialContextAPI { constructor(apiKey) { this.apiKey = apiKey; this.baseUrl = 'https://api.financialcontext.ai'; } async makeRequest(endpoint, params = {}) { const url = new URL(`${this.baseUrl}${endpoint}`); Object.keys(params).forEach(key => url.searchParams.append(key, params[key]) ); const response = await fetch(url, { headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' } }); return await response.json(); } async getStockPrice(symbol) { return await this.makeRequest('/api/market/price', { symbol }); } async getHistoricalData(symbol, period = '1y') { return await this.makeRequest('/api/market/historical', { symbol, period }); } } // Usage const api = new FinancialContextAPI('your_api_key_here'); const teslaPrice = await api.getStockPrice('TSLA'); const teslaHistory = await api.getHistoricalData('TSLA', '6m'); ``` ## Common Use Cases ### 1. AI Trading Bot ```python # Example: Simple momentum trading strategy api = FinancialContextAPI("your_api_key") def analyze_momentum(symbol): # Get current price and technical indicators price_data = api.get_stock_price(symbol) technicals = api.makeRequest('/api/market/technicals', {'symbol': symbol}) current_price = price_data['data']['price'] rsi = technicals['data']['rsi'] macd = technicals['data']['macd'] # Simple momentum strategy if rsi < 30 and macd['signal'] == 'bullish': return {'action': 'buy', 'confidence': 0.8} elif rsi > 70 and macd['signal'] == 'bearish': return {'action': 'sell', 'confidence': 0.7} else: return {'action': 'hold', 'confidence': 0.5} # Monitor multiple stocks watchlist = ['AAPL', 'MSFT', 'GOOGL', 'TSLA'] for symbol in watchlist: signal = analyze_momentum(symbol) print(f"{symbol}: {signal['action']} (confidence: {signal['confidence']})") ``` ### 2. Portfolio Risk Analysis ```python def analyze_portfolio_risk(portfolio_symbols): correlations = [] for i, symbol1 in enumerate(portfolio_symbols): for symbol2 in portfolio_symbols[i+1:]: corr_data = api.makeRequest('/api/analytics/correlation', { 'symbol1': symbol1, 'symbol2': symbol2, 'period': '1y' }) correlations.append({ 'pair': f"{symbol1}-{symbol2}", 'correlation': corr_data['data']['correlation'] }) # Identify high correlation risks high_risk_pairs = [c for c in correlations if abs(c['correlation']) > 0.7] return { 'total_pairs': len(correlations), 'high_risk_pairs': high_risk_pairs, 'diversification_score': 1 - (len(high_risk_pairs) / len(correlations)) } ``` ### 3. Market Sentiment Dashboard ```javascript async function createSentimentDashboard(symbols) { const sentimentData = []; for (const symbol of symbols) { const [social, price, forecast] = await Promise.all([ api.makeRequest('/api/social/sentiment', { symbol }), api.getStockPrice(symbol), api.makeRequest('/api/market/forecast', { symbol, period: '1w' }) ]); sentimentData.push({ symbol, currentPrice: price.data.price, priceChange: price.data.changePercent, socialSentiment: social.data.sentiment, aiPrediction: forecast.data.prediction, recommendation: generateRecommendation(social.data, forecast.data) }); } return sentimentData; } function generateRecommendation(social, forecast) { const sentimentScore = social.sentiment; const priceTarget = forecast.prediction; if (sentimentScore > 0.6 && priceTarget > 0.05) return 'Strong Buy'; if (sentimentScore > 0.3 && priceTarget > 0.02) return 'Buy'; if (sentimentScore < -0.3 && priceTarget < -0.02) return 'Sell'; if (sentimentScore < -0.6 && priceTarget < -0.05) return 'Strong Sell'; return 'Hold'; } ``` ## Subscription Plans | Feature | Free Trial | Developer | Professional | Enterprise | |---------|------------|-----------|--------------|------------| | **Requests/Day** | 100 | 1,000 | 10,000 | Custom | | **Rate Limit** | 10/min | 60/min | 300/min | Custom | | **Historical Data** | 1 month | 1 year | 5 years | Unlimited | | **Real-time Data** | ✓ | ✓ | ✓ | ✓ | | **Technical Indicators** | Basic | All | All | All + Custom | | **Social Sentiment** | ✗ | ✓ | ✓ | ✓ | | **AI Predictions** | ✗ | ✗ | ✓ | ✓ | | **Support** | Community | Email | Priority | Dedicated | | **Price** | Free | $29/month | $99/month | Contact | ## Best Practices ### 1. Efficient API Usage - **Batch Requests**: Combine multiple symbol requests when possible - **Caching**: Cache responses locally to reduce API calls - **Error Handling**: Implement proper retry logic with exponential backoff - **Rate Limiting**: Monitor your usage to avoid hitting limits ### 2. Data Freshness - **Market Hours**: Real-time data available during market hours - **After Hours**: Limited data updates outside trading hours - **Weekends**: Historical data only, no real-time updates - **Holidays**: Check market calendar for trading schedules ### 3. Security - **API Key Protection**: Never expose API keys in client-side code - **Environment Variables**: Store keys securely in environment variables - **HTTPS Only**: Always use HTTPS for API requests - **Key Rotation**: Regularly rotate API keys for security ## Support & Resources ### Documentation - **API Reference**: https://docs.financialcontext.ai - **OpenAPI Spec**: https://api.financialcontext.ai/openapi.json - **Postman Collection**: Available in documentation - **Code Examples**: GitHub repository with samples ### Community - **Discord Server**: Real-time community support - **GitHub Issues**: Bug reports and feature requests - **Stack Overflow**: Tag questions with `financial-context-api` - **Blog**: Latest updates and tutorials ### Contact - **Email**: support@financialcontext.ai - **Enterprise Sales**: enterprise@financialcontext.ai - **Status Page**: https://status.financialcontext.ai - **Changelog**: https://changelog.financialcontext.ai --- **Financial Context API** - Empowering AI agents and developers with comprehensive financial data and intelligence. Built for modern applications that require real-time market insights, company analysis, and predictive analytics.