|
| 1 | +import os |
| 2 | +import sqlite3 |
| 3 | +import pandas as pd |
| 4 | +import time |
| 5 | +import pickle |
| 6 | +import logging |
| 7 | +from typing import Optional, List, Dict, Any |
| 8 | +from datetime import datetime, timedelta |
| 9 | +from openbb_akshare.utils.tools import setup_logger |
| 10 | + |
| 11 | +CACHE_TTL = 60*60 # 60 seconds |
| 12 | +setup_logger() |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | +# Constant TTL strategy |
| 16 | +def constant_ttl(now: datetime, ttl_seconds: int) -> datetime: |
| 17 | + return now + timedelta(seconds=ttl_seconds) |
| 18 | + |
| 19 | +# Quarter-based expiry (each quarter is 3 months) |
| 20 | +def get_next_quarter_start(dt: datetime) -> datetime: |
| 21 | + month = ((dt.month - 1) // 3 + 1) * 3 + 1 |
| 22 | + if month > 12: |
| 23 | + return datetime(dt.year + 1, 1, 1) |
| 24 | + return datetime(dt.year, month, 1) |
| 25 | + |
| 26 | +# Year-based expiry |
| 27 | +def get_next_year_start(dt: datetime) -> datetime: |
| 28 | + return datetime(dt.year + 1, 1, 1) |
| 29 | + |
| 30 | +def calculate_cache_ttl(ttl_strategy_func, *args, now=None): |
| 31 | + """ |
| 32 | + Generic function to calculate cache TTL using a strategy function. |
| 33 | + |
| 34 | + Args: |
| 35 | + ttl_strategy_func: A function that calculates the TTL end time. |
| 36 | + *args: Arguments for the strategy function. |
| 37 | + now: Optional current time (for testing or simulation). |
| 38 | + |
| 39 | + Returns: |
| 40 | + The calculated TTL expiry time. |
| 41 | + """ |
| 42 | + now = now or datetime.now() |
| 43 | + return ttl_strategy_func(now, *args) |
| 44 | + |
| 45 | +class BlobCache: |
| 46 | + def __init__(self, table_name: Optional[str] = None, db_path: Optional[str] = None): |
| 47 | + if table_name is None: |
| 48 | + raise ValueError("Table name must be provided") |
| 49 | + |
| 50 | + self.table_name = table_name |
| 51 | + self.conn = None |
| 52 | + if db_path is None: |
| 53 | + from openbb_akshare.utils import get_cache_path |
| 54 | + self.db_path = get_cache_path() |
| 55 | + else: |
| 56 | + os.makedirs(db_path, exist_ok=True) |
| 57 | + db_path = f"{db_path}/equity.db" |
| 58 | + self.db_path = db_path |
| 59 | + self._ensure_db_exists() |
| 60 | + |
| 61 | + def _ensure_db_exists(self): |
| 62 | + """Ensure the SQLite database and table exist.""" |
| 63 | + with sqlite3.connect(self.db_path) as conn: |
| 64 | + cursor = conn.cursor() |
| 65 | + cursor.execute(f''' |
| 66 | + CREATE TABLE IF NOT EXISTS {self.table_name} ( |
| 67 | + key TEXT PRIMARY KEY, |
| 68 | + timestamp REAL, |
| 69 | + data BLOB |
| 70 | + ) |
| 71 | + ''') |
| 72 | + conn.commit() |
| 73 | + |
| 74 | + def load_cached_data(self, symbol:str, report_type, get_data, *args, **kwargs): |
| 75 | + """Load cached data from SQLite cache or generate new data.""" |
| 76 | + from openbb_akshare.utils.tools import normalize_symbol |
| 77 | + symbol_b, symbol_f, market = normalize_symbol(symbol) |
| 78 | + key = f"{market}{symbol_b}{report_type}" |
| 79 | + now = time.time() |
| 80 | + with sqlite3.connect(self.db_path) as conn: |
| 81 | + cursor = conn.cursor() |
| 82 | + cursor.execute(f'SELECT timestamp, data FROM {self.table_name} WHERE key=?', (key,)) |
| 83 | + row = cursor.fetchone() |
| 84 | + |
| 85 | + if row: |
| 86 | + timestamp, data_blob = row |
| 87 | + stored_date = datetime.fromtimestamp(timestamp) |
| 88 | + if report_type == "annual": |
| 89 | + expired_date = calculate_cache_ttl(get_next_year_start, now=stored_date) |
| 90 | + if now < expired_date.timestamp(): |
| 91 | + logger.info("Loading annual data from SQLite cache...") |
| 92 | + return pickle.loads(data_blob) |
| 93 | + elif report_type == "quarter": |
| 94 | + expired_date = calculate_cache_ttl(get_next_quarter_start, now=stored_date) |
| 95 | + if now < expired_date.timestamp(): |
| 96 | + logger.info("Loading quarter data from SQLite cache...") |
| 97 | + return pickle.loads(data_blob) |
| 98 | + else: |
| 99 | + if now - timestamp < CACHE_TTL: |
| 100 | + logger.info("Loading data from SQLite cache...") |
| 101 | + return pickle.loads(data_blob) |
| 102 | + |
| 103 | + logger.info(f"Generating new {report_type} data...") |
| 104 | + df = get_data(symbol, report_type) |
| 105 | + |
| 106 | + # 序列化 DataFrame |
| 107 | + data_blob = pickle.dumps(df) |
| 108 | + |
| 109 | + # 更新或插入缓存 |
| 110 | + cursor.execute(f''' |
| 111 | + INSERT OR REPLACE INTO {self.table_name} (key, timestamp, data) |
| 112 | + VALUES (?, ?, ?) |
| 113 | + ''', (key, now, data_blob)) |
| 114 | + |
| 115 | + conn.commit() |
| 116 | + return df |
0 commit comments