Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement financial_modelling import source (#66761)

Tom Owersbda28afcb6e1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index d561ce2bc160..bf90797fedda 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -42,203 +42,204 @@ the row lists both.
## Implemented sources
-| Source | Comm method | Primary library | Tracked transport |
-| ----------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- |
-| adroll | HTTP | requests | ✅ |
-| aircall | HTTP | requests | ✅ |
-| airtable | HTTP | requests | ✅ |
-| algolia | HTTP | requests | ✅ |
-| amazon_ads | HTTP | requests | ✅ |
-| amplitude | HTTP | requests | ✅ |
-| apollo | HTTP | requests | ✅ |
-| appsflyer | HTTP (CSV reports) | requests | ✅ |
-| asana | HTTP | requests | ✅ |
-| ashby | HTTP | requests | ✅ |
-| attentive | HTTP (webhook-first) | requests (webhook management) | ✅ |
-| attio | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| azure_devops | HTTP | requests | ✅ |
-| bamboohr | HTTP | requests | ✅ |
-| beamer | HTTP | requests | ✅ |
-| bigmailer | HTTP | requests | ✅ |
-| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
-| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
-| braintree | HTTP (GraphQL) | requests | ✅ |
-| braze | HTTP | requests | ✅ |
-| brevo | HTTP | requests | ✅ |
-| brex | HTTP | requests | ✅ |
-| bugsnag | HTTP | requests | ✅ |
-| buildbetter | HTTP | requests | ✅ |
-| buildkite | HTTP | requests | ✅ |
-| calendly | HTTP | requests | ✅ |
-| campaign_monitor | HTTP | requests | ✅ |
-| canny | HTTP | requests | ✅ |
-| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| chargedesk | HTTP | requests | ✅ |
-| checkout_com | HTTP | requests | ✅ |
-| coda | HTTP | requests | ✅ |
-| coingecko | HTTP | requests | ✅ |
-| coinmarketcap | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| commercetools | HTTP | requests | ✅ |
-| confluence | HTTP | requests | ✅ |
-| chartmogul | HTTP | requests | ✅ |
-| circleci | HTTP | requests | ✅ |
-| cloudflare | HTTP | requests | ✅ |
-| clari | HTTP | requests | ✅ |
-| clerk | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| clickhouse | DB protocol (HTTP-based) | clickhouse-connect / clickhouse-driver | ➖ |
-| clickup | HTTP | requests | ✅ |
-| clockify | HTTP | requests | ✅ |
-| close | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| convertkit | HTTP | requests | ✅ |
-| convex | HTTP | requests | ✅ |
-| copper | HTTP | requests | ✅ |
-| coupa | HTTP | requests | ✅ |
-| crunchbase | HTTP | requests | ✅ |
-| culture_amp | HTTP | requests | ✅ |
-| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) |
-| datadog | HTTP | requests | ✅ |
-| deel | HTTP | requests | ✅ |
-| delighted | HTTP | requests | ✅ |
-| dixa | HTTP | requests | ✅ |
-| docuseal | HTTP | requests | ✅ |
-| doit | HTTP | requests | ✅ |
-| drip | HTTP | requests | ✅ |
-| easypost | HTTP | requests | ✅ |
-| freshdesk | HTTP | requests | ✅ |
-| freshsales | HTTP | requests | ✅ |
-| elasticemail | HTTP | requests | ✅ |
-| elasticsearch | HTTP | requests | ✅ |
-| emailoctopus | HTTP | requests | ✅ |
-| eventbrite | HTTP | requests | ✅ |
-| everhour | HTTP | requests | ✅ |
-| fillout | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| finnworlds | HTTP | requests | ✅ |
-| front | HTTP | requests | ✅ |
-| fullstory | HTTP | requests | ✅ |
-| github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
-| giphy | HTTP | requests | ✅ |
-| gitlab | HTTP | requests | ✅ |
-| gladly | HTTP | requests | ✅ |
-| gocardless | HTTP | requests | ✅ |
-| gong | HTTP | requests | ✅ |
-| google_ads | gRPC | google-ads (googleads.client) | ✅ |
-| google_analytics | HTTP | requests (`AuthorizedSession` + `TrackedHTTPAdapter`) | ✅ |
-| google_sheets | HTTP (vendor SDK) | gspread | ✅ |
-| granola | HTTP | requests | ✅ |
-| gorgias | HTTP | requests | ✅ |
-| greenhouse | HTTP | requests | ✅ |
-| guru | HTTP | requests | ✅ |
-| hibob | HTTP | requests | ✅ |
-| hubspot | HTTP | requests | ✅ |
-| incident_io | HTTP | requests | ✅ |
-| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| iterable | HTTP | requests | ✅ |
-| jira | HTTP | requests | ✅ |
-| jotform | HTTP | requests | ✅ |
-| klaviyo | HTTP | requests | ✅ |
-| lago | HTTP | requests | ✅ |
-| launchdarkly | HTTP | requests | ✅ |
-| kustomer | HTTP | requests | ✅ |
-| lattice | HTTP | requests | ✅ |
-| lemlist | HTTP | requests | ✅ |
-| lightspeed_retail | HTTP | requests | ✅ |
-| linear | HTTP | requests | ✅ |
-| lever | HTTP | requests | ✅ |
-| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |
-| lob | HTTP | requests | ✅ |
-| mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| mailerlite | HTTP | requests | ✅ |
-| mailersend | HTTP | requests | ✅ |
-| mailgun | HTTP | requests | ✅ |
-| mailjet | HTTP | requests | ✅ |
-| matomo | HTTP | requests | ✅ |
-| meta_ads | HTTP | requests | ✅ |
-| metabase | HTTP | requests | ✅ |
-| mixpanel | HTTP | requests | ✅ |
-| mollie | HTTP | requests | ✅ |
-| monday | HTTP (GraphQL) | requests | ✅ |
-| mongodb | DB protocol | pymongo | ➖ |
-| mssql | DB protocol | pyodbc / pymssql | ➖ |
-| mux | HTTP | requests | ✅ |
-| mysql | DB protocol | pymysql | ➖ |
-| okta | HTTP | requests | ✅ |
-| notion | HTTP | requests | ✅ |
-| omnisend | HTTP | requests | ✅ |
-| orb | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| openweather | HTTP | requests | ✅ |
-| ortto | HTTP | requests | ✅ |
-| oura | HTTP | requests | ✅ |
-| outbrain | HTTP | requests | ✅ |
-| paddle | HTTP | requests | ✅ |
-| optimizely | HTTP | requests | ✅ |
-| pagerduty | HTTP | requests | ✅ |
-| pandadoc | HTTP | requests | ✅ |
-| paystack | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| pendo | HTTP | requests | ✅ |
-| personio | HTTP | requests | ✅ |
-| pingdom | HTTP | requests | ✅ |
-| pinterest_ads | HTTP | requests | ✅ |
-| pipedrive | HTTP | requests | ✅ |
-| plain | HTTP | requests | ✅ |
-| plausible | HTTP | requests | ✅ |
-| polar | HTTP | requests | ✅ |
-| plaid | HTTP | requests | ✅ |
-| postgres | DB protocol | psycopg | ➖ |
-| postmark | HTTP | requests | ✅ |
-| productboard | HTTP | requests | ✅ |
-| pylon | HTTP | requests | ✅ |
-| recurly | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| ramp | HTTP | requests | ✅ |
-| recharge | HTTP | requests | ✅ |
-| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| redshift | DB protocol | psycopg (Postgres-compatible) | ➖ |
-| resend | HTTP | requests | ✅ |
-| revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
-| rippling | HTTP | requests | ✅ |
-| rollbar | HTTP | requests | ✅ |
-| rootly | HTTP | requests | ✅ |
-| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| salesloft | HTTP | requests | ✅ |
-| segment | HTTP | requests | ✅ |
-| sendgrid | HTTP | requests | ✅ |
-| sentry | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| servicenow | HTTP | requests | ✅ |
-| shipstation | HTTP | requests | ✅ |
-| shopify | HTTP | requests | ✅ |
-| shortcut | HTTP | requests | ✅ |
-| slack | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| smartsheet | HTTP | requests | ✅ |
-| snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| snowflake | DB protocol | snowflake-connector-python | ➖ |
-| sparkpost | HTTP | requests | ✅ |
-| square | HTTP | requests | ✅ |
-| squarespace | HTTP | requests | ✅ |
-| statuspage | HTTP | requests | ✅ |
-| stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
-| supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ |
-| surveymonkey | HTTP | requests | ✅ |
-| taboola | HTTP | requests | ✅ |
-| teamwork | HTTP | requests | ✅ |
-| temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |
-| thinkific | HTTP | requests | ✅ |
-| tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| tmdb | HTTP | requests | ✅ |
-| todoist | HTTP | requests | ✅ |
-| trello | HTTP | requests | ✅ |
-| twilio | HTTP | requests | ✅ |
-| typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| vercel | HTTP | requests | ✅ |
-| vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| webflow | HTTP | requests | ✅ |
-| woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| wordpress | HTTP | requests | ✅ |
-| workable | HTTP | requests | ✅ |
-| workos | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| wrike | HTTP | requests | ✅ |
-| zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| zendesk_sell | HTTP | requests | ✅ |
-| zoom | HTTP | requests | ✅ |
-| zuora | HTTP | requests | ✅ |
+| Source | Comm method | Primary library | Tracked transport |
+| ------------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- |
+| adroll | HTTP | requests | ✅ |
+| aircall | HTTP | requests | ✅ |
+| airtable | HTTP | requests | ✅ |
+| algolia | HTTP | requests | ✅ |
+| amazon_ads | HTTP | requests | ✅ |
+| amplitude | HTTP | requests | ✅ |
+| apollo | HTTP | requests | ✅ |
+| appsflyer | HTTP (CSV reports) | requests | ✅ |
+| asana | HTTP | requests | ✅ |
+| ashby | HTTP | requests | ✅ |
+| attentive | HTTP (webhook-first) | requests (webhook management) | ✅ |
+| attio | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| azure_devops | HTTP | requests | ✅ |
+| bamboohr | HTTP | requests | ✅ |
+| beamer | HTTP | requests | ✅ |
+| bigmailer | HTTP | requests | ✅ |
+| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
+| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
+| braintree | HTTP (GraphQL) | requests | ✅ |
+| braze | HTTP | requests | ✅ |
+| brevo | HTTP | requests | ✅ |
+| brex | HTTP | requests | ✅ |
+| bugsnag | HTTP | requests | ✅ |
+| buildbetter | HTTP | requests | ✅ |
+| buildkite | HTTP | requests | ✅ |
+| calendly | HTTP | requests | ✅ |
+| campaign_monitor | HTTP | requests | ✅ |
+| canny | HTTP | requests | ✅ |
+| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| chargedesk | HTTP | requests | ✅ |
+| checkout_com | HTTP | requests | ✅ |
+| coda | HTTP | requests | ✅ |
+| coingecko | HTTP | requests | ✅ |
+| coinmarketcap | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| commercetools | HTTP | requests | ✅ |
+| confluence | HTTP | requests | ✅ |
+| chartmogul | HTTP | requests | ✅ |
+| circleci | HTTP | requests | ✅ |
+| cloudflare | HTTP | requests | ✅ |
+| clari | HTTP | requests | ✅ |
+| clerk | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| clickhouse | DB protocol (HTTP-based) | clickhouse-connect / clickhouse-driver | ➖ |
+| clickup | HTTP | requests | ✅ |
+| clockify | HTTP | requests | ✅ |
+| close | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| convertkit | HTTP | requests | ✅ |
+| convex | HTTP | requests | ✅ |
+| copper | HTTP | requests | ✅ |
+| coupa | HTTP | requests | ✅ |
+| crunchbase | HTTP | requests | ✅ |
+| culture_amp | HTTP | requests | ✅ |
+| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) |
+| datadog | HTTP | requests | ✅ |
+| deel | HTTP | requests | ✅ |
+| delighted | HTTP | requests | ✅ |
+| dixa | HTTP | requests | ✅ |
+| docuseal | HTTP | requests | ✅ |
+| doit | HTTP | requests | ✅ |
+| drip | HTTP | requests | ✅ |
+| easypost | HTTP | requests | ✅ |
+| freshdesk | HTTP | requests | ✅ |
+| freshsales | HTTP | requests | ✅ |
+| elasticemail | HTTP | requests | ✅ |
+| elasticsearch | HTTP | requests | ✅ |
+| emailoctopus | HTTP | requests | ✅ |
+| eventbrite | HTTP | requests | ✅ |
+| everhour | HTTP | requests | ✅ |
+| fillout | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| financial_modelling | HTTP | requests | ✅ |
+| finnworlds | HTTP | requests | ✅ |
+| front | HTTP | requests | ✅ |
+| fullstory | HTTP | requests | ✅ |
+| github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
+| giphy | HTTP | requests | ✅ |
+| gitlab | HTTP | requests | ✅ |
+| gladly | HTTP | requests | ✅ |
+| gocardless | HTTP | requests | ✅ |
+| gong | HTTP | requests | ✅ |
+| google_ads | gRPC | google-ads (googleads.client) | ✅ |
+| google_analytics | HTTP | requests (`AuthorizedSession` + `TrackedHTTPAdapter`) | ✅ |
+| google_sheets | HTTP (vendor SDK) | gspread | ✅ |
+| granola | HTTP | requests | ✅ |
+| gorgias | HTTP | requests | ✅ |
+| greenhouse | HTTP | requests | ✅ |
+| guru | HTTP | requests | ✅ |
+| hibob | HTTP | requests | ✅ |
+| hubspot | HTTP | requests | ✅ |
+| incident_io | HTTP | requests | ✅ |
+| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| iterable | HTTP | requests | ✅ |
+| jira | HTTP | requests | ✅ |
+| jotform | HTTP | requests | ✅ |
+| klaviyo | HTTP | requests | ✅ |
+| lago | HTTP | requests | ✅ |
+| launchdarkly | HTTP | requests | ✅ |
+| kustomer | HTTP | requests | ✅ |
+| lattice | HTTP | requests | ✅ |
+| lemlist | HTTP | requests | ✅ |
+| lightspeed_retail | HTTP | requests | ✅ |
+| linear | HTTP | requests | ✅ |
+| lever | HTTP | requests | ✅ |
+| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |
+| lob | HTTP | requests | ✅ |
+| mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| mailerlite | HTTP | requests | ✅ |
+| mailersend | HTTP | requests | ✅ |
+| mailgun | HTTP | requests | ✅ |
+| mailjet | HTTP | requests | ✅ |
+| matomo | HTTP | requests | ✅ |
+| meta_ads | HTTP | requests | ✅ |
+| metabase | HTTP | requests | ✅ |
+| mixpanel | HTTP | requests | ✅ |
+| mollie | HTTP | requests | ✅ |
+| monday | HTTP (GraphQL) | requests | ✅ |
+| mongodb | DB protocol | pymongo | ➖ |
+| mssql | DB protocol | pyodbc / pymssql | ➖ |
+| mux | HTTP | requests | ✅ |
+| mysql | DB protocol | pymysql | ➖ |
+| okta | HTTP | requests | ✅ |
+| notion | HTTP | requests | ✅ |
+| omnisend | HTTP | requests | ✅ |
+| orb | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| openweather | HTTP | requests | ✅ |
+| ortto | HTTP | requests | ✅ |
+| oura | HTTP | requests | ✅ |
+| outbrain | HTTP | requests | ✅ |
+| paddle | HTTP | requests | ✅ |
+| optimizely | HTTP | requests | ✅ |
+| pagerduty | HTTP | requests | ✅ |
+| pandadoc | HTTP | requests | ✅ |
+| paystack | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| pendo | HTTP | requests | ✅ |
+| personio | HTTP | requests | ✅ |
+| pingdom | HTTP | requests | ✅ |
+| pinterest_ads | HTTP | requests | ✅ |
+| pipedrive | HTTP | requests | ✅ |
+| plain | HTTP | requests | ✅ |
+| plausible | HTTP | requests | ✅ |
+| polar | HTTP | requests | ✅ |
+| plaid | HTTP | requests | ✅ |
+| postgres | DB protocol | psycopg | ➖ |
+| postmark | HTTP | requests | ✅ |
+| productboard | HTTP | requests | ✅ |
+| pylon | HTTP | requests | ✅ |
+| recurly | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| ramp | HTTP | requests | ✅ |
+| recharge | HTTP | requests | ✅ |
+| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| redshift | DB protocol | psycopg (Postgres-compatible) | ➖ |
+| resend | HTTP | requests | ✅ |
+| revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
+| rippling | HTTP | requests | ✅ |
+| rollbar | HTTP | requests | ✅ |
+| rootly | HTTP | requests | ✅ |
+| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| salesloft | HTTP | requests | ✅ |
+| segment | HTTP | requests | ✅ |
+| sendgrid | HTTP | requests | ✅ |
+| sentry | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| servicenow | HTTP | requests | ✅ |
+| shipstation | HTTP | requests | ✅ |
+| shopify | HTTP | requests | ✅ |
+| shortcut | HTTP | requests | ✅ |
+| slack | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| smartsheet | HTTP | requests | ✅ |
+| snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| snowflake | DB protocol | snowflake-connector-python | ➖ |
+| sparkpost | HTTP | requests | ✅ |
+| square | HTTP | requests | ✅ |
+| squarespace | HTTP | requests | ✅ |
+| statuspage | HTTP | requests | ✅ |
+| stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
+| supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ |
+| surveymonkey | HTTP | requests | ✅ |
+| taboola | HTTP | requests | ✅ |
+| teamwork | HTTP | requests | ✅ |
+| temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |
+| thinkific | HTTP | requests | ✅ |
+| tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| tmdb | HTTP | requests | ✅ |
+| todoist | HTTP | requests | ✅ |
+| trello | HTTP | requests | ✅ |
+| twilio | HTTP | requests | ✅ |
+| typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| vercel | HTTP | requests | ✅ |
+| vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| webflow | HTTP | requests | ✅ |
+| woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| wordpress | HTTP | requests | ✅ |
+| workable | HTTP | requests | ✅ |
+| workos | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| wrike | HTTP | requests | ✅ |
+| zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| zendesk_sell | HTTP | requests | ✅ |
+| zoom | HTTP | requests | ✅ |
+| zuora | HTTP | requests | ✅ |
### Notes on partially-tracked sources
@@ -393,7 +394,6 @@ doesn't conflict with concurrent PRs.
- fauna
- feishu
- finage
-- financial_modelling
- finnhub
- firebase
- firebolt
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/canonical_descriptions.py
new file mode 100644
index 000000000000..eddc4998a4a7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/canonical_descriptions.py
@@ -0,0 +1,107 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Curated from the Financial Modeling Prep stable API docs. Keyed by the schema/endpoint name
+# returned by get_schemas. Any endpoint, column, or table description not covered here falls back to
+# LLM enrichment via the docs_url.
+_DOCS = "https://site.financialmodelingprep.com/developer/docs/stable"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "stock_list": {
+ "description": "Every tradable symbol Financial Modeling Prep tracks, with its exchange and name.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol uniquely identifying the security.",
+ "companyName": "Name of the company or fund behind the symbol.",
+ "exchange": "Exchange the symbol trades on.",
+ },
+ },
+ "company_profiles": {
+ "description": "Company profile: sector, industry, market cap, description, and contact details for each symbol.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol the profile describes.",
+ "companyName": "Registered company name.",
+ "industry": "Industry classification of the company.",
+ "sector": "Sector classification of the company.",
+ "marketCap": "Market capitalization in the reporting currency.",
+ "currency": "Currency the financial figures are reported in.",
+ "exchange": "Exchange the symbol trades on.",
+ },
+ },
+ "income_statements": {
+ "description": "Annual income statements (revenue, expenses, net income) per symbol and fiscal period.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol the statement belongs to.",
+ "date": "Fiscal-period end date the figures cover.",
+ "period": "Reporting period of the statement (annual).",
+ "revenue": "Total revenue for the period.",
+ "netIncome": "Net income for the period.",
+ "reportedCurrency": "Currency the statement is reported in.",
+ },
+ },
+ "balance_sheet_statements": {
+ "description": "Annual balance sheets (assets, liabilities, equity) per symbol and fiscal period.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol the statement belongs to.",
+ "date": "Fiscal-period end date the figures cover.",
+ "period": "Reporting period of the statement (annual).",
+ "totalAssets": "Total assets at the period end.",
+ "totalLiabilities": "Total liabilities at the period end.",
+ "totalEquity": "Total shareholder equity at the period end.",
+ "reportedCurrency": "Currency the statement is reported in.",
+ },
+ },
+ "cash_flow_statements": {
+ "description": "Annual cash flow statements (operating, investing, financing) per symbol and fiscal period.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol the statement belongs to.",
+ "date": "Fiscal-period end date the figures cover.",
+ "period": "Reporting period of the statement (annual).",
+ "operatingCashFlow": "Net cash generated by operating activities.",
+ "netCashUsedForInvestingActivites": "Net cash used in investing activities.",
+ "netChangeInCash": "Net change in cash and equivalents over the period.",
+ "reportedCurrency": "Currency the statement is reported in.",
+ },
+ },
+ "historical_prices": {
+ "description": "End-of-day OHLCV price history per symbol, filtered server-side by trading date.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol the price row belongs to.",
+ "date": "Trading date the prices apply to.",
+ "open": "Opening price for the trading day.",
+ "high": "Highest price during the trading day.",
+ "low": "Lowest price during the trading day.",
+ "close": "Closing price for the trading day.",
+ "volume": "Number of shares traded during the day.",
+ },
+ },
+ "earnings_calendar": {
+ "description": "Scheduled and historical earnings announcements across the market, filtered by date.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol reporting earnings.",
+ "date": "Date of the earnings announcement.",
+ "epsEstimated": "Consensus estimated earnings per share.",
+ "eps": "Actual reported earnings per share (when available).",
+ "revenueEstimated": "Consensus estimated revenue.",
+ "revenue": "Actual reported revenue (when available).",
+ },
+ },
+ "dividends_calendar": {
+ "description": "Dividend events across the market (ex-date, payment, amount), filtered by date.",
+ "docs_url": _DOCS,
+ "columns": {
+ "symbol": "Ticker symbol paying the dividend.",
+ "date": "Ex-dividend date.",
+ "dividend": "Dividend amount per share.",
+ "recordDate": "Date used to determine shareholders eligible for the dividend.",
+ "paymentDate": "Date the dividend is paid.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/financial_modelling.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/financial_modelling.py
new file mode 100644
index 000000000000..9c9aed65576c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/financial_modelling.py
@@ -0,0 +1,253 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.settings import (
+ FINANCIAL_MODELLING_BASE_URL,
+ FINANCIAL_MODELLING_ENDPOINTS,
+ FinancialModellingEndpointConfig,
+)
+
+# Free-tier keys are heavily rate-limited (~250 req/day) and return HTTP 429 once exceeded, so we
+# back off on 429 and transient 5xx and otherwise let `raise_for_status` surface the error.
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+
+
+class FinancialModellingRetryableError(Exception):
+ pass
+
+
+class FinancialModellingError(Exception):
+ """FMP returned a JSON error body (e.g. plan restriction) rather than a result array."""
+
+
+class FinancialModellingResumeConfig:
+ # Index into the configured symbol list of the next symbol to fetch. For market-wide endpoints
+ # (no fan-out) this stays 0. The symbol list is user-defined and stable across runs, so a stored
+ # index resumes into the same symbol.
+ symbol_index: int = 0
+
+
+def parse_symbols(raw: str | None) -> list[str]:
+ """Split a user-entered symbol list (comma/whitespace separated) into normalized tickers."""
+ if not raw:
+ return []
+ tokens = raw.replace("\n", ",").replace(" ", ",").split(",")
+ seen: set[str] = set()
+ symbols: list[str] = []
+ for token in tokens:
+ symbol = token.strip().upper()
+ if symbol and symbol not in seen:
+ seen.add(symbol)
+ symbols.append(symbol)
+ return symbols
+
+
+def _build_url(path: str, params: dict[str, Any], api_key: str) -> str:
+ query = urlencode({**params, "apikey": api_key})
+ return f"{FINANCIAL_MODELLING_BASE_URL}/{path}?{query}"
+
+
+@retry(
+ retry=retry_if_exception_type((FinancialModellingRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ params: dict[str, Any],
+ api_key: str,
+ logger: FilteringBoundLogger,
+) -> Any:
+ url = _build_url(path, params, api_key)
+ response = session.get(url, headers={"Accept": "application/json"}, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise FinancialModellingRetryableError(
+ f"Financial Modeling Prep API error (retryable): status={response.status_code}, path={path}"
+ )
+
+ if not response.ok:
+ logger.error(f"Financial Modeling Prep API error: status={response.status_code}, path={path}")
+ # `raise_for_status` would embed the full request URL — which carries the apikey — in the
+ # exception text, leaking the credential into stored error state. Re-raise with a sanitized
+ # URL that preserves the stable "<status> Client Error: <reason> for url: <base>/<path>" text
+ # get_non_retryable_errors matches on (this path only handles 4xx; 429/5xx are handled above).
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {response.reason} for url: {FINANCIAL_MODELLING_BASE_URL}/{path}",
+ response=response,
+ )
+
+ return response.json()
+
+
+def _extract_rows(data: Any, response_key: str | None) -> list[dict[str, Any]]:
+ """Normalize an FMP response into a list of row dicts.
+
+ Stable endpoints return a bare JSON array. Some historical-data endpoints instead wrap the array
+ under a key (e.g. {"symbol": ..., "historical": [...]}). Error responses are JSON objects carrying
+ an "Error Message" field.
+ """
+ if isinstance(data, list):
+ return data
+ if isinstance(data, dict):
+ if "Error Message" in data:
+ # FMP returns HTTP 200 with this body for plan restrictions and invalid keys, which a
+ # retry can't fix. The stable prefix lets get_non_retryable_errors match it so the schema
+ # is disabled with a friendly message instead of looping on every scheduled run.
+ raise FinancialModellingError(
+ f"Financial Modeling Prep API returned an error response: {data['Error Message']}"
+ )
+ if response_key and isinstance(data.get(response_key), list):
+ return data[response_key]
+ return [data]
+ return []
+
+
+def validate_credentials(api_key: str) -> bool:
+ # `profile` is a cheap, free-tier endpoint; a genuine key returns 200, a bad one returns 401.
+ url = _build_url("profile", {"symbol": "AAPL"}, api_key)
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ url, headers={"Accept": "application/json"}, timeout=10
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _to_date(value: Any) -> date | None:
+ if isinstance(value, datetime):
+ return value.date()
+ if isinstance(value, date):
+ return value
+ if isinstance(value, str) and value:
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()
+ except ValueError:
+ return None
+ return None
+
+
+def _window_params(
+ config: FinancialModellingEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, str]:
+ """Build the `from`/`to` server-side date filter for incremental endpoints."""
+ if not config.supports_date_window:
+ return {}
+
+ today = datetime.now(UTC).date()
+ from_date: date | None = None
+
+ if should_use_incremental_field and db_incremental_field_last_value:
+ from_date = _to_date(db_incremental_field_last_value)
+ # A future-dated cursor (bad source data) would otherwise build an empty/invalid window.
+ if from_date and from_date > today:
+ from_date = today
+ elif config.default_lookback_days:
+ from_date = today - timedelta(days=config.default_lookback_days)
+
+ if from_date is None:
+ return {}
+ return {"from": from_date.isoformat(), "to": today.isoformat()}
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ symbols: list[str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FinancialModellingResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[Any]:
+ config = FINANCIAL_MODELLING_ENDPOINTS[endpoint]
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ session = make_tracked_session(redact_values=(api_key,))
+ window = _window_params(config, should_use_incremental_field, db_incremental_field_last_value)
+
+ if config.fan_out_over_symbols:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_index = resume.symbol_index if resume is not None else 0
+ if start_index:
+ logger.debug(f"Financial Modeling Prep: resuming {endpoint} from symbol index {start_index}")
+
+ for offset, symbol in enumerate(symbols[start_index:]):
+ index = start_index + offset
+ params: dict[str, Any] = {"symbol": symbol, **config.extra_params, **window}
+ data = _fetch_page(session, config.path, params, api_key, logger)
+ for row in _extract_rows(data, config.response_key):
+ row.setdefault("symbol", symbol)
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ # Flush this symbol's rows before advancing the bookmark, so a crash re-fetches only from
+ # the next symbol (whose rows are not yet persisted) rather than dropping buffered rows.
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+ if index + 1 < len(symbols):
+ resumable_source_manager.save_state(FinancialModellingResumeConfig(symbol_index=index + 1))
+ return
+
+ params = {**config.extra_params, **window}
+ data = _fetch_page(session, config.path, params, api_key, logger)
+ for row in _extract_rows(data, config.response_key):
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def financial_modelling_source(
+ api_key: str,
+ endpoint: str,
+ symbols: list[str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FinancialModellingResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = FINANCIAL_MODELLING_ENDPOINTS[endpoint]
+ is_incremental = bool(config.incremental_fields)
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ symbols=symbols,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ # Rows arrive grouped per symbol (fan-out) and/or newest-first, never globally cursor-ascending,
+ # so use "desc": the pipeline commits the high watermark as the global max at run end instead of
+ # checkpointing per batch (which could skip a later symbol's older rows after an interruption).
+ sort_mode="desc" if is_incremental else "asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/settings.py
new file mode 100644
index 000000000000..df641def4927
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/settings.py
@@ -0,0 +1,131 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Financial Modeling Prep "stable" API host. The legacy `/api/v3/` paths still work, but every
+# endpoint here is expressed relative to the stable base. Auth is an `apikey` query param appended
+# to every request (see financial_modelling.py).
+FINANCIAL_MODELLING_BASE_URL = "https://financialmodelingprep.com/stable"
+
+
+@dataclass
+class FinancialModellingEndpointConfig:
+ name: str
+ # Path under FINANCIAL_MODELLING_BASE_URL (no leading slash).
+ path: str
+ primary_keys: list[str]
+ # When True, the endpoint is symbol-keyed: we issue one request per configured symbol and inject
+ # the symbol onto each row. When False, the endpoint is market-wide (a single request per sync).
+ fan_out_over_symbols: bool = False
+ # Stable field used to partition the Delta table. Must be a value that never changes for a row
+ # (a fiscal-period or trading `date`), never `updated_at`/`lastSeen`.
+ partition_key: Optional[str] = None
+ # Server-side incremental cursor options surfaced in the schema picker. Only populated for
+ # endpoints that honor a genuine `from`/`to` date filter.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # True only when the endpoint actually filters server-side on `from`/`to`. Drives incremental sync.
+ supports_date_window: bool = False
+ # Extra static query params (e.g. statement period).
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # Some endpoints historically wrapped their array under a key (e.g. {"symbol": ..., "historical": [...]}).
+ # When set, rows are read from data[response_key] if the response is an object rather than a bare array.
+ response_key: Optional[str] = None
+ # First incremental sync is bounded to the last N days so we don't pull unbounded history in one go.
+ default_lookback_days: Optional[int] = None
+ should_sync_default: bool = True
+
+
+def _date_incremental_fields() -> list[IncrementalField]:
+ return [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+ }
+ ]
+
+
+FINANCIAL_MODELLING_ENDPOINTS: dict[str, FinancialModellingEndpointConfig] = {
+ # Reference catalog of every tradable symbol FMP knows about. One bounded request, no symbol
+ # required. Full refresh — there is no server-side change cursor.
+ "stock_list": FinancialModellingEndpointConfig(
+ name="stock_list",
+ path="stock-list",
+ primary_keys=["symbol"],
+ ),
+ # Company profile (sector, industry, market cap, description, ...). One request per symbol.
+ # Full refresh — no updated_at cursor exposed by the API.
+ "company_profiles": FinancialModellingEndpointConfig(
+ name="company_profiles",
+ path="profile",
+ primary_keys=["symbol"],
+ fan_out_over_symbols=True,
+ ),
+ # Annual income statements per symbol. Full refresh; rows are keyed by the fiscal-period `date`.
+ "income_statements": FinancialModellingEndpointConfig(
+ name="income_statements",
+ path="income-statement",
+ primary_keys=["symbol", "date", "period"],
+ fan_out_over_symbols=True,
+ partition_key="date",
+ extra_params={"period": "annual"},
+ ),
+ "balance_sheet_statements": FinancialModellingEndpointConfig(
+ name="balance_sheet_statements",
+ path="balance-sheet-statement",
+ primary_keys=["symbol", "date", "period"],
+ fan_out_over_symbols=True,
+ partition_key="date",
+ extra_params={"period": "annual"},
+ ),
+ "cash_flow_statements": FinancialModellingEndpointConfig(
+ name="cash_flow_statements",
+ path="cash-flow-statement",
+ primary_keys=["symbol", "date", "period"],
+ fan_out_over_symbols=True,
+ partition_key="date",
+ extra_params={"period": "annual"},
+ ),
+ # End-of-day OHLCV history per symbol. Honors `from`/`to`, so this is the one symbol-keyed
+ # endpoint we sync incrementally on the trading `date`.
+ "historical_prices": FinancialModellingEndpointConfig(
+ name="historical_prices",
+ path="historical-price-full",
+ primary_keys=["symbol", "date"],
+ fan_out_over_symbols=True,
+ partition_key="date",
+ incremental_fields=_date_incremental_fields(),
+ supports_date_window=True,
+ # Stable bare-array responses need no unwrapping; the legacy shape nests under "historical".
+ response_key="historical",
+ default_lookback_days=365 * 5,
+ ),
+ # Market-wide earnings calendar. Honors `from`/`to`; incremental on the event `date`.
+ "earnings_calendar": FinancialModellingEndpointConfig(
+ name="earnings_calendar",
+ path="earnings-calendar",
+ primary_keys=["symbol", "date"],
+ partition_key="date",
+ incremental_fields=_date_incremental_fields(),
+ supports_date_window=True,
+ default_lookback_days=365 * 2,
+ ),
+ # Market-wide dividends calendar. Honors `from`/`to`; incremental on the ex-dividend `date`.
+ "dividends_calendar": FinancialModellingEndpointConfig(
+ name="dividends_calendar",
+ path="dividends-calendar",
+ primary_keys=["symbol", "date"],
+ partition_key="date",
+ incremental_fields=_date_incremental_fields(),
+ supports_date_window=True,
+ default_lookback_days=365 * 2,
+ ),
+}
+
+ENDPOINTS = tuple(FINANCIAL_MODELLING_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in FINANCIAL_MODELLING_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/source.py
index 0a79af7f9f01..0c92da0207a0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/source.py
@@ -1,13 +1,35 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.financial_modelling import (
+ FinancialModellingResumeConfig,
+ financial_modelling_source,
+ parse_symbols,
+ validate_credentials as validate_financial_modelling_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.settings import (
+ ENDPOINTS,
+ FINANCIAL_MODELLING_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (
FinancialModellingSourceConfig,
)
@@ -15,7 +37,9 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class FinancialModellingSource(SimpleSource[FinancialModellingSourceConfig]):
+class FinancialModellingSource(ResumableSource[FinancialModellingSourceConfig, FinancialModellingResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FINANCIALMODELLING
@@ -25,8 +49,104 @@ class FinancialModellingSource(SimpleSource[FinancialModellingSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.FINANCIAL_MODELLING,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
- label="Financial Modelling",
- iconPath="/static/services/financial_modelling.png",
- fields=cast(list[FieldType], []),
+ label="Financial Modeling Prep",
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Financial Modeling Prep API key to pull market and company financial data into the PostHog Data warehouse.
+
+You can find your API key in your [Financial Modeling Prep dashboard](https://site.financialmodelingprep.com/developer/docs/dashboard).
+
+The symbol-keyed tables (company profiles, financial statements, historical prices) are fetched once per ticker you list below, so keep the list focused — free-tier keys are heavily rate-limited.""",
+ iconPath="/static/services/financial_modelling.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/financial-modelling",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="symbols",
+ label="Symbols",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="AAPL, MSFT, GOOGL",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://financialmodelingprep.com": "Your Financial Modeling Prep API key is invalid or has been revoked. Generate a new key in your Financial Modeling Prep dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://financialmodelingprep.com": "Your Financial Modeling Prep plan does not grant access to this data. Upgrade your plan or deselect the affected tables, then reconnect.",
+ "Financial Modeling Prep API returned an error response": "Financial Modeling Prep returned an error for this table — usually because your plan does not include this data or your API key is invalid. Upgrade your plan or deselect the affected tables, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: FinancialModellingSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = FINANCIAL_MODELLING_ENDPOINTS[endpoint]
+ has_incremental = endpoint_config.supports_date_window and bool(endpoint_config.incremental_fields)
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ supports_append=has_incremental,
+ incremental_fields=endpoint_config.incremental_fields,
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: FinancialModellingSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_financial_modelling_credentials(config.api_key):
+ return True, None
+ return False, "Invalid Financial Modeling Prep API key"
+
+ def get_resumable_source_manager(
+ self, inputs: SourceInputs
+ ) -> ResumableSourceManager[FinancialModellingResumeConfig]:
+ return ResumableSourceManager[FinancialModellingResumeConfig](inputs, FinancialModellingResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FinancialModellingSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FinancialModellingResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return financial_modelling_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ symbols=parse_symbols(config.symbols),
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling.py
new file mode 100644
index 000000000000..d7573562e425
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling.py
@@ -0,0 +1,295 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling import financial_modelling
+from products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.financial_modelling import (
+ FinancialModellingError,
+ FinancialModellingResumeConfig,
+ _build_url,
+ _extract_rows,
+ _fetch_page,
+ _to_date,
+ _window_params,
+ financial_modelling_source,
+ get_rows,
+ parse_symbols,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.settings import (
+ FINANCIAL_MODELLING_ENDPOINTS,
+)
+
+
+class TestParseSymbols:
+ @parameterized.expand(
+ [
+ ("comma", "AAPL,MSFT,GOOGL", ["AAPL", "MSFT", "GOOGL"]),
+ ("comma_space", "AAPL, MSFT, GOOGL", ["AAPL", "MSFT", "GOOGL"]),
+ ("lowercase_uppercased", "aapl,msft", ["AAPL", "MSFT"]),
+ ("newline_and_space", "AAPL\nMSFT GOOGL", ["AAPL", "MSFT", "GOOGL"]),
+ ("dedupes_preserving_order", "AAPL,MSFT,AAPL", ["AAPL", "MSFT"]),
+ ("strips_whitespace", " AAPL , MSFT ", ["AAPL", "MSFT"]),
+ ("empty", "", []),
+ ("none", None, []),
+ ]
+ )
+ def test_parse_symbols(self, _name: str, raw: str | None, expected: list[str]) -> None:
+ assert parse_symbols(raw) == expected
+
+
+class TestBuildUrl:
+ def test_appends_apikey_and_params(self) -> None:
+ url = _build_url("profile", {"symbol": "AAPL"}, "secret_key")
+ assert url.startswith("https://financialmodelingprep.com/stable/profile?")
+ assert "symbol=AAPL" in url
+ assert "apikey=secret_key" in url
+
+ def test_url_encodes_param_values(self) -> None:
+ url = _build_url("earnings-calendar", {"from": "2024-01-01", "to": "2024-12-31"}, "k")
+ assert "from=2024-01-01" in url
+ assert "to=2024-12-31" in url
+
+
+class TestFetchPage:
+ def test_client_error_does_not_leak_api_key(self) -> None:
+ response = MagicMock()
+ response.status_code = 401
+ response.ok = False
+ response.reason = "Unauthorized"
+
+ session = MagicMock()
+ session.get.return_value = response
+
+ with pytest.raises(requests.HTTPError) as exc_info:
+ _fetch_page(session, "profile", {"symbol": "AAPL"}, "super_secret_key", MagicMock())
+
+ message = str(exc_info.value)
+ assert "super_secret_key" not in message
+ # Still carries the stable text get_non_retryable_errors matches on.
+ assert message.startswith("401 Client Error: Unauthorized for url: https://financialmodelingprep.com")
+
+
+class TestExtractRows:
+ def test_bare_array_returned_as_is(self) -> None:
+ assert _extract_rows([{"a": 1}, {"a": 2}], None) == [{"a": 1}, {"a": 2}]
+
+ def test_wrapped_array_read_from_response_key(self) -> None:
+ data = {"symbol": "AAPL", "historical": [{"date": "2024-01-01"}]}
+ assert _extract_rows(data, "historical") == [{"date": "2024-01-01"}]
+
+ def test_single_object_is_wrapped(self) -> None:
+ assert _extract_rows({"symbol": "AAPL", "price": 1}, None) == [{"symbol": "AAPL", "price": 1}]
+
+ def test_error_body_raises(self) -> None:
+ with pytest.raises(FinancialModellingError):
+ _extract_rows({"Error Message": "Invalid API KEY"}, None)
+
+ def test_error_body_message_is_non_retryable_matchable(self) -> None:
+ # The raised message must carry the stable prefix get_non_retryable_errors keys on, otherwise
+ # plan-restriction bodies loop forever instead of disabling the schema.
+ with pytest.raises(FinancialModellingError) as exc_info:
+ _extract_rows({"Error Message": "Exclusive Endpoint"}, None)
+ assert str(exc_info.value).startswith("Financial Modeling Prep API returned an error response")
+
+ def test_unexpected_type_returns_empty(self) -> None:
+ assert _extract_rows(None, None) == []
+
+
+class TestToDate:
+ @parameterized.expand(
+ [
+ ("datetime", datetime(2024, 5, 1, 10, 30, tzinfo=UTC), date(2024, 5, 1)),
+ ("date", date(2024, 5, 1), date(2024, 5, 1)),
+ ("iso_string", "2024-05-01", date(2024, 5, 1)),
+ ("z_string", "2024-05-01T00:00:00Z", date(2024, 5, 1)),
+ ("bad_string", "not-a-date", None),
+ ("none", None, None),
+ ]
+ )
+ def test_to_date(self, _name: str, value: Any, expected: date | None) -> None:
+ assert _to_date(value) == expected
+
+
+@freeze_time("2024-06-15")
+class TestWindowParams:
+ def test_non_windowed_endpoint_returns_empty(self) -> None:
+ config = FINANCIAL_MODELLING_ENDPOINTS["company_profiles"]
+ assert (
+ _window_params(config, should_use_incremental_field=True, db_incremental_field_last_value="2024-01-01")
+ == {}
+ )
+
+ def test_incremental_uses_last_value_as_from(self) -> None:
+ config = FINANCIAL_MODELLING_ENDPOINTS["historical_prices"]
+ params = _window_params(config, should_use_incremental_field=True, db_incremental_field_last_value="2024-05-01")
+ assert params == {"from": "2024-05-01", "to": "2024-06-15"}
+
+ def test_future_cursor_is_clamped_to_today(self) -> None:
+ config = FINANCIAL_MODELLING_ENDPOINTS["historical_prices"]
+ params = _window_params(config, should_use_incremental_field=True, db_incremental_field_last_value="2030-01-01")
+ assert params == {"from": "2024-06-15", "to": "2024-06-15"}
+
+ def test_first_sync_falls_back_to_lookback(self) -> None:
+ config = FINANCIAL_MODELLING_ENDPOINTS["earnings_calendar"]
+ params = _window_params(config, should_use_incremental_field=True, db_incremental_field_last_value=None)
+ # default_lookback_days = 365 * 2 -> two years before the frozen "today"
+ assert params["to"] == "2024-06-15"
+ assert params["from"] == "2022-06-16"
+
+
+class _FakeResumableManager:
+ def __init__(self, state: FinancialModellingResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[FinancialModellingResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> FinancialModellingResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: FinancialModellingResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(
+ endpoint: str, symbols: list[str], manager: _FakeResumableManager, monkeypatch: Any, by_symbol: dict[str, Any]
+) -> list[dict]:
+ def fake_fetch(session: Any, path: str, params: dict[str, Any], api_key: str, logger: Any) -> Any:
+ key = params.get("symbol", path)
+ return by_symbol[key]
+
+ monkeypatch.setattr(financial_modelling, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for table in get_rows(
+ api_key="k",
+ endpoint=endpoint,
+ symbols=symbols,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(table.to_pylist())
+ return rows
+
+
+class TestGetRowsFanOut:
+ def test_fans_out_over_each_symbol_and_injects_symbol(self, monkeypatch: Any) -> None:
+ by_symbol = {
+ "AAPL": [{"symbol": "AAPL", "companyName": "Apple"}],
+ "MSFT": [{"symbol": "MSFT", "companyName": "Microsoft"}],
+ }
+ rows = _collect("company_profiles", ["AAPL", "MSFT"], _FakeResumableManager(), monkeypatch, by_symbol)
+ assert {r["symbol"] for r in rows} == {"AAPL", "MSFT"}
+
+ def test_symbol_injected_when_missing_from_row(self, monkeypatch: Any) -> None:
+ # historical_prices rows arrive without a symbol; the fan-out injects it.
+ by_symbol = {"AAPL": {"symbol": "AAPL", "historical": [{"date": "2024-01-02", "close": 10}]}}
+ rows = _collect("historical_prices", ["AAPL"], _FakeResumableManager(), monkeypatch, by_symbol)
+ assert rows == [{"date": "2024-01-02", "close": 10, "symbol": "AAPL"}]
+
+ def test_saves_resume_state_advancing_per_symbol(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ by_symbol = {
+ "AAPL": [{"symbol": "AAPL"}],
+ "MSFT": [{"symbol": "MSFT"}],
+ "GOOGL": [{"symbol": "GOOGL"}],
+ }
+ _collect("company_profiles", ["AAPL", "MSFT", "GOOGL"], manager, monkeypatch, by_symbol)
+ # State is saved after every symbol except the last (no point bookmarking past the end).
+ assert [s.symbol_index for s in manager.saved] == [1, 2]
+
+ def test_resumes_from_saved_symbol_index(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(FinancialModellingResumeConfig(symbol_index=1))
+ fetched: list[str] = []
+
+ def fake_fetch(session: Any, path: str, params: dict[str, Any], api_key: str, logger: Any) -> Any:
+ fetched.append(params["symbol"])
+ return [{"symbol": params["symbol"]}]
+
+ monkeypatch.setattr(financial_modelling, "_fetch_page", fake_fetch)
+ list(
+ get_rows(
+ api_key="k",
+ endpoint="company_profiles",
+ symbols=["AAPL", "MSFT", "GOOGL"],
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+ # AAPL (index 0) is skipped because the bookmark resumes at index 1.
+ assert fetched == ["MSFT", "GOOGL"]
+
+
+class TestGetRowsMarketWide:
+ def test_single_request_no_symbol(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ by_path = {"earnings-calendar": [{"symbol": "AAPL", "date": "2024-01-01"}]}
+ rows = _collect("earnings_calendar", [], manager, monkeypatch, by_path)
+ assert rows == [{"symbol": "AAPL", "date": "2024-01-01"}]
+ # Market-wide endpoints fan out over nothing, so no resume bookmark is saved.
+ assert manager.saved == []
+
+
+class TestFinancialModellingSourceResponse:
+ @parameterized.expand(
+ [
+ ("incremental_uses_desc", "historical_prices", "desc"),
+ ("full_refresh_uses_asc", "company_profiles", "asc"),
+ ]
+ )
+ def test_sort_mode(self, _name: str, endpoint: str, expected: str) -> None:
+ response = financial_modelling_source(
+ api_key="k",
+ endpoint=endpoint,
+ symbols=["AAPL"],
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.sort_mode == expected
+
+ @parameterized.expand(
+ [
+ ("stock_list", ["symbol"]),
+ ("income_statements", ["symbol", "date", "period"]),
+ ("historical_prices", ["symbol", "date"]),
+ ("earnings_calendar", ["symbol", "date"]),
+ ]
+ )
+ def test_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:
+ response = financial_modelling_source(
+ api_key="k",
+ endpoint=endpoint,
+ symbols=["AAPL"],
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.primary_keys == expected_keys
+
+ def test_partitioned_endpoint_has_datetime_partitioning(self) -> None:
+ response = financial_modelling_source(
+ api_key="k",
+ endpoint="historical_prices",
+ symbols=["AAPL"],
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["date"]
+
+ def test_unpartitioned_endpoint_has_no_partitioning(self) -> None:
+ response = financial_modelling_source(
+ api_key="k",
+ endpoint="company_profiles",
+ symbols=["AAPL"],
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling_source.py
new file mode 100644
index 000000000000..21d19ba7f4c8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/financial_modelling/tests/test_financial_modelling_source.py
@@ -0,0 +1,206 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.financial_modelling import (
+ FinancialModellingResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.source import (
+ FinancialModellingSource,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _inputs(schema_name: str, **overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": schema_name,
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestFinancialModellingSourceConfig:
+ def test_source_type(self) -> None:
+ assert FinancialModellingSource().source_type == ExternalDataSourceType.FINANCIALMODELLING
+
+ def test_source_config_basics(self) -> None:
+ config = FinancialModellingSource().get_source_config
+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/financial-modelling"
+
+ def test_fields(self) -> None:
+ fields = {f.name: f for f in FinancialModellingSource().get_source_config.fields}
+ assert set(fields) == {"api_key", "symbols"}
+ api_key, symbols = fields["api_key"], fields["symbols"]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert isinstance(symbols, SourceFieldInputConfig)
+ assert api_key.required is True
+ assert api_key.secret is True
+ assert symbols.required is True
+ assert symbols.secret is False
+
+
+class TestGetSchemas:
+ def test_all_endpoints_present(self) -> None:
+ schemas = FinancialModellingSource().get_schemas(MagicMock(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("stock_list", False),
+ ("company_profiles", False),
+ ("income_statements", False),
+ ("historical_prices", True),
+ ("earnings_calendar", True),
+ ("dividends_calendar", True),
+ ]
+ )
+ def test_incremental_support_matches_date_window(self, endpoint: str, expected_incremental: bool) -> None:
+ schemas = {s.name: s for s in FinancialModellingSource().get_schemas(MagicMock(), team_id=1)}
+ assert schemas[endpoint].supports_incremental is expected_incremental
+ # supports_append tracks incremental here (date-windowed endpoints can append).
+ assert schemas[endpoint].supports_append is expected_incremental
+
+ def test_names_filter(self) -> None:
+ schemas = FinancialModellingSource().get_schemas(MagicMock(), team_id=1, names=["historical_prices"])
+ assert [s.name for s in schemas] == ["historical_prices"]
+
+
+class TestValidateCredentials:
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.source.validate_financial_modelling_credentials"
+ )
+ def test_valid(self, mock_validate: MagicMock) -> None:
+ mock_validate.return_value = True
+ config = FinancialModellingSource().parse_config({"api_key": "k", "symbols": "AAPL"})
+ ok, error = FinancialModellingSource().validate_credentials(config, team_id=1)
+ assert ok is True
+ assert error is None
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.source.validate_financial_modelling_credentials"
+ )
+ def test_invalid(self, mock_validate: MagicMock) -> None:
+ mock_validate.return_value = False
+ config = FinancialModellingSource().parse_config({"api_key": "bad", "symbols": "AAPL"})
+ ok, error = FinancialModellingSource().validate_credentials(config, team_id=1)
+ assert ok is False
+ assert error is not None
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://financialmodelingprep.com/stable/profile?symbol=AAPL",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://financialmodelingprep.com/stable/income-statement?symbol=AAPL",
+ ),
+ (
+ "error_body",
+ "Financial Modeling Prep API returned an error response: Exclusive Endpoint: This endpoint is only for premium subscribers.",
+ ),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = FinancialModellingSource().get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://financialmodelingprep.com/stable/profile",
+ ),
+ (
+ "rate_limited",
+ "429 Client Error: Too Many Requests for url: https://financialmodelingprep.com/stable/profile",
+ ),
+ ("timeout", "Read timed out."),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ non_retryable = FinancialModellingSource().get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable)
+
+
+class TestResumableSourceManager:
+ def test_returns_manager_bound_to_resume_config(self) -> None:
+ manager = FinancialModellingSource().get_resumable_source_manager(_inputs("historical_prices"))
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FinancialModellingResumeConfig
+
+
+class TestSourceForPipeline:
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.source.financial_modelling_source"
+ )
+ def test_parses_symbols_and_plumbs_arguments(self, mock_source: MagicMock) -> None:
+ config = FinancialModellingSource().parse_config({"api_key": "k", "symbols": "aapl, msft"})
+ FinancialModellingSource().source_for_pipeline(config, MagicMock(), _inputs("company_profiles"))
+ _, kwargs = mock_source.call_args
+ assert kwargs["api_key"] == "k"
+ assert kwargs["symbols"] == ["AAPL", "MSFT"]
+ assert kwargs["endpoint"] == "company_profiles"
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.financial_modelling.source.financial_modelling_source"
+ )
+ def test_last_value_passed_only_when_incremental(self, mock_source: MagicMock) -> None:
+ config = FinancialModellingSource().parse_config({"api_key": "k", "symbols": "AAPL"})
+
+ FinancialModellingSource().source_for_pipeline(
+ config,
+ MagicMock(),
+ _inputs(
+ "historical_prices", should_use_incremental_field=True, db_incremental_field_last_value="2024-01-01"
+ ),
+ )
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] == "2024-01-01"
+
+ FinancialModellingSource().source_for_pipeline(
+ config,
+ MagicMock(),
+ _inputs(
+ "historical_prices", should_use_incremental_field=False, db_incremental_field_last_value="2024-01-01"
+ ),
+ )
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+
+class TestPublicDocs:
+ def test_lists_tables_without_credentials(self) -> None:
+ assert FinancialModellingSource().lists_tables_without_credentials is True
+
+ def test_documented_tables_cover_every_endpoint(self) -> None:
+ tables = {t["name"] for t in FinancialModellingSource().get_documented_tables()}
+ assert tables == set(ENDPOINTS)
+
+ def test_canonical_descriptions_keys_are_valid_endpoints(self) -> None:
+ assert set(CANONICAL_DESCRIPTIONS).issubset(set(ENDPOINTS))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index dc13ef78ae76..e145fafb656a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1128,7 +1128,8 @@ class FinageSourceConfig(config.Config):
@config.config
class FinancialModellingSourceConfig(config.Config):
- pass
+ api_key: str
+ symbols: str
@config.config