Hermes docs18 sections▾
Getting Started
Requirements
- Python >= 3.11
- uv for dependency management
API Keys
| Service | Key | Purpose |
|---|---|---|
| OpenSanctions | opensanction_api |
Sanctions lists (OFAC, EU, UK, UN) |
| FRED | fred_api |
23 US economic series |
| Finnhub | finnhub_api |
Stock fundamentals, candles, profiles |
| SEC EDGAR | sec_username + sec_email |
Company facts via XBRL (free, register at EDGAR) |
| NewsData | new_data_api |
News ingestion (wired, no connector yet) |
Installation
# uv (recommended)
uv add hermes-plt
# pip
pip install hermes-plt
Quick Start
import asyncio
from hermes import Hermes
async def main():
hr = Hermes(
opensanction_api="your-key",
new_data_api="",
fred_api="your-key",
sec_username="your-username",
sec_email="you@example.com",
finnhub_api="your-key",
)
# Country risk snapshot
risk = await hr.country_features.get_country_risk_features("USA")
print(risk["economic"]["gdp_growth_yoy"])
# List all supported countries
print(len(hr.list_countries)) # ~250
# Direct connector usage
df = await hr.world_bank.fetch("NY.GDP.MKTP.KD.ZG", "USA", 2010, 2024)
print(df.head())
asyncio.run(main())
What to Read Next
- Connectors — fetch raw data from each source
- Features — 58 country risk features + analysis models
- Cache — TTL-based Parquet caching system
Hermes SDK
File: hermes/__init__.py
What It Does
The Hermes class is the single entry point to the entire platform. It composes every connector, the feature pipeline, and the analysis models into one object — all functionality is reachable through one import:
from hermes import Hermes
Constructor
Hermes(
opensanction_api: str, # OpenSanctions API key
new_data_api: str, # NewsData API key (wired, no connector yet)
fred_api: str, # FRED API key
sec_username: str, # SEC EDGAR username (for User-Agent)
sec_email: str, # SEC EDGAR email
finnhub_api: str, # Finnhub API key
cache_dir: str | None = None,# Custom cache dir (default: ~/.hermes_cache)
use_cache: bool = True, # Enable/disable caching
)
Data Source Connectors
| Attribute | Class | Source | What It Fetches |
|---|---|---|---|
.world_bank |
World_bank |
World Bank v2 API | GDP, inflation, unemployment, governance, debt — 20+ indicators |
.imf |
IMF |
IMF SDMX 3.0 | IFS, WEO, GFS dataflows — PPI, CPI, fiscal balance, REER |
.gdelt |
GDELT |
GDELT Doc API + exports | Conflict, protest, diplomacy events — Goldstein scale, battle deaths |
.opensanction |
OpenSanction |
OpenSanctions API | Sanctions lists (OFAC, EU, UK, UN) |
.fred |
FRED |
FRED (Federal Reserve) | 23 US economic series — GDP, CPI, Fed Funds, VIX, yield curve |
.binance |
Binance |
Binance API | Spot + futures OHLCV, order book, funding rate, open interest |
.finnhub |
FINNHUB |
Finnhub API | 12 endpoints: candles, quote, profile, metrics, peers, earnings, EPS |
.sec_edger |
SECEDGAR |
SEC EDGAR XBRL | Company facts — income, balance sheet, cash flow via XBRL |
.yfin |
Yfinance |
Yahoo Finance | EPS estimate, revenue estimate, earnings history |
.datasets |
PUBLIC_DATASET |
Bundled CSVs | 8 datasets: HRS, HDI, CPI, FSI, NATO, CRS, CVS, SIPRI |
Analysis Models
| Attribute | Class | What It Provides |
|---|---|---|
.country_features |
pipeline |
get_country_risk_features() and build_training_panel() — 58 country risk features |
.ta_feature |
TAfeatures |
Technical analysis — 86-field TechnicalSnapshot from Binance data |
.fa_features |
FAfeatures |
Fundamental analysis — 71-field CompanyFundamental from Finnhub/SEC/FRED/YF |
Feature Registry
| Attribute | Description |
|---|---|
.lf |
Feature groups: .eco (economic), .geo (geopolitical), .sec (security), .soc (social), .env (environmental) |
.list_countries |
All ~250 supported ISO3 country codes |
.list_features |
All ~58 feature functions (decorated with @feature) |
Methods
| Method | Returns | Description |
|---|---|---|
.clear_cache(older_than) |
None |
Evict cache entries older than a timedelta (supports h/d/w units) |
.cache_stats() |
dict |
Files, per-source hit/miss counts, and hit rates |
Example
from hermes import Hermes
hr = Hermes(
opensanction_api="your-key",
new_data_api="",
fred_api="your-key",
sec_username="your-username",
sec_email="you@example.com",
finnhub_api="your-key",
)
# Country risk snapshot (dashboard mode)
risk = await hr.country_features.get_country_risk_features("USA")
risk["economic"]["gdp_growth_yoy"]
# Country risk panel (ML mode)
panel = await hr.country_features.build_training_panel(
fns=hr.list_features[:5],
countries=["USA", "GBR", "DEU"],
)
# Technical snapshot
ta = await hr.ta_feature.get_technical("BTCUSDT")
ta.trend_score
# Fundamental snapshot
fa = await hr.fa_features.get_fundamentels("AAPL")
fa.pe_ratio
# Direct connector usage
df = await hr.world_bank.fetch("NY.GDP.MKTP.KD.ZG", "USA", 2010, 2024)
df = await hr.fred.fetch(["DFF", "UNRATE", "CPIAUCSL"])Schemas
Connector Output (Standard)
All connectors (except GDELT) return a pd.DataFrame with a consistent shape:
| Column | Type | Description |
|---|---|---|
date |
datetime | Observation date |
indicator_id |
str | Indicator code (e.g. NY.GDP.MKTP.KD.ZG) |
country |
str | ISO2 or ISO3 country code |
value |
float | Numeric value |
source |
str | Data source identifier |
GDELT Event Schema
| Column | Type | Description |
|---|---|---|
event_id |
str | GDELT event identifier |
date |
datetime | Event date |
country_iso3 |
str | ISO3 country code (FIPS-normalized) |
event_type |
str | CONFLICT, PROTEST, DIPLOMACY, or SANCTIONS |
severity |
float | Event severity score |
lat |
float | Latitude |
lon |
float | Longitude |
source |
str | Always "gdelt" |
Feature Output (Dual-Mode)
Every feature function returns different shapes depending on mode:
"F" mode (dashboard): A single scalar — float, int, str, or bool.
await hr.lf.eco.gdp_growth_yoy("USA", mode="F") # 2.3
await hr.lf.geo.regime_type("USA", mode="F") # "presidential"
"ML" mode (training): A monthly pd.Series with DatetimeIndex, resampled and interpolated.
await hr.lf.eco.gdp_growth_yoy("USA", mode="ML")
# 2020-01-01 2.1
# 2020-02-01 2.0
# ...
Missing data returns np.nan ("F") or an empty pd.Series ("ML") — never raises.
Risk Snapshot Schema
Output of get_country_risk_features(country):
{
"country": "USA",
"economic": {
"gdp_growth_yoy": 2.3,
"inflation_cpi_yoy": 3.1,
"unemployment_rate": 3.7,
# ... 18 features
},
"geopolitical": {
"conflict_event_count_30d": 12,
"sanctions_count_active": 847,
"governance_wgi_composite": 1.2,
# ... 21 features
},
"security": {
"military_spending_gdp": 3.5,
"nato_member": True,
# ... 7 features
},
"social": {
"human_development_index": 0.921,
"fragile_state_index": 24.5,
# ... 6 features
},
"environmental": {
"climate_vulnerability_score": 0.35,
"water_stress_index": 4.2,
# ... 6 features
},
"metadata": {
"last_updated": "2025-01-15T10:30:00Z",
"features_version": "1.0.0"
}
}
Training Panel Schema
Output of build_training_panel(fns, countries):
A pd.DataFrame with a MultiIndex(country_iso3, date), one column per feature function. Handles deduplication and concatenation across countries.
TechnicalSnapshot
86-field dataclass for crypto technical analysis (hr.ta_feature.get_technical(symbol)):
| Category | Fields |
|---|---|
| Price | OHLCV, returns (1/5/10/60-bar), range metrics |
| Moving averages | SMA 20/50/200 distance, EMA 9/21/50 differences |
| Volatility | 20/60-bar vol, ATR-14 normalized |
| Volume | relative volume 20-bar, taker buy ratio |
| Trades | count, buy ratio, avg/median trade size, large trade ratio |
| Order book | bid/ask price/qty, spread (abs/bps), imbalance, depth |
| 24h metrics | high/low/last, range, pct change, position in range, volume |
| Funding | rate, lag-3, change, z-score, time to next funding |
| Open interest | current, 1h/24h changes, OI-to-volume ratio |
| Composites | trend score, mean reversion score, liquidity score, order flow score, sentiment score |
CompanyFundamental
71-field dataclass for stock fundamental analysis (hr.fa_features.get_fundamentels(ticker)):
| Category | Fields |
|---|---|
| Filing | ticker, date, period, year, type |
| Income | revenue through net income, EPS basic/diluted |
| Balance sheet | cash, receivables, inventory, assets, liabilities, equity, debt |
| Cash flows | operating/investing/financing, capex |
| Market | shares outstanding, current price, market cap |
| Estimates | EPS, revenue, earnings/revenue surprise |
| Macro | GDP, GDP growth, inflation, interest rates, unemployment, government debt, FX rates |
| Valuation | P/E, P/S, P/B, EV/EBITDA, ROE, ROA, D/E |
Features
Country Risk Features
Files: features/country_risk_features/
58 features across 5 groups, each decorated with @feature and registered in a lineage graph.
Feature Groups
| Group | Count | Key Sources |
|---|---|---|
| Economic | 18 | World Bank, IMF |
| Geopolitical | 21 | GDELT, OpenSanctions, World Bank, bundled datasets |
| Security | 7 | SIPRI, NATO |
| Social | 6 | HRS, FSI, HDI, World Bank |
| Environmental | 6 | NDGAIN, World Bank |
Dual-Mode Interface
Every feature function follows this signature:
async def feature_name(country_code: str, mode: Literal["F", "ML"]) -> float | pd.Series
| Mode | Returns | Use Case |
|---|---|---|
"F" |
Scalar (float, int, str, bool) | Dashboards — latest value |
"ML" |
Monthly pd.Series with DatetimeIndex |
ML training — time-series panel |
Missing data returns np.nan ("F") or empty pd.Series ("ML") — never raises.
Snapshot
risk = await hr.country_features.get_country_risk_features("USA")
# {"country": "USA", "economic": {...}, "geopolitical": {...}, ...}
Training Panel
panel = await hr.country_features.build_training_panel(
fns=hr.list_features[:5],
countries=["USA", "GBR", "DEU"],
)
# pd.DataFrame with MultiIndex(country_iso3, date)
Feature Decorator
Features are registered via @feature(name, group, deps, compute) in core/feature_decorator.py. The LineageGraph singleton tracks dependencies and resolves execution order via topological sort into tiers (TieredPlan).
Technical Analysis
File: features/analysis/technical.py
TAfeatures computes an 86-field TechnicalSnapshot from Binance data:
ta = await hr.ta_feature.get_technical("BTCUSDT")
ta.trend_score # composite trend score
ta.rsi_14 # RSI(14)
ta.bid_ask_spread # order book spread in bps
See Technical Features for the full field list.
Fundamental Analysis
File: features/analysis/fundamental.py
FAfeatures computes a 71-field CompanyFundamental from Finnhub, SEC EDGAR, FRED, and Yahoo Finance:
fa = await hr.fa_features.get_fundamentels("AAPL")
fa.pe_ratio # P/E ratio
fa.revenue # latest revenue
fa.gdp_growth # macro context
See Fundamental Features for the full field list.
Cache
File: core/cache.py
How It Works
Every fetch goes through RawCache.get_or_fetch(). Data is stored as Parquet files with a sidecar .meta.json under ~/.hermes_cache/raw/<source>/<hash>.parquet.
Keying: SHA-256 of "{source}:{json(params, sort_keys=True)}", truncated to 16 hex chars.
Flow: Check cache → if miss or expired, call async fetch → store result → return DataFrame.
Per-Source TTLs
| Source | TTL |
|---|---|
| GDELT | 6 hours |
| World Bank | 7 days |
| IMF | 7 days |
| SEC EDGAR | 7 days |
| Finnhub | 7 days |
| OpenSanctions | 30 days |
| FRED | 30 days (per code) |
| Binance | 1 day |
| Yahoo Finance | 1 day |
| Public Datasets | static (no cache) |
API
| Method | Description |
|---|---|
get(source, params, ttl) |
Read cached DataFrame; raises CacheMiss on miss/expiry |
put(source, params, df) |
Write DataFrame to Parquet with metadata |
get_or_fetch(source, params, fetch_fn, force, ttl) |
Try cache first (skip if force=True), fall back to fetch_fn |
clear(older_than) |
Evict entries older than a timedelta (supports h/d/w units) |
stats() |
File counts by source, hit/miss counts, hit rates |
Usage
# Force a fresh fetch (bypass cache)
df = await hr.world_bank.fetch("NY.GDP.MKTP.KD.ZG", "USA", 2010, 2024, force=True)
# Check cache health
stats = hr.cache_stats()
# {"files": {"world_bank": 42, "fred": 18, ...}, "hits": {...}, "misses": {...}}
# Evict old entries
hr.clear_cache(older_than="7d")Data Export
File: hermes/core/export.py
What It Does
The export() helper writes any pandas.DataFrame or pandas.Series to disk as CSV, JSON, or Parquet. It creates the target directory if it doesn’t exist.
Signature
export(
data: pd.DataFrame | pd.Series,
filetype: str = "csv",
loc: Path | str = "data/",
name: str | None = None,
)
| Argument | Default | Description |
|---|---|---|
data |
— | The DataFrame or Series to export. |
filetype |
"csv" |
One of "csv", "json", "parquet". |
loc |
"data/" |
Target directory. |
name |
None |
Output filename (without extension). Defaults to a Unix timestamp. |
Examples
from hermes.core.export import export
# Save a country risk snapshot as JSON
export(data=risk, filetype="json", name="ukr_risk")
# Save a training panel as Parquet
export(data=panel, filetype="parquet", loc="data/panels/", name="monthly_panel")
Passing anything other than a DataFrame or Series raises a
TypeError. Unsupported file types are logged and skipped.
Countries
Supported Codes
Hermes uses ~250 ISO3 country codes (Alpha-3) from the pycountry library. Full list accessible via:
hr.list_countries # ["AFG", "ALB", "DZA", ...]
Validation
from hermes.core.countries import check_iso3
check_iso3("USA") # True
check_iso3("XYZ") # raises ValueError
Coverage Notes
Not every source covers every country:
| Source | Coverage |
|---|---|
| World Bank | ~200 countries |
| IMF | ~190 countries |
| GDELT | Global (event-level) |
| OpenSanctions | Global (entity-level) |
| FRED | United States only |
| Binance | N/A (asset-based, not country-based) |
| Bundled datasets | Varies (HRS: ~200, HDI: ~190, FSI: ~170, SIPRI: ~170) |
Features that depend on missing data return NaN rather than raising.
World Bank
File: sources/world_bank.py
What It Does
Fetches indicator time series from the World Bank v2 API (api.worldbank.org/v2). Covers ~20 indicators across economic, governance, and social dimensions.
Fetch
df = await hr.world_bank.fetch(
indicator="NY.GDP.MKTP.KD.ZG", # GDP growth
country="USA",
start_year=2010,
end_year=2024,
)
Output Columns
| Column | Type | Description |
|---|---|---|
date |
datetime | Year |
indicator_id |
str | World Bank indicator code |
country |
str | ISO3 country code |
value |
float | Indicator value |
source |
str | "world_bank" |
Key Indicators
| Code | Name | Group |
|---|---|---|
NY.GDP.MKTP.KD.ZG |
GDP growth (annual %) | Economic |
FP.CPI.TOTL.ZG |
Inflation, consumer prices | Economic |
SL.UEM.TOTL.ZS |
Unemployment rate | Economic |
BN.CAB.XOKA.GD.ZS |
Current account balance | Economic |
DT.DOD.DECT.GN.ZS |
External debt stocks | Economic |
FB.AST.NPLN.ZS |
Non-performing loans | Economic |
RL.EST |
Rule of law estimate | Geopolitical |
RQ.EST |
Regulatory quality | Geopolitical |
VA.EST |
Voice and accountability | Geopolitical |
CC.EST |
Control of corruption | Geopolitical |
GE.EST |
Government effectiveness | Geopolitical |
PV.EST |
Political stability | Geopolitical |
SI.POV.GINI |
Gini coefficient | Social |
SI.POV.DDAY |
Poverty headcount ratio | Social |
EG.IMP.CONS.ZS |
Energy dependence | Environmental |
ER.H2O.FWTL.ZS |
Water stress index | Environmental |
Cache
7-day TTL. Retry with exponential backoff via aiohttp.
IMF
File: sources/imf.py
What It Does
Fetches data from the IMF SDMX 3.0 API (api.imf.org/external/sdmx/3.0). Supports three dataflows: International Financial Statistics (IFS), World Economic Outlook (WEO), and Government Finance Statistics (GFS).
Fetch
df = await hr.imf.fetch(
dataflow="IFS", # or "WEO" or "GFS"
key="M..IX.._T", # SDMX key pattern
start_period=2010,
end_period=2024,
)
Output Columns
| Column | Type | Description |
|---|---|---|
date |
datetime | Observation date |
indicator_id |
str | IMF indicator code (e.g. PPI.IX.A) |
country |
str | ISO2 country code (auto-converted from ISO3) |
value |
float | Indicator value |
source |
str | "imf" |
Key Indicators
| Dataflow | Code | Name | Used In |
|---|---|---|---|
| IFS | PPI.IX.A |
Producer Price Index | ppi_yoy feature |
| IFS | CPI._T.IX.M |
Consumer Price Index | inflation_yoy feature |
| IFS | EREER_IX.M |
Effective Exchange Rate | reer_misalignment feature |
| WEO | GGXCNL_NGDP |
Fiscal Deficit (% GDP) | fiscal_deficit_gdp feature |
| WEO | GGXWDG_NGDP |
Government Debt (% GDP) | government_debt_gdp feature |
Notes
- ISO3 → ISO2 conversion handled automatically via
pycountry - 404 responses return empty DataFrame (no error)
- 7-day cache TTL
GDELT
File: sources/gdelt.py
What It Does
Queries the GDELT Doc API v2 for global event data — conflict events, protests, diplomacy, and sanctions activity. Includes FIPS-to-ISO3 normalization and rate limiting.
Fetch
df = await hr.gdelt.query_events(
theme="CONFLICT", # CONFLICT, PROTEST, DIPLOMACY, SANCTIONS
country="USA",
start_date="2024-01-01",
end_date="2024-03-01",
)
Output Schema
| Column | Type | Description |
|---|---|---|
event_id |
str | GDELT event identifier |
date |
datetime | Event date |
country_iso3 |
str | ISO3 country code (FIPS-normalized) |
event_type |
str | CONFLICT, PROTEST, DIPLOMACY, or SANCTIONS |
severity |
float | Event severity score |
lat |
float | Latitude |
lon |
float | Longitude |
source |
str | Always "gdelt" |
Theme Mapping
| Theme | GDELT Event Types | Features |
|---|---|---|
| CONFLICT | ASSAULT, FIGHT,Military action | conflict_event_count, battle_deaths, goldstein_scale |
| PROTEST | PROTEST, RIOT, peaceful protest | protest_event_count, protest_violence_level |
| DIPLOMACY | Diplomatic meetings, treaties | diplomatic_event_count, diplomatic_intensity |
| SANCTIONS | Sanctions-related events | sanctions_count_active, sanctions_new_30d |
Rate Limiting
- 5-second minimum between GDELT calls
- Session-level in-memory cache for repeated queries
- Health check pings Doc API before issuing queries
Cache
6-hour TTL (shorter than other sources — GDELT data updates frequently).
OpenSanctions
File: sources/opensanctions.py
What It Does
Fetches sanctioned entities from the OpenSanctions API (api.opensanctions.org). Covers multiple sanctions lists: US OFAC SDN, EU FSUK, UK FCDOS, and UN Security Council.
Fetch
df = await hr.opensanction.fetch(
country="USA", # ISO3 country code
datasets="us_ofac_sdn", # specific dataset
)
Datasets
| Dataset | Description |
|---|---|
us_ofac_sdn |
US Treasury OFAC Specially Designated Nationals |
eu_fsf |
EU Financial Sanctions List |
uk_fcdos |
UK Financial Conduct Department of State |
un_sc |
UN Security Council Sanctions |
Output Columns
| Column | Type | Description |
|---|---|---|
date |
datetime | Observation date |
indicator_id |
str | Entity type |
country |
str | ISO2 country code |
value |
float | Sanctions count |
source |
str | "opensanctions" |
Used By
sanctions_count_active— total active sanctions for a countrysanctions_new_30d— sanctions added in last 30 dayssanctions_sector_coverage— sector coverage ratio
Cache
30-day TTL (sanctions lists change slowly).
FRED
File: sources/fred.py
What It Does
Fetches US economic data from the FRED API (api.stlouisfed.org). 23 series covering GDP, inflation, employment, interest rates, housing, and market indicators.
Fetch
df = await hr.fred.fetch(
series_ids=["DFF", "UNRATE", "CPIAUCSL"],
start_date="2020-01-01",
)
Series
| Series ID | Name | Used In |
|---|---|---|
DFF |
Fed Funds Effective Rate | Interest rate context |
CPIAUCSL |
Consumer Price Index | Inflation analysis |
UNRATE |
Unemployment Rate | Labor market |
GDP |
Gross Domestic Product | Economic output |
T10Y2Y |
10Y-2Y Yield Curve | Recession indicator |
VIXCLS |
CBOE Volatility Index | Market fear gauge |
DTWEXBGS |
Trade Weighted USD Index | Currency strength |
MORTGAGE30US |
30-Year Fixed Mortgage Rate | Housing market |
Plus 15 additional series (M2, industrial production, housing starts, consumer sentiment, etc.).
Output Columns
| Column | Type | Description |
|---|---|---|
date |
datetime | Observation date |
indicator_id |
str | FRED series ID |
country |
str | Always "USA" |
value |
float | Series value |
source |
str | "fred" |
API Key
Get a free key at fred.stlouisfed.org/docs/api/api_key.html.
Cache
30-day TTL per series code. Connector-level TTL of 1 day.
Binance
File: sources/binance.py
What It Does
Fetches crypto market data from the Binance API — both spot and futures (USDT-margined). No API key required for public endpoints.
Fetch
df = await hr.binance.fetch(
symbol="BTCUSDT",
interval="1d", # 1m, 5m, 15m, 1h, 4h, 1d
limit=100,
)
Endpoints
| Method | What It Fetches |
|---|---|
fetch() |
OHLCV candles |
fetch_trades() |
Recent trades |
fetch_agg_trades() |
Aggregated trades |
fetch_order_book() |
Order book depth |
fetch_ticker() |
24hr rolling stats |
fetch_funding_rate() |
Perpetual futures funding rate |
fetch_open_interest() |
Open interest |
Output (OHLCV)
| Column | Type | Description |
|---|---|---|
date |
datetime | Candle open time |
indicator_id |
str | "OHLCV" |
country |
str | N/A |
value |
float | Close price |
source |
str | "binance" |
Additional columns: open, high, low, volume.
Used By
The TAfeatures class (technical analysis) pulls from Binance to compute 86-field snapshots including trend scores, order book imbalance, funding rates, and composite signals.
Cache
1-day TTL.
Finnhub
File: sources/finnhub.py
What It Does
Fetches US equity data from the Finnhub API (finnhub.io/api/v1). 12 endpoints covering price history, company profiles, financial metrics, and earnings.
Fetch
df = await hr.finnhub.fetch(
symbol="AAPL",
resolution="D", # D, W, M
from_date=1609459200, # Unix timestamp
to_date=1704067200,
)
Endpoints
| Method | Description |
|---|---|
fetch() |
OHLCV candles |
fetch_quote() |
Current quote (price, change, percent) |
fetch_profile() |
Company profile (name, industry, market cap) |
fetch_metric() |
Financial metrics (P/E, P/S, P/B, ROE, etc.) |
fetch_peers() |
Company peers |
fetch_earnings() |
Earnings history |
fetch_insider() |
Insider transactions |
fetch_eps() |
EPS estimates |
fetch_ebitda() |
EBITDA estimates |
fetch_revenue() |
Revenue estimates |
fetch_news() |
Company news |
fetch_symbol() |
Symbol search |
Output Columns
| Column | Type | Description |
|---|---|---|
date |
datetime | Observation date |
indicator_id |
str | Endpoint identifier |
country |
str | N/A |
value |
float | Metric value |
source |
str | "finnhub" |
Used By
The FAfeatures class (fundamental analysis) pulls from Finnhub for company profiles, financial metrics, and earnings data to compute 71-field snapshots.
API Key
Get a free key at finnhub.io (60 calls/min free tier).
Cache
7-day TTL.
SEC EDGAR
File: sources/sec_edgar.py
What It Does
Fetches company financial facts from the SEC EDGAR XBRL API (data.sec.gov/api/xbrl/companyfacts). Provides structured access to income statements, balance sheets, and cash flow data.
Fetch
df = await hr.sec_edger.fetch(
ticker="AAPL",
tags=["Revenues", "NetIncomeLoss", "Assets"],
)
Notes
- Uses
sec-cik-mapperfor automatic ticker → CIK lookup - User-Agent header required:
"{username} {email}"(set in constructor) - Covers all US publicly traded companies
- Data is quarterly and annual
Output Columns
| Column | Type | Description |
|---|---|---|
date |
datetime | Filing date |
indicator_id |
str | XBRL tag (e.g. Revenues) |
country |
str | N/A |
value |
float | Filing value |
source |
str | "sec_edgar" |
Used By
The FAfeatures class pulls from SEC EDGAR for income statement, balance sheet, and cash flow fields in the 71-field CompanyFundamental snapshot.
Cache
7-day TTL.
Yahoo Finance
File: sources/yf.py
What It Does
Wraps the yfinance library to fetch analyst estimates and earnings history for US equities.
Fetch
df = await hr.yfin.fetch(
ticker="AAPL",
metrics=["eps_estimate", "revenue_estimate", "earnings_history"],
)
Metrics
| Metric | Description |
|---|---|
eps_estimate |
Analyst EPS estimates |
revenue_estimate |
Analyst revenue estimates |
earnings_history |
Historical earnings (actual vs estimate) |
Output Columns
| Column | Type | Description |
|---|---|---|
date |
datetime | Period date |
indicator_id |
str | Metric identifier |
country |
str | N/A |
value |
float | Estimate or actual value |
source |
str | "yfinance" |
Used By
The FAfeatures class pulls from Yahoo Finance for earnings estimates and revenue estimates in the CompanyFundamental snapshot.
Cache
1-day TTL.
Public Datasets
File: sources/public_data.py
What It Does
Provides access to 8 bundled static CSV datasets in sources/lib/datasets/. No network requests — data ships with the package.
Datasets
| File | Name | Fields | Used By |
|---|---|---|---|
hrs.csv |
Human Rights Scores | country, year, score | human_rights_score |
hdi1.csv |
Human Development Index | country, year, hdi | human_development_index |
global_cpi_all.csv |
Corruption Perception Index | country, year, score | corruption_perception_index |
fsi.csv |
Fragile States Index | country, year, total | fragile_state_index |
nato.csv |
NATO Membership | country, member | nato_member |
crs.csv |
Climate Readiness Score (NDGAIN) | country, year, score | climate_readiness_score |
cvs.csv |
Climate Vulnerability Score (NDGAIN) | country, year, score | climate_vulnerability_score |
sipri.csv |
SIPRI Military Spending | country, year, spending_gdp, growth | military_spending_gdp |
Fetch
df = await hr.datasets.fetch(
dataset="hrs", # dataset name
country="USA", # optional filter
)
Output Columns
| Column | Type | Description |
|---|---|---|
date |
datetime | Year (if applicable) |
indicator_id |
str | Dataset name |
country |
str | ISO3 country code |
value |
float | Dataset value |
source |
str | "public_data" |
Notes
These datasets replace API calls for indicators that are static or update infrequently. They back several features in the security, social, and environmental groups.
HDX CPI
File: sources/lib/datasets/global_cpi_all.csv
What It Does
Provides the Transparency International Corruption Perception Index (CPI) as a bundled CSV. No network requests — ships with the package.
Fetch
df = await hr.datasets.fetch(dataset="cpi", country="USA")
Output Columns
| Column | Type | Description |
|---|---|---|
date |
datetime | Year |
indicator_id |
str | "cpi" |
country |
str | ISO3 country code |
value |
float | CPI score (0-100) |
source |
str | "public_data" |
Used By
corruption_perception_index feature — score 0-100 where higher is less corrupt.
See Public Datasets for the full list of bundled datasets.