Implementation:24mlight A Share investment Agent AkshareSQLiteCache
Appearance
| Knowledge Sources | |
|---|---|
| Domains | Data_Engineering, Caching |
| Last Updated | 2026-10-10 14:00 GMT |
Overview
Concrete tool for generic SQLite caching with auto-schema creation, TTL support, upsert semantics, and thread-safe per-thread connections, provided by the A_Share_investment_Agent repository.
Description
The AkshareSQLiteCache class provides a lightweight but robust caching layer used throughout the system for financial data, news, and LLM result caching. Key features:
- Auto-schema creation: Tables created lazily from first record; column types inferred from Python types
- Upsert semantics: Uses
INSERT ... ON CONFLICT DO UPDATEwith configurable key columns - TTL support:
fetch_recordsacceptsttl_secondsto filter stale records by缓存时间column - Thread safety: Uses
threading.local()for per-thread connections with WAL journal mode - Data normalization: Handles pandas Timestamps, numpy types, NaN values
- Auto-cleanup: Registers
atexithandler to close connections
Usage
Import when you need to:
- Cache API responses with TTL-based expiry
- Store news, financial data, or LLM results with upsert semantics
- Access a thread-safe shared cache from multiple agents
Code Reference
Source Location
- Repository: A_Share_investment_Agent
- File: src/database/sqlite_cache.py
- Lines: L51-235 (class), L54-125 (__init__, schema helpers), L126-168 (upsert_records), L170-235 (fetch_records, delete_records, close)
Signature
class AkshareSQLiteCache:
"""Simple SQLite-backed cache with insert-or-update semantics."""
def __init__(self, database_path: Path) -> None:
"""Initialize with SQLite database path."""
def upsert_records(
self,
table: str,
records: Iterable[Dict[str, Any]],
key_columns: Sequence[str],
) -> None:
"""Insert or update records by key columns."""
def fetch_records(
self,
table: str,
filters: Optional[Dict[str, Any]] = None,
ttl_seconds: Optional[int] = None,
order_by: Optional[str] = None,
limit: Optional[int] = None,
) -> List[Dict[str, Any]]:
"""Fetch records with optional filters, TTL, ordering, and limit."""
def delete_records(
self,
table: str,
filters: Optional[Dict[str, Any]] = None,
) -> None:
"""Delete records matching filters."""
def close(self) -> None:
"""Close thread-local connections."""
Import
from src.database import AkshareSQLiteCache
# or
from src.database.sqlite_cache import AkshareSQLiteCache
I/O Contract
upsert_records
| Name | Type | Required | Description |
|---|---|---|---|
| table | str | Yes | Table name |
| records | Iterable[Dict] | Yes | Records to upsert |
| key_columns | Sequence[str] | Yes | Columns for conflict resolution |
fetch_records
| Name | Type | Required | Description |
|---|---|---|---|
| table | str | Yes | Table name |
| filters | dict | No | Column-value equality filters |
| ttl_seconds | int | No | TTL in seconds (filters by 缓存时间 column) |
| order_by | str | No | ORDER BY clause |
| limit | int | No | Maximum records |
Usage Examples
Cache News Data
from src.database import AkshareSQLiteCache
from pathlib import Path
cache = AkshareSQLiteCache(Path("data/market_data_cache.db"))
# Upsert news
cache.upsert_records(
table="stock_news_daily_cache",
records=[{
"symbol": "002848",
"cache_date": "2025-01-15",
"news_json": '[{"title": "...", "content": "..."}]',
"news_count": 5,
"method": "tavily",
"search_time": "2025-01-15 10:30:00",
}],
key_columns=["symbol", "cache_date"],
)
# Fetch cached news
records = cache.fetch_records(
table="stock_news_daily_cache",
filters={"symbol": "002848", "cache_date": "2025-01-15"},
limit=1,
)
With TTL
# Fetch only records from the last 10 minutes
records = cache.fetch_records(
table="real_time_data",
filters={"symbol": "002848"},
ttl_seconds=600, # 10 minutes
)
Related Pages
Implements Principle
Requires Environment
Uses Heuristics
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment