{ "mcp_server_info": { "name": "SEC Financial Report MCP Server", "description": "FastAPI-based MCP Server for querying SEC EDGAR financial data", "base_url_local": "http://localhost:7860", "base_url_deployed": "https://YOUR_USERNAME-YOUR_SPACE_NAME.hf.space", "documentation": { "swagger_ui": "/docs", "redoc": "/redoc" } }, "api_endpoints": { "1_search_company": { "name": "Search Company by Name", "endpoint": "/api/search_company", "method": "POST", "description": "Search for a company by name and retrieve its CIK number", "request_example": { "company_name": "NVIDIA" }, "response_success": { "cik": "0001045810", "name": "NVIDIA CORP", "ticker": "NVDA", "error": null }, "response_not_found": { "cik": null, "name": null, "ticker": null, "error": "No company found matching 'INVALID_COMPANY'" }, "curl_example": "curl -X POST 'https://YOUR_SPACE.hf.space/api/search_company' -H 'Content-Type: application/json' -d '{\"company_name\": \"NVIDIA\"}'", "python_example": "import requests\nresponse = requests.post('https://YOUR_SPACE.hf.space/api/search_company', json={'company_name': 'NVIDIA'})\nprint(response.json())", "javascript_example": "fetch('https://YOUR_SPACE.hf.space/api/search_company', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({company_name: 'NVIDIA'})\n}).then(r => r.json()).then(console.log)", "notes": [ "Returns exact match first, then partial matches", "CIK is zero-padded to 10 digits", "Search is case-insensitive" ] }, "2_get_company_info": { "name": "Get Company Information", "endpoint": "/api/get_company_info", "method": "POST", "description": "Retrieve detailed company information using CIK", "request_example": { "cik": "0001045810" }, "response_success": { "cik": "0001045810", "name": "NVIDIA CORP", "tickers": ["NVDA"], "sic": "3674", "sic_description": "Semiconductors & Related Devices", "error": null }, "response_not_found": { "cik": null, "name": null, "tickers": null, "sic": null, "sic_description": null, "error": "No company information found for CIK: 9999999999" }, "curl_example": "curl -X POST 'https://YOUR_SPACE.hf.space/api/get_company_info' -H 'Content-Type: application/json' -d '{\"cik\": \"0001045810\"}'", "python_example": "import requests\nresponse = requests.post('https://YOUR_SPACE.hf.space/api/get_company_info', json={'cik': '0001045810'})\ninfo = response.json()\nprint(f\"Company: {info['name']}\")\nprint(f\"Industry: {info['sic_description']}\")", "javascript_example": "fetch('https://YOUR_SPACE.hf.space/api/get_company_info', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({cik: '0001045810'})\n}).then(r => r.json()).then(data => console.log(data.name))", "notes": [ "CIK must be zero-padded to 10 digits", "SIC code represents industry classification", "Multiple tickers may exist for one company" ] }, "3_get_company_filings": { "name": "Get Company Filings", "endpoint": "/api/get_company_filings", "method": "POST", "description": "Retrieve company SEC filings with optional form type filter", "request_all_forms": { "cik": "0001045810", "form_types": null }, "request_specific_forms": { "cik": "0001045810", "form_types": ["10-K", "10-Q"] }, "response_success": { "filings": [ { "form_type": "10-K", "filing_date": "2024-02-21", "accession_number": "0001045810-24-000029", "primary_document": "nvda-20240128.htm" }, { "form_type": "10-Q", "filing_date": "2024-11-20", "accession_number": "0001045810-24-000147", "primary_document": "nvda-20241027.htm" } ], "error": null }, "response_not_found": { "filings": [], "error": "No filings found for CIK: 0001045810" }, "curl_example": "curl -X POST 'https://YOUR_SPACE.hf.space/api/get_company_filings' -H 'Content-Type: application/json' -d '{\"cik\": \"0001045810\", \"form_types\": [\"10-K\", \"10-Q\"]}'", "python_example": "import requests\nresponse = requests.post(\n 'https://YOUR_SPACE.hf.space/api/get_company_filings',\n json={'cik': '0001045810', 'form_types': ['10-K', '10-Q']}\n)\nfilings = response.json()['filings']\nfor filing in filings[:5]:\n print(f\"{filing['form_type']}: {filing['filing_date']}\")", "javascript_example": "fetch('https://YOUR_SPACE.hf.space/api/get_company_filings', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({cik: '0001045810', form_types: ['10-K']})\n}).then(r => r.json()).then(data => data.filings.forEach(f => console.log(f.form_type)))", "form_types_reference": { "10-K": "Annual report (US companies)", "10-Q": "Quarterly report (US companies)", "20-F": "Annual report (Foreign private issuers)", "8-K": "Current report (major events)", "S-1": "Registration statement" }, "notes": [ "Set form_types to null to get all filing types", "Filings are returned in reverse chronological order", "Most companies file multiple forms per year" ] }, "4_get_company_facts": { "name": "Get Company Financial Facts", "endpoint": "/api/get_company_facts", "method": "POST", "description": "Retrieve complete XBRL financial facts data for a company", "request_example": { "cik": "0001045810" }, "response_structure": { "facts": { "us-gaap": { "Revenues": { "label": "Revenues", "description": "Amount of revenue recognized...", "units": { "USD": [ { "end": "2024-01-28", "val": 60922000000, "accn": "0001045810-24-000029", "fy": 2024, "fp": "FY", "form": "10-K", "filed": "2024-02-21", "frame": "CY2023" } ] } }, "NetIncomeLoss": "...", "EarningsPerShareBasic": "..." }, "ifrs-full": { "Revenue": "..." }, "dei": { "EntityCommonStockSharesOutstanding": "..." } }, "error": null }, "curl_example": "curl -X POST 'https://YOUR_SPACE.hf.space/api/get_company_facts' -H 'Content-Type: application/json' -d '{\"cik\": \"0001045810\"}'", "python_example": "import requests\nresponse = requests.post(\n 'https://YOUR_SPACE.hf.space/api/get_company_facts',\n json={'cik': '0001045810'}\n)\nfacts = response.json()['facts']\nprint(f\"Available standards: {list(facts.keys())}\")\nif 'us-gaap' in facts:\n print(f\"US-GAAP metrics count: {len(facts['us-gaap'])}\")", "javascript_example": "fetch('https://YOUR_SPACE.hf.space/api/get_company_facts', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({cik: '0001045810'})\n}).then(r => r.json()).then(data => console.log(Object.keys(data.facts)))", "notes": [ "Response can be very large (several MB)", "Contains historical data for all reported periods", "Supports both US-GAAP and IFRS standards", "Best for advanced analysis requiring raw XBRL data" ] }, "5_get_financial_data_annual": { "name": "Get Annual Financial Data", "endpoint": "/api/get_financial_data", "method": "POST", "description": "Extract key financial metrics for a specific fiscal year", "request_example": { "cik": "0001045810", "period": "2024" }, "response_success": { "period": "2024", "total_revenue": 60922000000, "net_income": 29760000000, "earnings_per_share": 12.04, "operating_expenses": 11822000000, "operating_cash_flow": 28091000000, "source_url": "https://www.sec.gov/Archives/edgar/data/1045810/000104581024000029", "source_form": "10-K", "data_source": "us-gaap", "additional_details": { "total_revenue_details": { "tag": "Revenues", "form": "10-K", "fy": 2024, "fp": "FY", "val": 60922000000, "start": "2023-01-30", "end": "2024-01-28", "accn": "0001045810-24-000029", "filed": "2024-02-21", "frame": "CY2023", "data_source": "us-gaap" } }, "error": null }, "curl_example": "curl -X POST 'https://YOUR_SPACE.hf.space/api/get_financial_data' -H 'Content-Type: application/json' -d '{\"cik\": \"0001045810\", \"period\": \"2024\"}'", "python_example": "import requests\nresponse = requests.post(\n 'https://YOUR_SPACE.hf.space/api/get_financial_data',\n json={'cik': '0001045810', 'period': '2024'}\n)\ndata = response.json()\nprint(f\"Period: FY{data['period']}\")\nprint(f\"Revenue: ${data['total_revenue']:,.0f}\")\nprint(f\"Net Income: ${data['net_income']:,.0f}\")\nprint(f\"EPS: ${data['earnings_per_share']:.2f}\")\nprint(f\"Source: {data['source_form']}\")", "javascript_example": "fetch('https://YOUR_SPACE.hf.space/api/get_financial_data', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({cik: '0001045810', period: '2024'})\n}).then(r => r.json()).then(data => {\n console.log(`Revenue: $${(data.total_revenue / 1e9).toFixed(2)}B`);\n console.log(`Net Income: $${(data.net_income / 1e9).toFixed(2)}B`);\n})", "notes": [ "Period format: 'YYYY' for annual data", "All monetary values in USD (original values)", "EPS is per share value", "Data sourced from 10-K (US) or 20-F (foreign) forms" ] }, "6_get_financial_data_quarterly": { "name": "Get Quarterly Financial Data", "endpoint": "/api/get_financial_data", "method": "POST", "description": "Extract key financial metrics for a specific quarter", "request_example": { "cik": "0001045810", "period": "2024Q3" }, "response_success": { "period": "2024Q3", "total_revenue": 30040000000, "net_income": 19309000000, "earnings_per_share": 7.81, "operating_expenses": 3932000000, "operating_cash_flow": 14502000000, "source_url": "https://www.sec.gov/Archives/edgar/data/1045810/000104581024000147", "source_form": "10-Q", "data_source": "us-gaap", "additional_details": null, "error": null }, "curl_example": "curl -X POST 'https://YOUR_SPACE.hf.space/api/get_financial_data' -H 'Content-Type: application/json' -d '{\"cik\": \"0001045810\", \"period\": \"2024Q3\"}'", "python_example": "import requests\n\n# Get multiple quarters for comparison\nquarters = ['2024Q1', '2024Q2', '2024Q3']\nfor quarter in quarters:\n response = requests.post(\n 'https://YOUR_SPACE.hf.space/api/get_financial_data',\n json={'cik': '0001045810', 'period': quarter}\n )\n data = response.json()\n if not data.get('error'):\n print(f\"{quarter}: Revenue ${data['total_revenue']/1e9:.2f}B\")", "javascript_example": "// Compare Q3 vs Q2\nconst periods = ['2024Q3', '2024Q2'];\nPromise.all(periods.map(period =>\n fetch('https://YOUR_SPACE.hf.space/api/get_financial_data', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({cik: '0001045810', period})\n }).then(r => r.json())\n)).then(results => results.forEach(d => \n console.log(`${d.period}: $${(d.total_revenue/1e9).toFixed(2)}B`)\n))", "quarter_reference": { "Q1": "First quarter (typically Jan-Mar or similar)", "Q2": "Second quarter (typically Apr-Jun or similar)", "Q3": "Third quarter (typically Jul-Sep or similar)", "Q4": "Fourth quarter (typically Oct-Dec or similar)" }, "notes": [ "Period format: 'YYYYQX' where X is 1, 2, 3, or 4", "Data sourced from 10-Q forms", "Foreign companies (20-F filers) typically don't file quarterly reports", "Quarters may not align with calendar year for all companies" ] }, "7_health_check": { "name": "Health Check", "endpoint": "/health", "method": "GET", "description": "Check if the MCP server is running and healthy", "request": "No request body required (GET request)", "response": { "status": "healthy", "service": "SEC Financial Report MCP Server" }, "curl_example": "curl https://YOUR_SPACE.hf.space/health", "python_example": "import requests\nresponse = requests.get('https://YOUR_SPACE.hf.space/health')\nif response.json()['status'] == 'healthy':\n print('✓ Server is running')", "javascript_example": "fetch('https://YOUR_SPACE.hf.space/health')\n .then(r => r.json())\n .then(data => console.log(`Status: ${data.status}`))", "notes": [ "No authentication required", "Use for monitoring and health checks", "Always returns 200 if server is running" ] }, "8_advanced_search": { "name": "Advanced Company Search", "endpoint": "/api/advanced_search", "method": "POST", "description": "Advanced search supporting both company name and CIK (uses FinancialAnalyzer.search_company)", "request_by_name": { "company_input": "Apple" }, "request_by_cik": { "company_input": "0000320193" }, "response_success": { "cik": "0000320193", "name": "Apple Inc.", "tickers": ["AAPL"], "sic": "3571", "sic_description": "Electronic Computers", "error": null }, "curl_example": "curl -X POST 'https://YOUR_SPACE.hf.space/api/advanced_search' -H 'Content-Type: application/json' -d '{\"company_input\": \"Apple\"}'" , "python_example": "import requests\n\n# Search by name\nresponse = requests.post(\n 'https://YOUR_SPACE.hf.space/api/advanced_search',\n json={'company_input': 'Apple'}\n)\nprint(response.json())\n\n# Search by CIK\nresponse = requests.post(\n 'https://YOUR_SPACE.hf.space/api/advanced_search',\n json={'company_input': '0000320193'}\n)\nprint(response.json())", "javascript_example": "// Flexible search - works with both name and CIK\nfetch('https://YOUR_SPACE.hf.space/api/advanced_search', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({company_input: 'Apple'})\n}).then(r => r.json()).then(console.log)", "notes": [ "Automatically detects if input is CIK (numeric, 8+ digits) or company name", "Returns full company information including SIC", "More intelligent than basic search_company endpoint" ] }, "9_extract_financial_metrics": { "name": "Extract Multi-Year Financial Metrics", "endpoint": "/api/extract_financial_metrics", "method": "POST", "description": "Extract financial metrics for multiple years (both annual and quarterly data)", "request_example": { "cik": "0001045810", "years": 3 }, "response_success": { "metrics": [ { "period": "2024", "total_revenue": 60922000000, "net_income": 29760000000, "earnings_per_share": 12.04, "operating_expenses": 11822000000, "operating_cash_flow": 28091000000, "source_form": "10-K", "data_source": "us-gaap" }, { "period": "2024Q4", "total_revenue": 35082000000, "net_income": 19309000000, "earnings_per_share": 7.81, "source_form": "10-Q" }, { "period": "2024Q3", "total_revenue": 30040000000, "net_income": 16599000000, "earnings_per_share": 6.70, "source_form": "10-Q" } ], "count": 3, "error": null }, "curl_example": "curl -X POST 'https://YOUR_SPACE.hf.space/api/extract_financial_metrics' -H 'Content-Type: application/json' -d '{\"cik\": \"0001045810\", \"years\": 3}'", "python_example": "import requests\nimport pandas as pd\n\nresponse = requests.post(\n 'https://YOUR_SPACE.hf.space/api/extract_financial_metrics',\n json={'cik': '0001045810', 'years': 3}\n)\ndata = response.json()\n\n# Convert to DataFrame for easy analysis\ndf = pd.DataFrame(data['metrics'])\nprint(f\"Retrieved {data['count']} periods\")\nprint(df[['period', 'total_revenue', 'net_income', 'earnings_per_share']])", "javascript_example": "fetch('https://YOUR_SPACE.hf.space/api/extract_financial_metrics', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({cik: '0001045810', years: 3})\n}).then(r => r.json()).then(data => {\n console.log(`Found ${data.count} periods`);\n data.metrics.forEach(m => {\n console.log(`${m.period}: Revenue $${(m.total_revenue/1e9).toFixed(2)}B`);\n });\n})", "notes": [ "Returns both annual (e.g., '2024') and quarterly (e.g., '2024Q3') data", "Data is automatically formatted and sorted by period", "Years parameter: min=1, max=10, default=3", "Very useful for trend analysis and historical comparison" ] }, "10_get_latest_financial_data": { "name": "Get Latest Financial Data", "endpoint": "/api/get_latest_financial_data", "method": "POST", "description": "Get the most recent annual financial data for a company", "request_example": { "cik": "0001045810" }, "response_success": { "period": "2024", "total_revenue": 60922000000, "net_income": 29760000000, "earnings_per_share": 12.04, "operating_expenses": 11822000000, "operating_cash_flow": 28091000000, "source_url": "https://www.sec.gov/Archives/edgar/data/1045810/000104581024000029", "source_form": "10-K", "data_source": "us-gaap", "error": null }, "curl_example": "curl -X POST 'https://YOUR_SPACE.hf.space/api/get_latest_financial_data' -H 'Content-Type: application/json' -d '{\"cik\": \"0001045810\"}' ", "python_example": "import requests\n\nresponse = requests.post(\n 'https://YOUR_SPACE.hf.space/api/get_latest_financial_data',\n json={'cik': '0001045810'}\n)\ndata = response.json()\n\nif not data.get('error'):\n print(f\"Latest Data: FY{data['period']}\")\n print(f\"Revenue: ${data['total_revenue']:,.0f}\")\n print(f\"Net Income: ${data['net_income']:,.0f}\")\n print(f\"EPS: ${data['earnings_per_share']:.2f}\")\n print(f\"Source: {data['source_form']}\")\nelse:\n print(f\"Error: {data['error']}\")", "javascript_example": "fetch('https://YOUR_SPACE.hf.space/api/get_latest_financial_data', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({cik: '0001045810'})\n}).then(r => r.json()).then(data => {\n if (!data.error) {\n console.log(`Latest FY${data.period}`);\n console.log(`Revenue: $${(data.total_revenue/1e9).toFixed(2)}B`);\n console.log(`Net Income: $${(data.net_income/1e9).toFixed(2)}B`);\n }\n})", "notes": [ "Automatically finds and returns the most recent annual report data", "Saves you from having to manually determine the latest year", "Returns data from most recent 10-K or 20-F filing", "Ideal for getting current snapshot without knowing fiscal year" ] } }, "complete_workflow_examples": { "example_1_basic_company_analysis": { "name": "Basic Company Financial Analysis", "description": "Search a company and get its latest annual financial data", "steps": [ { "step": 1, "action": "Search for company", "endpoint": "/api/search_company", "request": { "company_name": "Apple" }, "extract": "cik" }, { "step": 2, "action": "Get company information", "endpoint": "/api/get_company_info", "request": { "cik": "{{cik_from_step_1}}" }, "extract": "name, tickers, sic_description" }, { "step": 3, "action": "Get latest annual financial data", "endpoint": "/api/get_financial_data", "request": { "cik": "{{cik_from_step_1}}", "period": "2024" }, "extract": "total_revenue, net_income, earnings_per_share" } ], "python_code": "import requests\n\nBASE_URL = 'https://YOUR_SPACE.hf.space'\n\n# Step 1: Search company\nresponse = requests.post(f'{BASE_URL}/api/search_company', \n json={'company_name': 'Apple'})\ncompany = response.json()\ncik = company['cik']\nprint(f\"Found: {company['name']} (CIK: {cik})\")\n\n# Step 2: Get company info\nresponse = requests.post(f'{BASE_URL}/api/get_company_info',\n json={'cik': cik})\ninfo = response.json()\nprint(f\"Industry: {info['sic_description']}\")\n\n# Step 3: Get financial data\nresponse = requests.post(f'{BASE_URL}/api/get_financial_data',\n json={'cik': cik, 'period': '2024'})\ndata = response.json()\nprint(f\"FY2024 Revenue: ${data['total_revenue']:,.0f}\")\nprint(f\"FY2024 Net Income: ${data['net_income']:,.0f}\")\nprint(f\"FY2024 EPS: ${data['earnings_per_share']:.2f}\")" }, "example_2_quarterly_trend_analysis": { "name": "Quarterly Revenue Trend Analysis", "description": "Analyze revenue trends across multiple quarters", "steps": [ { "step": 1, "action": "Get Q1 2024 data", "endpoint": "/api/get_financial_data", "request": { "cik": "0001045810", "period": "2024Q1" } }, { "step": 2, "action": "Get Q2 2024 data", "endpoint": "/api/get_financial_data", "request": { "cik": "0001045810", "period": "2024Q2" } }, { "step": 3, "action": "Get Q3 2024 data", "endpoint": "/api/get_financial_data", "request": { "cik": "0001045810", "period": "2024Q3" } } ], "python_code": "import requests\nimport pandas as pd\n\nBASE_URL = 'https://YOUR_SPACE.hf.space'\nCIK = '0001045810' # NVIDIA\n\n# Get quarterly data\nquarters = ['2024Q1', '2024Q2', '2024Q3']\ndata_list = []\n\nfor quarter in quarters:\n response = requests.post(\n f'{BASE_URL}/api/get_financial_data',\n json={'cik': CIK, 'period': quarter}\n )\n data = response.json()\n if not data.get('error'):\n data_list.append({\n 'Quarter': quarter,\n 'Revenue': data['total_revenue'] / 1e9, # Convert to billions\n 'Net Income': data['net_income'] / 1e9,\n 'EPS': data['earnings_per_share']\n })\n\n# Create DataFrame and analyze\ndf = pd.DataFrame(data_list)\nprint(df)\nprint(f\"\\nRevenue Growth Q2->Q3: {((df.iloc[2]['Revenue'] / df.iloc[1]['Revenue']) - 1) * 100:.1f}%\")" }, "example_3_multi_company_comparison": { "name": "Compare Multiple Companies", "description": "Compare financial metrics across different companies", "companies": ["NVIDIA", "AMD", "Intel"], "python_code": "import requests\n\nBASE_URL = 'https://YOUR_SPACE.hf.space'\ncompanies = ['NVIDIA', 'AMD', 'Intel']\nperiod = '2024'\n\nresults = []\nfor company_name in companies:\n # Search company\n response = requests.post(\n f'{BASE_URL}/api/search_company',\n json={'company_name': company_name}\n )\n company = response.json()\n \n if not company.get('error'):\n # Get financial data\n response = requests.post(\n f'{BASE_URL}/api/get_financial_data',\n json={'cik': company['cik'], 'period': period}\n )\n data = response.json()\n \n if not data.get('error'):\n results.append({\n 'Company': company['name'],\n 'Revenue (B)': data['total_revenue'] / 1e9,\n 'Net Income (B)': data['net_income'] / 1e9,\n 'EPS': data['earnings_per_share']\n })\n\n# Print comparison\nfor result in results:\n print(f\"{result['Company']}:\")\n print(f\" Revenue: ${result['Revenue (B)']:.2f}B\")\n print(f\" Net Income: ${result['Net Income (B)']:.2f}B\")\n print(f\" EPS: ${result['EPS']:.2f}\\n\")" }, "example_4_filing_history_analysis": { "name": "Analyze Filing History", "description": "Get and analyze a company's filing history", "python_code": "import requests\nfrom datetime import datetime\n\nBASE_URL = 'https://YOUR_SPACE.hf.space'\nCIK = '0001045810'\n\n# Get all 10-K filings\nresponse = requests.post(\n f'{BASE_URL}/api/get_company_filings',\n json={'cik': CIK, 'form_types': ['10-K']}\n)\nfilings = response.json()['filings']\n\nprint(f\"Found {len(filings)} annual reports (10-K)\\n\")\n\n# Analyze filing dates\nfor filing in filings[:5]: # Last 5 years\n filing_date = datetime.strptime(filing['filing_date'], '%Y-%m-%d')\n print(f\"Form: {filing['form_type']}\")\n print(f\"Filed: {filing_date.strftime('%B %d, %Y')}\")\n print(f\"Document: {filing['primary_document']}\")\n print(f\"Accession: {filing['accession_number']}\")\n print()" } }, "error_handling_examples": { "handling_company_not_found": { "scenario": "Company name not found in database", "python_code": "import requests\n\nBASE_URL = 'https://YOUR_SPACE.hf.space'\n\nresponse = requests.post(\n f'{BASE_URL}/api/search_company',\n json={'company_name': 'INVALID_COMPANY_XYZ'}\n)\nresult = response.json()\n\nif result.get('error'):\n print(f\"Error: {result['error']}\")\n # Handle error: ask user to try again, suggest alternatives, etc.\nelse:\n print(f\"Found: {result['name']}\")" }, "handling_no_financial_data": { "scenario": "No financial data available for requested period", "python_code": "import requests\n\nBASE_URL = 'https://YOUR_SPACE.hf.space'\n\nresponse = requests.post(\n f'{BASE_URL}/api/get_financial_data',\n json={'cik': '0001045810', 'period': '1990'}\n)\ndata = response.json()\n\nif data.get('error'):\n print(f\"No data available: {data['error']}\")\n # Try different period or notify user\nelif not data.get('total_revenue'):\n print(\"Warning: Incomplete data for this period\")\n # Handle partial data\nelse:\n print(f\"Revenue: ${data['total_revenue']:,.0f}\")" }, "handling_network_errors": { "scenario": "Handle network errors and timeouts", "python_code": "import requests\nfrom requests.exceptions import RequestException, Timeout\n\nBASE_URL = 'https://YOUR_SPACE.hf.space'\n\ntry:\n response = requests.post(\n f'{BASE_URL}/api/search_company',\n json={'company_name': 'NVIDIA'},\n timeout=10 # 10 seconds timeout\n )\n response.raise_for_status() # Raise error for 4xx/5xx status\n data = response.json()\n print(f\"Success: {data['name']}\")\n \nexcept Timeout:\n print(\"Request timed out. Server may be slow or unavailable.\")\nexcept RequestException as e:\n print(f\"Network error occurred: {e}\")\nexcept Exception as e:\n print(f\"Unexpected error: {e}\")" }, "handling_validation_errors": { "scenario": "Handle request validation errors (422 status)", "python_code": "import requests\n\nBASE_URL = 'https://YOUR_SPACE.hf.space'\n\n# Invalid request (missing required field)\nresponse = requests.post(\n f'{BASE_URL}/api/search_company',\n json={'wrong_field': 'value'}\n)\n\nif response.status_code == 422:\n errors = response.json()['detail']\n print(\"Validation errors:\")\n for error in errors:\n field = error['loc'][-1]\n message = error['msg']\n print(f\" - {field}: {message}\")\nelse:\n data = response.json()\n print(data)" } }, "best_practices": { "rate_limiting": { "description": "SEC EDGAR API has rate limits (10 requests per second)", "recommendation": "Add delays between requests when fetching multiple companies", "python_example": "import requests\nimport time\n\nBASE_URL = 'https://YOUR_SPACE.hf.space'\ncompanies = ['NVIDIA', 'AMD', 'Intel', 'TSMC']\n\nfor company in companies:\n response = requests.post(\n f'{BASE_URL}/api/search_company',\n json={'company_name': company}\n )\n print(response.json())\n time.sleep(0.2) # 200ms delay = max 5 requests/second" }, "caching_results": { "description": "Cache results to avoid repeated API calls for same data", "python_example": "import requests\nimport json\nfrom pathlib import Path\n\ncache_file = Path('financial_data_cache.json')\n\ndef get_financial_data(cik, period):\n # Try to load from cache\n cache = {}\n if cache_file.exists():\n cache = json.loads(cache_file.read_text())\n \n cache_key = f\"{cik}_{period}\"\n if cache_key in cache:\n print(\"Using cached data\")\n return cache[cache_key]\n \n # Fetch from API\n response = requests.post(\n 'https://YOUR_SPACE.hf.space/api/get_financial_data',\n json={'cik': cik, 'period': period}\n )\n data = response.json()\n \n # Save to cache\n cache[cache_key] = data\n cache_file.write_text(json.dumps(cache, indent=2))\n \n return data" }, "error_handling": { "description": "Always check for errors in API responses", "python_example": "def safe_api_call(endpoint, payload):\n try:\n response = requests.post(endpoint, json=payload, timeout=10)\n response.raise_for_status()\n data = response.json()\n \n if data.get('error'):\n print(f\"API Error: {data['error']}\")\n return None\n \n return data\n except Exception as e:\n print(f\"Request failed: {e}\")\n return None\n\n# Usage\nresult = safe_api_call(\n 'https://YOUR_SPACE.hf.space/api/search_company',\n {'company_name': 'NVIDIA'}\n)\nif result:\n print(f\"Found: {result['name']}\")" }, "data_validation": { "description": "Validate data before using it in calculations", "python_example": "def calculate_profit_margin(financial_data):\n revenue = financial_data.get('total_revenue')\n net_income = financial_data.get('net_income')\n \n # Validate data exists and is valid\n if not revenue or not net_income:\n return None\n if revenue <= 0:\n return None\n \n # Calculate margin\n margin = (net_income / revenue) * 100\n return round(margin, 2)\n\n# Usage\ndata = get_financial_data('0001045810', '2024')\nmargin = calculate_profit_margin(data)\nif margin:\n print(f\"Profit Margin: {margin}%\")\nelse:\n print(\"Unable to calculate profit margin\")" } }, "notes": { "data_format": "All monetary values are in USD (original amounts, not scaled)", "eps_format": "Earnings per share is per-share value", "period_formats": { "annual": "YYYY (e.g., '2024')", "quarterly": "YYYYQX (e.g., '2024Q3')" }, "supported_forms": { "10-K": "Annual report for US companies", "10-Q": "Quarterly report for US companies", "20-F": "Annual report for foreign private issuers" }, "accounting_standards": ["US-GAAP", "IFRS"], "user_agent": "Juntao Peng Financial Report Metrics App (jtyxabc@gmail.com)", "rate_limiting": "Follow SEC EDGAR guidelines (10 requests per second)", "documentation_urls": { "swagger_ui": "/docs", "redoc": "/redoc" } } }