Heuristic:24mlight A Share investment Agent SQLite Cache TTL Strategy
| Knowledge Sources | |
|---|---|
| Domains | Optimization, Infrastructure, Finance |
| Last Updated | 2026-10-10 14:00 GMT |
Overview
Differentiated TTL strategy for SQLite-cached financial data: real-time data expires in minutes, financial indicators in days, reports in weeks, and historical price data never expires.
Description
The akshare_cache.py module applies different cache TTLs based on data volatility:
- Real-time spot data (
stock_zh_a_spot_em): 10-minute TTL (600s) — prices change constantly during trading hours. - Financial indicators (
stock_financial_analysis_indicator): No TTL (permanent cache) — historical indicators never change;force_refreshflag used for updates. - Financial reports (
stock_financial_report_sina): No TTL (permanent cache) — historical reports are immutable. - Historical price data (
baostock_history_k): No TTL — historical OHLCV data is permanent; incremental fetch fills missing segments. - News data (
stock_news_em): 2-hour TTL for today's news, no TTL for historical dates — today's news updates frequently, past news is stable.
The config.json file allows per-agent cache refresh overrides via the cache_refresh configuration section.
Usage
Use this heuristic when:
- Deciding TTL values for new cached data types
- Understanding why the system seems to "remember" old data
- Configuring
cache_refreshinconfig.jsonto force-refresh specific data - Debugging stale data issues
The Insight (Rule of Thumb)
- Action: Set TTL based on data mutability: real-time data = minutes, daily data = hours, historical data = no TTL (permanent).
- Value: Default TTLs: spot=600s, news=7200s (today only), indicators/reports/price history=permanent.
- Trade-off: Longer TTLs reduce API calls and improve performance but risk stale data; shorter TTLs ensure freshness but increase latency and API usage.
- Compatibility:
config.json→cache_refreshsection can override per-agent, per-data-type to force refresh.
Reasoning
AkShare and BaoStock are free APIs with rate limits and occasional instability. Caching reduces API calls dramatically, especially during backtesting where the same historical data is requested repeatedly. The key insight is that financial data has different volatility profiles:
- Real-time prices change every second during trading → 10-minute TTL is sufficient for analysis.
- Financial indicators (quarterly) never change once published → permanent cache with manual refresh.
- Historical price data is immutable → permanent cache with incremental gap-filling.
- News for today is still accumulating → 2-hour TTL; news from past dates is stable → no TTL.
The _missing_segments() function computes which trading days are missing from the cache and only fetches those gaps, avoiding redundant full-range fetches. This incremental approach is critical for long backtest ranges.
Code Evidence
Spot data TTL from src/tools/akshare_cache.py:80:
def get_stock_spot_row(symbol: str, ttl_seconds: int = 600) -> Optional[pd.Series]:
Financial indicators permanent cache from src/tools/akshare_cache.py:114-116:
def get_financial_indicators(
symbol: str, start_year: str, ttl_seconds: int = 24 * 3600, force_refresh: bool = False
) -> pd.DataFrame:
# 财务指标缓存改为"无 TTL 常驻";ttl_seconds 参数仅保留兼容性
News TTL with date-awareness from src/tools/akshare_cache.py:360-362:
today_str = datetime.now().strftime("%Y-%m-%d")
date_str = _normalize_date_str(date or today_str)
effective_ttl = ttl_seconds if date is None or date_str == today_str else None
Incremental gap-filling from src/tools/akshare_cache.py:297-312:
expected_days = _expected_trading_days(start_date, end_date)
missing_segments = _missing_segments(expected_days, cached_dates)
if not missing_segments:
logger.info("📦 Price history cache satisfied for %s(%d 个交易日)", symbol, len(expected_days))
else:
logger.info("🔄 Price history cache 缺少 %d 个交易日,共 %d 个区间,正在增量拉取 %s",
missing_days, len(missing_segments), symbol)
Config override from src/utils/config_loader.py:10-31:
DEFAULT_CACHE_REFRESH: Dict[str, Dict[str, bool]] = {
"market_data_agent": {"price_history": False, "financial_indicators": False, ...},
"sentiment_agent": {"news": True},
"macro_analyst_agent": {"news": True},
}