424 lines
16 KiB
Python
424 lines
16 KiB
Python
|
|
"""
|
|||
|
|
共享内存K线数据缓存模块
|
|||
|
|
支持多进程间K线数据共享,供数据库写入程序使用
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
import json
|
|||
|
|
import pickle
|
|||
|
|
import threading
|
|||
|
|
from multiprocessing import shared_memory
|
|||
|
|
from typing import Dict, Optional, Any
|
|||
|
|
import pandas as pd
|
|||
|
|
from datetime import datetime
|
|||
|
|
import time
|
|||
|
|
import logging
|
|||
|
|
|
|||
|
|
# 导入公共配置
|
|||
|
|
from common import LOG_PREFIXES, get_cache_key, normalize_stock_code
|
|||
|
|
|
|||
|
|
# 配置日志
|
|||
|
|
logger = logging.getLogger(__name__)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class SharedMemoryKlineCache:
|
|||
|
|
"""共享内存K线数据缓存管理器"""
|
|||
|
|
|
|||
|
|
def __init__(self, cache_name: str = "qtrade_kline_cache", max_size_mb: int = 100):
|
|||
|
|
"""
|
|||
|
|
初始化共享内存缓存
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
cache_name: 共享内存名称
|
|||
|
|
max_size_mb: 最大内存大小(MB)
|
|||
|
|
"""
|
|||
|
|
self.cache_name = cache_name
|
|||
|
|
self.max_size_bytes = max_size_mb * 1024 * 1024
|
|||
|
|
self.lock = threading.Lock()
|
|||
|
|
|
|||
|
|
# 尝试连接现有共享内存,如果不存在则创建
|
|||
|
|
try:
|
|||
|
|
self.shm = shared_memory.SharedMemory(name=cache_name)
|
|||
|
|
logger.info(f"{LOG_PREFIXES['CACHE']} 连接到现有共享内存: {cache_name}")
|
|||
|
|
except FileNotFoundError:
|
|||
|
|
# 创建新的共享内存
|
|||
|
|
self.shm = shared_memory.SharedMemory(name=cache_name, create=True, size=self.max_size_bytes)
|
|||
|
|
# 初始化空的数据结构
|
|||
|
|
initial_data = {
|
|||
|
|
'metadata': {
|
|||
|
|
'created_time': datetime.now().isoformat(),
|
|||
|
|
'last_update': datetime.now().isoformat(),
|
|||
|
|
'version': '1.0.0'
|
|||
|
|
},
|
|||
|
|
'kline_data': {}, # {stock_code: [kline_records]}
|
|||
|
|
'status': 'initialized'
|
|||
|
|
}
|
|||
|
|
self._write_data_to_memory(initial_data)
|
|||
|
|
logger.info(f"{LOG_PREFIXES['CACHE']} 创建新共享内存: {cache_name}, 大小: {max_size_mb}MB")
|
|||
|
|
|
|||
|
|
def _write_data_to_memory(self, data: dict):
|
|||
|
|
"""将数据写入共享内存,支持动态扩展"""
|
|||
|
|
try:
|
|||
|
|
# 序列化数据
|
|||
|
|
serialized_data = pickle.dumps(data)
|
|||
|
|
data_size = len(serialized_data)
|
|||
|
|
|
|||
|
|
# 如果数据大小超过当前共享内存,尝试扩展
|
|||
|
|
if data_size > self.max_size_bytes:
|
|||
|
|
old_size_mb = self.max_size_bytes // (1024 * 1024)
|
|||
|
|
new_size_mb = max(old_size_mb * 2, (data_size // (1024 * 1024)) + 10)
|
|||
|
|
logger.info(f"{LOG_PREFIXES['CACHE']} 共享内存不足,从 {old_size_mb}MB 扩展到 {new_size_mb}MB")
|
|||
|
|
|
|||
|
|
if self._expand_shared_memory(new_size_mb):
|
|||
|
|
logger.info(f"{LOG_PREFIXES['SUCCESS']} 共享内存扩展成功")
|
|||
|
|
else:
|
|||
|
|
raise ValueError(f"共享内存扩展失败,数据大小 {data_size/1024/1024:.2f}MB 超过最大限制")
|
|||
|
|
|
|||
|
|
# 清空共享内存
|
|||
|
|
self.shm.buf[:] = b'\x00' * len(self.shm.buf)
|
|||
|
|
|
|||
|
|
# 写入数据大小(前8字节)
|
|||
|
|
size_bytes = data_size.to_bytes(8, byteorder='little')
|
|||
|
|
self.shm.buf[:8] = size_bytes
|
|||
|
|
|
|||
|
|
# 写入实际数据
|
|||
|
|
self.shm.buf[8:8+data_size] = serialized_data
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
logger.error(f"{LOG_PREFIXES['ERROR']} 写入共享内存失败: {e}")
|
|||
|
|
raise
|
|||
|
|
|
|||
|
|
def _expand_shared_memory(self, new_size_mb: int) -> bool:
|
|||
|
|
"""扩展共享内存大小"""
|
|||
|
|
try:
|
|||
|
|
# 保存现有数据
|
|||
|
|
existing_data = self._read_data_from_memory()
|
|||
|
|
|
|||
|
|
# 关闭当前共享内存
|
|||
|
|
old_name = self.cache_name
|
|||
|
|
self.shm.close()
|
|||
|
|
self.shm.unlink() # 删除旧的共享内存
|
|||
|
|
|
|||
|
|
# 创建新的更大的共享内存
|
|||
|
|
self.max_size_bytes = new_size_mb * 1024 * 1024
|
|||
|
|
self.shm = shared_memory.SharedMemory(
|
|||
|
|
name=old_name,
|
|||
|
|
create=True,
|
|||
|
|
size=self.max_size_bytes
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 恢复数据
|
|||
|
|
if existing_data:
|
|||
|
|
self._write_data_to_memory(existing_data)
|
|||
|
|
|
|||
|
|
return True
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f"❌ 扩展共享内存失败: {e}")
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
def _read_data_from_memory(self) -> dict:
|
|||
|
|
"""从共享内存读取数据"""
|
|||
|
|
try:
|
|||
|
|
# 读取数据大小
|
|||
|
|
size_bytes = bytes(self.shm.buf[:8])
|
|||
|
|
data_size = int.from_bytes(size_bytes, byteorder='little')
|
|||
|
|
|
|||
|
|
if data_size == 0:
|
|||
|
|
return {}
|
|||
|
|
|
|||
|
|
# 读取实际数据
|
|||
|
|
serialized_data = bytes(self.shm.buf[8:8+data_size])
|
|||
|
|
data = pickle.loads(serialized_data)
|
|||
|
|
|
|||
|
|
return data
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f"❌ 读取共享内存失败: {e}")
|
|||
|
|
return {}
|
|||
|
|
|
|||
|
|
def add_kline_data(self, stock_code: str, kline_record: dict) -> bool:
|
|||
|
|
"""
|
|||
|
|
添加K线数据到共享内存
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
stock_code: 股票代码
|
|||
|
|
kline_record: K线记录字典
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
是否添加成功
|
|||
|
|
"""
|
|||
|
|
with self.lock:
|
|||
|
|
try:
|
|||
|
|
# 读取现有数据
|
|||
|
|
data = self._read_data_from_memory()
|
|||
|
|
|
|||
|
|
# 确保数据结构存在
|
|||
|
|
if 'kline_data' not in data:
|
|||
|
|
data['kline_data'] = {}
|
|||
|
|
if 'metadata' not in data:
|
|||
|
|
data['metadata'] = {}
|
|||
|
|
|
|||
|
|
# 添加或更新K线数据
|
|||
|
|
if stock_code not in data['kline_data']:
|
|||
|
|
data['kline_data'][stock_code] = []
|
|||
|
|
|
|||
|
|
# 添加时间戳用于排序和去重
|
|||
|
|
kline_record['_added_time'] = datetime.now().isoformat()
|
|||
|
|
|
|||
|
|
# 检查是否重复(基于timestamp)
|
|||
|
|
existing_timestamps = {
|
|||
|
|
record.get('timestamp') for record in data['kline_data'][stock_code]
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if kline_record.get('timestamp') not in existing_timestamps:
|
|||
|
|
data['kline_data'][stock_code].append(kline_record)
|
|||
|
|
|
|||
|
|
# 限制每只股票的记录数量(保留最新1000条)
|
|||
|
|
if len(data['kline_data'][stock_code]) > 1000:
|
|||
|
|
# 按时间戳排序并保留最新的
|
|||
|
|
data['kline_data'][stock_code].sort(
|
|||
|
|
key=lambda x: x.get('timestamp', ''), reverse=True
|
|||
|
|
)
|
|||
|
|
data['kline_data'][stock_code] = data['kline_data'][stock_code][:1000]
|
|||
|
|
|
|||
|
|
# 更新元数据
|
|||
|
|
data['metadata']['last_update'] = datetime.now().isoformat()
|
|||
|
|
data['metadata']['total_stocks'] = len(data['kline_data'])
|
|||
|
|
data['metadata']['total_records'] = sum(
|
|||
|
|
len(records) for records in data['kline_data'].values()
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 写回共享内存
|
|||
|
|
self._write_data_to_memory(data)
|
|||
|
|
|
|||
|
|
return True
|
|||
|
|
else:
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f"❌ 添加K线数据到共享内存失败: {e}")
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
def add_kline_data_batch(self, stock_code: str, kline_records: list) -> int:
|
|||
|
|
"""
|
|||
|
|
批量添加K线数据到共享内存(性能优化版本)
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
stock_code: 股票代码
|
|||
|
|
kline_records: K线记录列表
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
成功添加的记录数量
|
|||
|
|
"""
|
|||
|
|
with self.lock:
|
|||
|
|
try:
|
|||
|
|
# 读取现有数据
|
|||
|
|
data = self._read_data_from_memory()
|
|||
|
|
|
|||
|
|
# 确保数据结构存在
|
|||
|
|
if 'kline_data' not in data:
|
|||
|
|
data['kline_data'] = {}
|
|||
|
|
if 'metadata' not in data:
|
|||
|
|
data['metadata'] = {}
|
|||
|
|
|
|||
|
|
if stock_code not in data['kline_data']:
|
|||
|
|
data['kline_data'][stock_code] = []
|
|||
|
|
|
|||
|
|
# 获取现有时间戳集合(优化重复检查)
|
|||
|
|
existing_timestamps = {
|
|||
|
|
record.get('timestamp') for record in data['kline_data'][stock_code]
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
# 批量处理新记录
|
|||
|
|
new_records = []
|
|||
|
|
for kline_record in kline_records:
|
|||
|
|
if kline_record.get('timestamp') not in existing_timestamps:
|
|||
|
|
# 添加时间戳用于排序
|
|||
|
|
kline_record['_added_time'] = datetime.now().isoformat()
|
|||
|
|
new_records.append(kline_record)
|
|||
|
|
existing_timestamps.add(kline_record.get('timestamp'))
|
|||
|
|
|
|||
|
|
# 批量添加新记录
|
|||
|
|
data['kline_data'][stock_code].extend(new_records)
|
|||
|
|
|
|||
|
|
# 如果记录过多,只排序一次并限制数量
|
|||
|
|
if len(data['kline_data'][stock_code]) > 1000:
|
|||
|
|
data['kline_data'][stock_code].sort(
|
|||
|
|
key=lambda x: x.get('timestamp', ''), reverse=True
|
|||
|
|
)
|
|||
|
|
data['kline_data'][stock_code] = data['kline_data'][stock_code][:1000]
|
|||
|
|
|
|||
|
|
# 更新元数据
|
|||
|
|
data['metadata']['last_update'] = datetime.now().isoformat()
|
|||
|
|
data['metadata']['total_stocks'] = len(data['kline_data'])
|
|||
|
|
data['metadata']['total_records'] = sum(
|
|||
|
|
len(records) for records in data['kline_data'].values()
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 一次性写回共享内存
|
|||
|
|
self._write_data_to_memory(data)
|
|||
|
|
|
|||
|
|
return len(new_records)
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f"❌ 批量添加K线数据到共享内存失败: {e}")
|
|||
|
|
return 0
|
|||
|
|
|
|||
|
|
def get_kline_data(self, stock_code: str = None, limit: int = 100) -> dict:
|
|||
|
|
"""
|
|||
|
|
从共享内存获取K线数据
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
stock_code: 股票代码,None表示获取所有
|
|||
|
|
limit: 每只股票的记录限制
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
K线数据字典
|
|||
|
|
"""
|
|||
|
|
with self.lock:
|
|||
|
|
try:
|
|||
|
|
data = self._read_data_from_memory()
|
|||
|
|
|
|||
|
|
if not data or 'kline_data' not in data:
|
|||
|
|
return {}
|
|||
|
|
|
|||
|
|
if stock_code:
|
|||
|
|
# 获取指定股票数据
|
|||
|
|
if stock_code in data['kline_data']:
|
|||
|
|
records = data['kline_data'][stock_code]
|
|||
|
|
# 按时间戳排序并限制数量
|
|||
|
|
sorted_records = sorted(
|
|||
|
|
records,
|
|||
|
|
key=lambda x: x.get('timestamp', ''),
|
|||
|
|
reverse=True
|
|||
|
|
)
|
|||
|
|
return {stock_code: sorted_records[:limit]}
|
|||
|
|
else:
|
|||
|
|
return {}
|
|||
|
|
else:
|
|||
|
|
# 获取所有股票数据
|
|||
|
|
result = {}
|
|||
|
|
for code, records in data['kline_data'].items():
|
|||
|
|
sorted_records = sorted(
|
|||
|
|
records,
|
|||
|
|
key=lambda x: x.get('timestamp', ''),
|
|||
|
|
reverse=True
|
|||
|
|
)
|
|||
|
|
result[code] = sorted_records[:limit]
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f"❌ 从共享内存获取K线数据失败: {e}")
|
|||
|
|
return {}
|
|||
|
|
|
|||
|
|
def get_cache_status(self) -> dict:
|
|||
|
|
"""获取缓存状态"""
|
|||
|
|
with self.lock:
|
|||
|
|
try:
|
|||
|
|
data = self._read_data_from_memory()
|
|||
|
|
|
|||
|
|
if not data:
|
|||
|
|
return {'status': 'empty', 'error': 'No data in shared memory'}
|
|||
|
|
|
|||
|
|
metadata = data.get('metadata', {})
|
|||
|
|
kline_data = data.get('kline_data', {})
|
|||
|
|
|
|||
|
|
total_records = sum(len(records) for records in kline_data.values()) if kline_data else 0
|
|||
|
|
|
|||
|
|
status = {
|
|||
|
|
'status': 'active',
|
|||
|
|
'created_time': metadata.get('created_time'),
|
|||
|
|
'last_update': metadata.get('last_update'),
|
|||
|
|
'total_stocks': len(kline_data),
|
|||
|
|
'total_records': total_records,
|
|||
|
|
'memory_usage': len(pickle.dumps(data)),
|
|||
|
|
'memory_limit': self.max_size_bytes,
|
|||
|
|
'stocks_info': {}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
# 统计每只股票的信息
|
|||
|
|
for stock_code, records in kline_data.items():
|
|||
|
|
if records:
|
|||
|
|
latest_record = max(records, key=lambda x: x.get('timestamp', ''))
|
|||
|
|
status['stocks_info'][stock_code] = {
|
|||
|
|
'record_count': len(records),
|
|||
|
|
'latest_timestamp': latest_record.get('timestamp'),
|
|||
|
|
'latest_price': latest_record.get('close')
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return status
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
return {'status': 'error', 'error': str(e)}
|
|||
|
|
|
|||
|
|
def clear_cache(self, stock_code: str = None) -> bool:
|
|||
|
|
"""清理缓存数据"""
|
|||
|
|
with self.lock:
|
|||
|
|
try:
|
|||
|
|
data = self._read_data_from_memory()
|
|||
|
|
|
|||
|
|
if not data or 'kline_data' not in data:
|
|||
|
|
return True
|
|||
|
|
|
|||
|
|
if stock_code:
|
|||
|
|
# 清理指定股票
|
|||
|
|
if stock_code in data['kline_data']:
|
|||
|
|
del data['kline_data'][stock_code]
|
|||
|
|
print(f"🗑️ 清理共享内存中 {stock_code} 的数据")
|
|||
|
|
else:
|
|||
|
|
# 清理所有数据
|
|||
|
|
data['kline_data'] = {}
|
|||
|
|
print("🗑️ 清理共享内存中所有K线数据")
|
|||
|
|
|
|||
|
|
# 更新元数据
|
|||
|
|
data['metadata']['last_update'] = datetime.now().isoformat()
|
|||
|
|
data['metadata']['total_stocks'] = len(data['kline_data'])
|
|||
|
|
data['metadata']['total_records'] = sum(
|
|||
|
|
len(records) for records in data['kline_data'].values()
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
self._write_data_to_memory(data)
|
|||
|
|
return True
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f"❌ 清理共享内存缓存失败: {e}")
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
def close(self):
|
|||
|
|
"""关闭共享内存连接"""
|
|||
|
|
try:
|
|||
|
|
self.shm.close()
|
|||
|
|
print(f"🔒 已关闭共享内存连接: {self.cache_name}")
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f"❌ 关闭共享内存连接失败: {e}")
|
|||
|
|
|
|||
|
|
def cleanup(self):
|
|||
|
|
"""清理并删除共享内存"""
|
|||
|
|
try:
|
|||
|
|
self.shm.close()
|
|||
|
|
self.shm.unlink()
|
|||
|
|
print(f"🗑️ 已删除共享内存: {self.cache_name}")
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f"❌ 删除共享内存失败: {e}")
|
|||
|
|
|
|||
|
|
|
|||
|
|
# 全局共享内存缓存实例
|
|||
|
|
shared_cache = None
|
|||
|
|
|
|||
|
|
|
|||
|
|
def init_shared_cache(cache_name: str = "qtrade_kline_cache", max_size_mb: int = 100):
|
|||
|
|
"""初始化全局共享内存缓存"""
|
|||
|
|
global shared_cache
|
|||
|
|
if shared_cache is None:
|
|||
|
|
shared_cache = SharedMemoryKlineCache(cache_name, max_size_mb)
|
|||
|
|
print(f"🚀 初始化共享内存缓存: {cache_name}")
|
|||
|
|
return shared_cache
|
|||
|
|
|
|||
|
|
|
|||
|
|
def get_shared_cache():
|
|||
|
|
"""获取全局共享内存缓存实例"""
|
|||
|
|
global shared_cache
|
|||
|
|
if shared_cache is None:
|
|||
|
|
shared_cache = init_shared_cache()
|
|||
|
|
return shared_cache
|