feat: 实现技术指标计算系统
- 创建indicator_calculator模块,包含BaseIndicator基类和MACD、KDJ、BOLL指标实现 - 实现IndicatorManager管理多个指标的批量计算 - 创建data_writer模块,包含KlineWriter和IndicatorWriter持久化类 - 重构BaseDataDownloader,添加download()方法(只下载不保存) - 在DataProvider中集成指标计算流程,新增download_klines_with_indicators()等方法 - 在global.yaml添加指标配置section - 更新main.py演示指标计算功能 核心设计: - 职责分离:下载、计算指标、保存三步独立 - 灵活配置:通过yaml配置启用/禁用指标及参数 - 可扩展性:易于添加新指标类型
This commit is contained in:
parent
9d11f64c08
commit
dc9ac91a5e
@ -69,6 +69,33 @@ market:
|
||||
- "1w"
|
||||
cache_ttl: 60
|
||||
|
||||
# 技术指标配置(公用)
|
||||
indicators:
|
||||
# 是否启用指标计算
|
||||
enabled: true
|
||||
|
||||
# 要计算的指标列表
|
||||
# 支持的指标类型: macd, kdj, boll
|
||||
enabled_indicators:
|
||||
- macd
|
||||
- kdj
|
||||
- boll
|
||||
|
||||
# 各指标的参数配置
|
||||
macd:
|
||||
fast_period: 12 # 快速EMA周期
|
||||
slow_period: 26 # 慢速EMA周期
|
||||
signal_period: 9 # 信号线周期
|
||||
|
||||
kdj:
|
||||
period: 9 # RSV计算周期
|
||||
k_period: 3 # K值平滑周期
|
||||
d_period: 3 # D值平滑周期
|
||||
|
||||
boll:
|
||||
period: 20 # 移动平均周期
|
||||
std_multiplier: 2.0 # 标准差倍数
|
||||
|
||||
# 交易配置(公用)
|
||||
trading:
|
||||
sessions:
|
||||
|
||||
@ -6,6 +6,7 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime
|
||||
from typing import List, Optional, Dict, Any
|
||||
import pandas as pd
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
@ -193,6 +194,79 @@ class BaseDataDownloader(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
def download(self) -> Dict[str, pd.DataFrame]:
|
||||
"""
|
||||
下载数据(不保存到数据库)
|
||||
|
||||
Returns:
|
||||
股票K线数据字典,格式: {f"{symbol}_{period}": DataFrame}
|
||||
DataFrame包含列: timestamp, open, high, low, close, volume, amount
|
||||
"""
|
||||
self.logger.info("=" * 50)
|
||||
self.logger.info("开始下载数据(仅下载,不保存)")
|
||||
self.logger.info("=" * 50)
|
||||
|
||||
result = {}
|
||||
|
||||
for symbol in self.symbols:
|
||||
for period in self.periods:
|
||||
try:
|
||||
self.logger.info(f"下载 {symbol} [{period}] 数据...")
|
||||
|
||||
# 调用子类实现的下载方法
|
||||
klines = self._download_klines(
|
||||
symbol=symbol,
|
||||
start_date=self.start_date,
|
||||
end_date=self.end_date,
|
||||
period=period,
|
||||
)
|
||||
|
||||
if klines:
|
||||
# 转换为 DataFrame
|
||||
df = self._klines_to_dataframe(klines)
|
||||
key = f"{symbol}_{period}"
|
||||
result[key] = df
|
||||
|
||||
self.logger.info(f"✓ {symbol} [{period}]: 下载 {len(df)} 条")
|
||||
else:
|
||||
self.logger.warning(f"✗ {symbol} [{period}]: 无数据")
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"✗ {symbol} [{period}]: 下载失败 - {e}")
|
||||
|
||||
self.logger.info("=" * 50)
|
||||
self.logger.info(f"下载完成,共获取 {len(result)} 个数据集")
|
||||
self.logger.info("=" * 50)
|
||||
|
||||
return result
|
||||
|
||||
def _klines_to_dataframe(self, klines: List[Kline]) -> pd.DataFrame:
|
||||
"""
|
||||
将Kline对象列表转换为DataFrame
|
||||
|
||||
Args:
|
||||
klines: Kline对象列表
|
||||
|
||||
Returns:
|
||||
包含K线数据的DataFrame
|
||||
"""
|
||||
data = []
|
||||
for kline in klines:
|
||||
data.append(
|
||||
{
|
||||
"symbol": kline.symbol,
|
||||
"timestamp": kline.timestamp,
|
||||
"open": kline.open,
|
||||
"high": kline.high,
|
||||
"low": kline.low,
|
||||
"close": kline.close,
|
||||
"volume": kline.volume,
|
||||
"amount": kline.amount,
|
||||
}
|
||||
)
|
||||
|
||||
return pd.DataFrame(data)
|
||||
|
||||
def download_and_save(self) -> Dict[str, Any]:
|
||||
"""
|
||||
下载并保存数据
|
||||
|
||||
@ -19,6 +19,8 @@ from .kline_reader import KlineReader
|
||||
from .data_coverage_checker import DataCoverageChecker
|
||||
from .data_quality_checker import DataQualityChecker
|
||||
from .data_downloader import DownloaderFactory
|
||||
from .indicator_calculator import IndicatorManager
|
||||
from .data_writer import KlineWriter, IndicatorWriter
|
||||
|
||||
|
||||
logger = get_logger("DataProvider")
|
||||
@ -104,6 +106,22 @@ class DataProvider:
|
||||
self.coverage_checker = DataCoverageChecker(self.db_manager)
|
||||
self.quality_checker = DataQualityChecker(self.db_manager)
|
||||
|
||||
# 初始化指标管理器
|
||||
indicator_config = config.get("indicators", {})
|
||||
if indicator_config.get("enabled", False):
|
||||
# 提取各指标的配置
|
||||
enabled_indicators = indicator_config.get("enabled_indicators", [])
|
||||
indicator_configs = {}
|
||||
for indicator_name in enabled_indicators:
|
||||
if indicator_name in indicator_config:
|
||||
indicator_configs[indicator_name] = indicator_config[indicator_name]
|
||||
|
||||
self.indicator_manager = IndicatorManager(indicator_configs)
|
||||
logger.info(f"指标计算已启用: {enabled_indicators}")
|
||||
else:
|
||||
self.indicator_manager = None
|
||||
logger.info("指标计算未启用")
|
||||
|
||||
logger.debug("DataProvider 初始化完成")
|
||||
|
||||
def __enter__(self):
|
||||
@ -754,3 +772,196 @@ class DataProvider:
|
||||
except Exception as e:
|
||||
logger.error(f"数据下载失败: {e}")
|
||||
raise RuntimeError(f"数据下载失败: {e}") from e
|
||||
|
||||
# ==================== 指标计算相关方法 ====================
|
||||
|
||||
def download_klines_with_indicators(
|
||||
self,
|
||||
symbols: List[str],
|
||||
start_date: datetime,
|
||||
end_date: datetime,
|
||||
periods: Optional[List[str]] = None,
|
||||
calculate_indicators: bool = True,
|
||||
save_indicators: bool = True,
|
||||
) -> Dict[str, pd.DataFrame]:
|
||||
"""
|
||||
下载K线数据并计算技术指标
|
||||
|
||||
完整流程:下载 -> 计算指标 -> 保存K线 -> 保存指标
|
||||
|
||||
Args:
|
||||
symbols: 股票代码列表
|
||||
start_date: 开始日期
|
||||
end_date: 结束日期
|
||||
periods: 数据周期列表,默认 ['1d']
|
||||
calculate_indicators: 是否计算指标,默认True
|
||||
save_indicators: 是否保存指标到数据库,默认True
|
||||
|
||||
Returns:
|
||||
包含指标列的K线数据字典: {f"{symbol}_{period}": DataFrame}
|
||||
|
||||
Examples:
|
||||
>>> with DataProvider() as provider:
|
||||
... # 下载数据并计算指标
|
||||
... data = provider.download_klines_with_indicators(
|
||||
... symbols=['000001.SZ', '600000.SH'],
|
||||
... start_date=datetime(2024, 1, 1),
|
||||
... end_date=datetime(2024, 12, 31),
|
||||
... periods=['1d']
|
||||
... )
|
||||
... # 查看带指标的数据
|
||||
... df = data['000001.SZ_1d']
|
||||
... print(df[['close', 'macd_dif', 'kdj_k', 'boll_upper']].tail())
|
||||
"""
|
||||
if self.downloader_type is None:
|
||||
raise RuntimeError(
|
||||
"未配置数据下载器,请在 global.yaml 中配置 data_source.downloader"
|
||||
)
|
||||
|
||||
if periods is None:
|
||||
periods = ["1d"]
|
||||
|
||||
logger.info(
|
||||
f"开始下载数据并计算指标: {len(symbols)} 只股票, "
|
||||
f"{start_date.date()} ~ {end_date.date()}, "
|
||||
f"周期: {periods}"
|
||||
)
|
||||
|
||||
try:
|
||||
# 1. 通过工厂创建下载器实例
|
||||
downloader_class = DownloaderFactory.create(self.downloader_type)
|
||||
downloader = downloader_class(
|
||||
symbols=symbols,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
periods=periods,
|
||||
database=self._get_database(),
|
||||
)
|
||||
|
||||
# 2. 下载数据(不保存)
|
||||
kline_data = downloader.download()
|
||||
logger.info(f"下载完成,共获取 {len(kline_data)} 个数据集")
|
||||
|
||||
# 3. 计算指标
|
||||
if calculate_indicators and self.indicator_manager:
|
||||
kline_data = self.indicator_manager.calculate_all(kline_data)
|
||||
logger.info("指标计算完成")
|
||||
elif calculate_indicators and not self.indicator_manager:
|
||||
logger.warning("指标计算未启用,跳过指标计算")
|
||||
|
||||
# 4. 保存K线数据
|
||||
kline_writer = KlineWriter(database=self._get_database())
|
||||
kline_results = kline_writer.save(kline_data)
|
||||
logger.info(f"K线数据保存完成: {sum(kline_results.values())} 条记录")
|
||||
kline_writer.close()
|
||||
|
||||
# 5. 保存指标数据
|
||||
if save_indicators and self.indicator_manager:
|
||||
indicator_writer = IndicatorWriter(database=self._get_database())
|
||||
indicator_names = self.indicator_manager.get_enabled_indicators()
|
||||
indicator_results = indicator_writer.save(kline_data, indicator_names)
|
||||
logger.info(f"指标数据保存完成: {len(indicator_results)} 个数据集")
|
||||
indicator_writer.close()
|
||||
|
||||
logger.info("数据下载和指标计算流程完成")
|
||||
return kline_data
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"数据下载和指标计算失败: {e}")
|
||||
raise RuntimeError(f"数据下载和指标计算失败: {e}") from e
|
||||
finally:
|
||||
# 确保关闭下载器连接
|
||||
if "downloader" in locals():
|
||||
downloader.close()
|
||||
|
||||
def calculate_indicators(
|
||||
self,
|
||||
kline_data: Dict[str, pd.DataFrame],
|
||||
indicator_names: Optional[List[str]] = None,
|
||||
) -> Dict[str, pd.DataFrame]:
|
||||
"""
|
||||
为已有的K线数据计算技术指标
|
||||
|
||||
Args:
|
||||
kline_data: K线数据字典,格式: {f"{symbol}_{period}": DataFrame}
|
||||
indicator_names: 要计算的指标名称列表,None表示计算所有已配置的指标
|
||||
|
||||
Returns:
|
||||
添加了指标列的K线数据字典
|
||||
|
||||
Examples:
|
||||
>>> with DataProvider() as provider:
|
||||
... # 先获取K线数据
|
||||
... klines = provider.get_klines(
|
||||
... symbols=['000001.SZ'],
|
||||
... start_date=datetime(2024, 1, 1),
|
||||
... end_date=datetime(2024, 12, 31),
|
||||
... period='1d'
|
||||
... )
|
||||
... # 转换为统一格式
|
||||
... kline_data = {'000001.SZ_1d': klines['000001.SZ']}
|
||||
... # 计算指标
|
||||
... data_with_indicators = provider.calculate_indicators(
|
||||
... kline_data,
|
||||
... indicator_names=['macd', 'kdj']
|
||||
... )
|
||||
"""
|
||||
if not self.indicator_manager:
|
||||
logger.warning("指标计算未启用,返回原始数据")
|
||||
return kline_data
|
||||
|
||||
logger.info(f"开始计算指标: {len(kline_data)} 个数据集")
|
||||
|
||||
if indicator_names:
|
||||
# 计算指定的指标
|
||||
result = {}
|
||||
for key, df in kline_data.items():
|
||||
result[key] = self.indicator_manager.calculate(df, indicator_names)
|
||||
else:
|
||||
# 计算所有配置的指标
|
||||
result = self.indicator_manager.calculate_all(kline_data)
|
||||
|
||||
logger.info("指标计算完成")
|
||||
return result
|
||||
|
||||
def save_indicators(
|
||||
self,
|
||||
indicator_data: Dict[str, pd.DataFrame],
|
||||
indicator_names: Optional[List[str]] = None,
|
||||
) -> Dict[str, int]:
|
||||
"""
|
||||
保存技术指标数据到数据库
|
||||
|
||||
Args:
|
||||
indicator_data: 包含指标的K线数据字典,格式: {f"{symbol}_{period}": DataFrame}
|
||||
indicator_names: 要保存的指标名称列表,None表示保存所有已启用的指标
|
||||
|
||||
Returns:
|
||||
保存结果字典,格式: {key: saved_count}
|
||||
|
||||
Examples:
|
||||
>>> with DataProvider() as provider:
|
||||
... # 计算指标后保存
|
||||
... data_with_indicators = provider.calculate_indicators(kline_data)
|
||||
... results = provider.save_indicators(
|
||||
... data_with_indicators,
|
||||
... indicator_names=['macd', 'kdj', 'boll']
|
||||
... )
|
||||
... print(f"保存指标记录数: {sum(results.values())}")
|
||||
"""
|
||||
if not self.indicator_manager:
|
||||
logger.warning("指标计算未启用,无法保存指标")
|
||||
return {}
|
||||
|
||||
if indicator_names is None:
|
||||
indicator_names = self.indicator_manager.get_enabled_indicators()
|
||||
|
||||
logger.info(f"开始保存指标数据: {indicator_names}")
|
||||
|
||||
indicator_writer = IndicatorWriter(database=self._get_database())
|
||||
try:
|
||||
results = indicator_writer.save(indicator_data, indicator_names)
|
||||
logger.info(f"指标数据保存完成: {len(results)} 个数据集")
|
||||
return results
|
||||
finally:
|
||||
indicator_writer.close()
|
||||
|
||||
6
src/data_provider/data_writer/__init__.py
Normal file
6
src/data_provider/data_writer/__init__.py
Normal file
@ -0,0 +1,6 @@
|
||||
"""数据持久化模块"""
|
||||
|
||||
from .kline_writer import KlineWriter
|
||||
from .indicator_writer import IndicatorWriter
|
||||
|
||||
__all__ = ["KlineWriter", "IndicatorWriter"]
|
||||
263
src/data_provider/data_writer/indicator_writer.py
Normal file
263
src/data_provider/data_writer/indicator_writer.py
Normal file
@ -0,0 +1,263 @@
|
||||
"""技术指标数据持久化类"""
|
||||
|
||||
from typing import Dict, List
|
||||
import pandas as pd
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from src.core.logger import Logger
|
||||
from src.core.config import Config
|
||||
|
||||
|
||||
class IndicatorWriter:
|
||||
"""技术指标数据持久化类
|
||||
|
||||
负责将技术指标数据保存到数据库
|
||||
"""
|
||||
|
||||
def __init__(self, database: str | None = None):
|
||||
"""初始化指标数据写入器
|
||||
|
||||
Args:
|
||||
database: 目标数据库名,默认从配置读取
|
||||
"""
|
||||
self.logger = Logger()
|
||||
self.config = Config()
|
||||
self.database = database or self.config.get("database.database")
|
||||
|
||||
if not self.database:
|
||||
raise ValueError(
|
||||
"未指定目标数据库,请在配置文件中设置 database.database 或通过参数传入"
|
||||
)
|
||||
|
||||
# 创建数据库引擎
|
||||
self.engine = self._create_engine()
|
||||
self.Session = sessionmaker(bind=self.engine)
|
||||
|
||||
self.logger.info(f"IndicatorWriter初始化完成,目标数据库: {self.database}")
|
||||
|
||||
def _create_engine(self):
|
||||
"""创建数据库引擎"""
|
||||
host = self.config.get("database.host", "127.0.0.1")
|
||||
port = self.config.get("database.port", 3306)
|
||||
user = self.config.get("database.user", "root")
|
||||
password = self.config.get("database.password", "")
|
||||
|
||||
connection_url = (
|
||||
f"mysql+pymysql://{user}:{password}@"
|
||||
f"{host}:{port}/{self.database}?charset=utf8mb4"
|
||||
)
|
||||
return create_engine(connection_url, echo=False, pool_pre_ping=True)
|
||||
|
||||
def save(
|
||||
self, indicator_data: Dict[str, pd.DataFrame], indicator_names: List[str]
|
||||
) -> Dict[str, int]:
|
||||
"""保存技术指标数据到数据库
|
||||
|
||||
Args:
|
||||
indicator_data: 包含指标的K线数据字典,格式: {f"{symbol}_{period}": DataFrame}
|
||||
DataFrame除K线列外,还包含指标列
|
||||
indicator_names: 要保存的指标名称列表,如 ['macd', 'kdj', 'boll']
|
||||
|
||||
Returns:
|
||||
保存结果字典,格式: {key: saved_count}
|
||||
"""
|
||||
results = {}
|
||||
|
||||
for key, df in indicator_data.items():
|
||||
try:
|
||||
# 从key解析出symbol和period
|
||||
parts = key.rsplit("_", 1)
|
||||
if len(parts) != 2:
|
||||
self.logger.warning(f"无效的key格式: {key},跳过")
|
||||
continue
|
||||
|
||||
symbol, period = parts
|
||||
|
||||
# 为每个指标分别保存
|
||||
for indicator_name in indicator_names:
|
||||
saved_count = self._save_single_indicator(
|
||||
df, period, indicator_name
|
||||
)
|
||||
result_key = f"{key}_{indicator_name}"
|
||||
results[result_key] = saved_count
|
||||
|
||||
self.logger.info(f"保存 {result_key}: {saved_count} 条记录")
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"保存 {key} 的指标失败: {e}")
|
||||
|
||||
return results
|
||||
|
||||
def _save_single_indicator(
|
||||
self, df: pd.DataFrame, period: str, indicator_name: str
|
||||
) -> int:
|
||||
"""保存单个指标的数据
|
||||
|
||||
Args:
|
||||
df: 包含指标列的DataFrame
|
||||
period: 数据周期
|
||||
indicator_name: 指标名称
|
||||
|
||||
Returns:
|
||||
保存的记录数
|
||||
"""
|
||||
if df.empty:
|
||||
return 0
|
||||
|
||||
# 获取该指标的所有列
|
||||
indicator_columns = [
|
||||
col for col in df.columns if col.startswith(f"{indicator_name}_")
|
||||
]
|
||||
|
||||
if not indicator_columns:
|
||||
self.logger.warning(f"DataFrame中未找到指标 {indicator_name} 的列")
|
||||
return 0
|
||||
|
||||
# 验证必需的列
|
||||
if "symbol" not in df.columns or "timestamp" not in df.columns:
|
||||
raise ValueError("DataFrame必须包含 symbol 和 timestamp 列")
|
||||
|
||||
session = self.Session()
|
||||
saved_count = 0
|
||||
|
||||
# 获取表名
|
||||
table_name = self._get_indicator_table_name(period, indicator_name)
|
||||
|
||||
# 确保表存在
|
||||
self._ensure_table_exists(table_name, indicator_columns)
|
||||
|
||||
try:
|
||||
for _, row in df.iterrows():
|
||||
# 构建记录
|
||||
record = {
|
||||
"symbol": row["symbol"],
|
||||
"timestamp": row["timestamp"],
|
||||
}
|
||||
|
||||
# 添加指标列
|
||||
for col in indicator_columns:
|
||||
if pd.notna(row[col]): # 跳过NaN值
|
||||
record[col] = float(row[col])
|
||||
|
||||
# 如果所有指标值都是NaN,跳过此行
|
||||
if len(record) == 2: # 只有symbol和timestamp
|
||||
continue
|
||||
|
||||
# 构建SQL
|
||||
columns_str = ", ".join(record.keys())
|
||||
placeholders = ", ".join([f":{k}" for k in record.keys()])
|
||||
update_str = ", ".join(
|
||||
[
|
||||
f"{k}=VALUES({k})"
|
||||
for k in record.keys()
|
||||
if k not in ["symbol", "timestamp"]
|
||||
]
|
||||
)
|
||||
|
||||
sql = f"""
|
||||
INSERT INTO {table_name}
|
||||
({columns_str})
|
||||
VALUES ({placeholders})
|
||||
ON DUPLICATE KEY UPDATE
|
||||
{update_str}
|
||||
"""
|
||||
|
||||
session.execute(text(sql), record)
|
||||
saved_count += 1
|
||||
|
||||
session.commit()
|
||||
self.logger.debug(f"保存 {saved_count} 条记录到 {table_name}")
|
||||
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
self.logger.error(f"保存指标数据到 {table_name} 失败: {e}")
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
return saved_count
|
||||
|
||||
def _get_indicator_table_name(self, period: str, indicator_name: str) -> str:
|
||||
"""获取指标表名
|
||||
|
||||
Args:
|
||||
period: 数据周期
|
||||
indicator_name: 指标名称
|
||||
|
||||
Returns:
|
||||
表名,格式: indicators_{period}_{indicator_name}
|
||||
"""
|
||||
return f"indicators_{period}_{indicator_name}"
|
||||
|
||||
def _ensure_table_exists(self, table_name: str, indicator_columns: List[str]):
|
||||
"""确保指标表存在,如果不存在则创建
|
||||
|
||||
Args:
|
||||
table_name: 表名
|
||||
indicator_columns: 指标列名列表
|
||||
"""
|
||||
from src.database_manager import DatabaseManager
|
||||
|
||||
db_manager = DatabaseManager()
|
||||
|
||||
if not db_manager.table_exists(self.database, table_name):
|
||||
self.logger.warning(f"表 {table_name} 不存在,正在创建...")
|
||||
|
||||
# 构建列定义
|
||||
columns = [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "INT",
|
||||
"nullable": False,
|
||||
"primary_key": True,
|
||||
"auto_increment": True,
|
||||
},
|
||||
{
|
||||
"name": "symbol",
|
||||
"type": "VARCHAR(20)",
|
||||
"nullable": False,
|
||||
},
|
||||
{
|
||||
"name": "timestamp",
|
||||
"type": "DATETIME",
|
||||
"nullable": False,
|
||||
},
|
||||
]
|
||||
|
||||
# 添加指标列
|
||||
for col in indicator_columns:
|
||||
columns.append(
|
||||
{
|
||||
"name": col,
|
||||
"type": "DECIMAL(20, 6)",
|
||||
"nullable": True,
|
||||
}
|
||||
)
|
||||
|
||||
# 定义索引
|
||||
indexes = [
|
||||
{
|
||||
"name": f"idx_{table_name}_symbol_timestamp",
|
||||
"columns": ["symbol", "timestamp"],
|
||||
"unique": True,
|
||||
}
|
||||
]
|
||||
|
||||
# 创建表
|
||||
db_manager.create_table(
|
||||
database=self.database,
|
||||
table_name=table_name,
|
||||
columns=columns,
|
||||
indexes=indexes,
|
||||
)
|
||||
|
||||
self.logger.info(f"成功创建表: {table_name}")
|
||||
|
||||
db_manager.close()
|
||||
|
||||
def close(self):
|
||||
"""关闭数据库连接"""
|
||||
if hasattr(self, "engine"):
|
||||
self.engine.dispose()
|
||||
self.logger.info("IndicatorWriter数据库连接已关闭")
|
||||
163
src/data_provider/data_writer/kline_writer.py
Normal file
163
src/data_provider/data_writer/kline_writer.py
Normal file
@ -0,0 +1,163 @@
|
||||
"""K线数据持久化类"""
|
||||
|
||||
from typing import Dict
|
||||
import pandas as pd
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from src.core.logger import Logger
|
||||
from src.core.config import Config
|
||||
|
||||
|
||||
class KlineWriter:
|
||||
"""K线数据持久化类
|
||||
|
||||
负责将K线数据保存到数据库
|
||||
"""
|
||||
|
||||
def __init__(self, database: str | None = None):
|
||||
"""初始化K线数据写入器
|
||||
|
||||
Args:
|
||||
database: 目标数据库名,默认从配置读取
|
||||
"""
|
||||
self.logger = Logger()
|
||||
self.config = Config()
|
||||
self.database = database or self.config.get("database.database")
|
||||
|
||||
if not self.database:
|
||||
raise ValueError(
|
||||
"未指定目标数据库,请在配置文件中设置 database.database 或通过参数传入"
|
||||
)
|
||||
|
||||
# 创建数据库引擎
|
||||
self.engine = self._create_engine()
|
||||
self.Session = sessionmaker(bind=self.engine)
|
||||
|
||||
self.logger.info(f"KlineWriter初始化完成,目标数据库: {self.database}")
|
||||
|
||||
def _create_engine(self):
|
||||
"""创建数据库引擎"""
|
||||
host = self.config.get("database.host", "127.0.0.1")
|
||||
port = self.config.get("database.port", 3306)
|
||||
user = self.config.get("database.user", "root")
|
||||
password = self.config.get("database.password", "")
|
||||
|
||||
connection_url = (
|
||||
f"mysql+pymysql://{user}:{password}@"
|
||||
f"{host}:{port}/{self.database}?charset=utf8mb4"
|
||||
)
|
||||
return create_engine(connection_url, echo=False, pool_pre_ping=True)
|
||||
|
||||
def save(self, kline_data: Dict[str, pd.DataFrame]) -> Dict[str, int]:
|
||||
"""保存K线数据到数据库
|
||||
|
||||
Args:
|
||||
kline_data: K线数据字典,格式: {f"{symbol}_{period}": DataFrame}
|
||||
DataFrame需包含列: symbol, timestamp, open, high, low, close, volume, amount
|
||||
|
||||
Returns:
|
||||
保存结果字典,格式: {key: saved_count}
|
||||
"""
|
||||
results = {}
|
||||
|
||||
for key, df in kline_data.items():
|
||||
try:
|
||||
# 从key解析出symbol和period
|
||||
parts = key.rsplit("_", 1)
|
||||
if len(parts) != 2:
|
||||
self.logger.warning(f"无效的key格式: {key},跳过")
|
||||
continue
|
||||
|
||||
symbol, period = parts
|
||||
saved_count = self._save_single(df, period)
|
||||
results[key] = saved_count
|
||||
|
||||
self.logger.info(f"保存 {key}: {saved_count} 条记录")
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"保存 {key} 失败: {e}")
|
||||
results[key] = 0
|
||||
|
||||
return results
|
||||
|
||||
def _save_single(self, df: pd.DataFrame, period: str) -> int:
|
||||
"""保存单个股票的K线数据
|
||||
|
||||
Args:
|
||||
df: K线数据DataFrame
|
||||
period: 数据周期
|
||||
|
||||
Returns:
|
||||
保存的记录数
|
||||
"""
|
||||
if df.empty:
|
||||
return 0
|
||||
|
||||
# 验证必需的列
|
||||
required_columns = [
|
||||
"symbol",
|
||||
"timestamp",
|
||||
"open",
|
||||
"high",
|
||||
"low",
|
||||
"close",
|
||||
"volume",
|
||||
"amount",
|
||||
]
|
||||
missing_columns = [col for col in required_columns if col not in df.columns]
|
||||
if missing_columns:
|
||||
raise ValueError(f"DataFrame缺少必需的列: {missing_columns}")
|
||||
|
||||
session = self.Session()
|
||||
saved_count = 0
|
||||
|
||||
# 获取表名
|
||||
from src.database_manager.table_utils import get_kline_table_name
|
||||
|
||||
table_name = get_kline_table_name(period)
|
||||
|
||||
try:
|
||||
for _, row in df.iterrows():
|
||||
record = {
|
||||
"symbol": row["symbol"],
|
||||
"timestamp": row["timestamp"],
|
||||
"open": float(row["open"]),
|
||||
"high": float(row["high"]),
|
||||
"low": float(row["low"]),
|
||||
"close": float(row["close"]),
|
||||
"volume": float(row["volume"]),
|
||||
"amount": float(row["amount"]),
|
||||
}
|
||||
|
||||
# 使用 INSERT ... ON DUPLICATE KEY UPDATE
|
||||
sql = f"""
|
||||
INSERT INTO {table_name}
|
||||
(symbol, timestamp, open, high, low, close, volume, amount)
|
||||
VALUES
|
||||
(:symbol, :timestamp, :open, :high, :low, :close, :volume, :amount)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
open=VALUES(open), high=VALUES(high), low=VALUES(low),
|
||||
close=VALUES(close), volume=VALUES(volume), amount=VALUES(amount)
|
||||
"""
|
||||
|
||||
session.execute(text(sql), record)
|
||||
saved_count += 1
|
||||
|
||||
session.commit()
|
||||
self.logger.debug(f"保存 {saved_count} 条记录到 {table_name}")
|
||||
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
self.logger.error(f"保存数据到 {table_name} 失败: {e}")
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
return saved_count
|
||||
|
||||
def close(self):
|
||||
"""关闭数据库连接"""
|
||||
if hasattr(self, "engine"):
|
||||
self.engine.dispose()
|
||||
self.logger.info("KlineWriter数据库连接已关闭")
|
||||
15
src/data_provider/indicator_calculator/__init__.py
Normal file
15
src/data_provider/indicator_calculator/__init__.py
Normal file
@ -0,0 +1,15 @@
|
||||
"""技术指标计算模块"""
|
||||
|
||||
from .base_indicator import BaseIndicator
|
||||
from .macd_indicator import MACDIndicator
|
||||
from .kdj_indicator import KDJIndicator
|
||||
from .boll_indicator import BOLLIndicator
|
||||
from .indicator_manager import IndicatorManager
|
||||
|
||||
__all__ = [
|
||||
"BaseIndicator",
|
||||
"MACDIndicator",
|
||||
"KDJIndicator",
|
||||
"BOLLIndicator",
|
||||
"IndicatorManager",
|
||||
]
|
||||
102
src/data_provider/indicator_calculator/base_indicator.py
Normal file
102
src/data_provider/indicator_calculator/base_indicator.py
Normal file
@ -0,0 +1,102 @@
|
||||
"""技术指标计算基类"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Dict, List
|
||||
import pandas as pd
|
||||
|
||||
|
||||
class BaseIndicator(ABC):
|
||||
"""技术指标计算基类
|
||||
|
||||
所有技术指标计算器都应该继承此类,实现calculate方法
|
||||
"""
|
||||
|
||||
def __init__(self, config: Dict | None = None):
|
||||
"""初始化指标计算器
|
||||
|
||||
Args:
|
||||
config: 指标参数配置,如 MACD的快慢线参数等
|
||||
"""
|
||||
self.config = config or {}
|
||||
self._validate_config()
|
||||
|
||||
@abstractmethod
|
||||
def _validate_config(self):
|
||||
"""验证配置参数的合法性
|
||||
|
||||
子类需要实现此方法,检查必需的参数是否存在,参数值是否合法
|
||||
如果配置不合法,应该抛出 ValueError
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def calculate(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""计算技术指标
|
||||
|
||||
Args:
|
||||
df: 包含K线数据的DataFrame,至少需要包含以下列:
|
||||
- open: 开盘价
|
||||
- high: 最高价
|
||||
- low: 最低价
|
||||
- close: 收盘价
|
||||
- volume: 成交量
|
||||
- timestamp: 时间戳
|
||||
|
||||
Returns:
|
||||
添加了指标列的DataFrame,原始K线数据列保持不变
|
||||
新增的指标列名应该遵循规范:{indicator_name}_{param}
|
||||
例如:macd_dif, macd_dea, macd_histogram
|
||||
|
||||
Raises:
|
||||
ValueError: 如果输入数据不符合要求
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_column_names(self) -> List[str]:
|
||||
"""获取此指标会添加的列名列表
|
||||
|
||||
Returns:
|
||||
指标列名列表,用于数据库表结构创建和数据验证
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def name(self) -> str:
|
||||
"""指标名称
|
||||
|
||||
Returns:
|
||||
指标的唯一标识名称,如 'macd', 'kdj', 'boll'
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
"""指标描述
|
||||
|
||||
Returns:
|
||||
指标的中文描述,如 'MACD指标'
|
||||
"""
|
||||
return self.name
|
||||
|
||||
def _validate_dataframe(self, df: pd.DataFrame):
|
||||
"""验证输入的DataFrame是否符合要求
|
||||
|
||||
Args:
|
||||
df: 待验证的DataFrame
|
||||
|
||||
Raises:
|
||||
ValueError: 如果DataFrame缺少必需的列
|
||||
"""
|
||||
required_columns = ["open", "high", "low", "close", "volume", "timestamp"]
|
||||
missing_columns = [col for col in required_columns if col not in df.columns]
|
||||
|
||||
if missing_columns:
|
||||
raise ValueError(
|
||||
f"DataFrame缺少必需的列: {missing_columns}. "
|
||||
f"需要的列: {required_columns}"
|
||||
)
|
||||
|
||||
if len(df) == 0:
|
||||
raise ValueError("DataFrame不能为空")
|
||||
85
src/data_provider/indicator_calculator/boll_indicator.py
Normal file
85
src/data_provider/indicator_calculator/boll_indicator.py
Normal file
@ -0,0 +1,85 @@
|
||||
"""布林带指标计算器"""
|
||||
|
||||
from typing import Dict, List
|
||||
import pandas as pd
|
||||
from .base_indicator import BaseIndicator
|
||||
|
||||
|
||||
class BOLLIndicator(BaseIndicator):
|
||||
"""BOLL(Bollinger Bands,布林带)指标计算器
|
||||
|
||||
布林带指标包含三条线:
|
||||
- 中轨:N日移动平均线
|
||||
- 上轨:中轨 + K倍标准差
|
||||
- 下轨:中轨 - K倍标准差
|
||||
"""
|
||||
|
||||
def __init__(self, config: Dict | None = None):
|
||||
"""初始化BOLL指标计算器
|
||||
|
||||
Args:
|
||||
config: 配置参数,包含:
|
||||
- period: 移动平均周期,默认20
|
||||
- std_multiplier: 标准差倍数,默认2
|
||||
"""
|
||||
super().__init__(config)
|
||||
|
||||
def _validate_config(self):
|
||||
"""验证配置参数"""
|
||||
# 设置默认值
|
||||
self.config.setdefault("period", 20)
|
||||
self.config.setdefault("std_multiplier", 2.0)
|
||||
|
||||
# 验证参数
|
||||
if self.config["period"] <= 0:
|
||||
raise ValueError("period必须大于0")
|
||||
if self.config["std_multiplier"] <= 0:
|
||||
raise ValueError("std_multiplier必须大于0")
|
||||
|
||||
def calculate(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""计算BOLL指标
|
||||
|
||||
Args:
|
||||
df: K线数据DataFrame
|
||||
|
||||
Returns:
|
||||
添加了BOLL指标列的DataFrame
|
||||
"""
|
||||
self._validate_dataframe(df)
|
||||
|
||||
# 复制DataFrame避免修改原始数据
|
||||
result = df.copy()
|
||||
|
||||
period = self.config["period"]
|
||||
std_multiplier = self.config["std_multiplier"]
|
||||
|
||||
# 计算中轨(移动平均线)
|
||||
result["boll_mid"] = (
|
||||
result["close"].rolling(window=period, min_periods=1).mean()
|
||||
)
|
||||
|
||||
# 计算标准差
|
||||
std = result["close"].rolling(window=period, min_periods=1).std()
|
||||
|
||||
# 计算上轨和下轨
|
||||
result["boll_upper"] = result["boll_mid"] + std_multiplier * std
|
||||
result["boll_lower"] = result["boll_mid"] - std_multiplier * std
|
||||
|
||||
# 计算布林带宽度(可选,用于判断波动性)
|
||||
result["boll_width"] = result["boll_upper"] - result["boll_lower"]
|
||||
|
||||
return result
|
||||
|
||||
def get_column_names(self) -> List[str]:
|
||||
"""获取BOLL指标的列名"""
|
||||
return ["boll_upper", "boll_mid", "boll_lower", "boll_width"]
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""指标名称"""
|
||||
return "boll"
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
"""指标描述"""
|
||||
return "BOLL指标(布林带)"
|
||||
170
src/data_provider/indicator_calculator/indicator_manager.py
Normal file
170
src/data_provider/indicator_calculator/indicator_manager.py
Normal file
@ -0,0 +1,170 @@
|
||||
"""技术指标管理器"""
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
import pandas as pd
|
||||
from src.core.logger import Logger
|
||||
from .base_indicator import BaseIndicator
|
||||
from .macd_indicator import MACDIndicator
|
||||
from .kdj_indicator import KDJIndicator
|
||||
from .boll_indicator import BOLLIndicator
|
||||
|
||||
|
||||
class IndicatorManager:
|
||||
"""技术指标管理器
|
||||
|
||||
负责管理和批量计算多个技术指标
|
||||
"""
|
||||
|
||||
# 内置指标映射
|
||||
INDICATOR_MAP = {
|
||||
"macd": MACDIndicator,
|
||||
"kdj": KDJIndicator,
|
||||
"boll": BOLLIndicator,
|
||||
}
|
||||
|
||||
def __init__(self, indicator_configs: Dict[str, Dict] | None = None):
|
||||
"""初始化指标管理器
|
||||
|
||||
Args:
|
||||
indicator_configs: 指标配置字典,格式:
|
||||
{
|
||||
'macd': {'fast_period': 12, 'slow_period': 26, 'signal_period': 9},
|
||||
'kdj': {'period': 9, 'k_period': 3, 'd_period': 3},
|
||||
'boll': {'period': 20, 'std_multiplier': 2.0}
|
||||
}
|
||||
"""
|
||||
self.logger = Logger()
|
||||
self.indicator_configs = indicator_configs or {}
|
||||
self.indicators: Dict[str, BaseIndicator] = {}
|
||||
|
||||
# 初始化配置的指标
|
||||
self._init_indicators()
|
||||
|
||||
def _init_indicators(self):
|
||||
"""根据配置初始化指标计算器"""
|
||||
for indicator_name, config in self.indicator_configs.items():
|
||||
if indicator_name in self.INDICATOR_MAP:
|
||||
try:
|
||||
indicator_class = self.INDICATOR_MAP[indicator_name]
|
||||
self.indicators[indicator_name] = indicator_class(config)
|
||||
self.logger.info(f"初始化指标: {indicator_name}, 配置: {config}")
|
||||
except Exception as e:
|
||||
self.logger.error(f"初始化指标 {indicator_name} 失败: {e}")
|
||||
else:
|
||||
self.logger.warning(f"未知的指标类型: {indicator_name}")
|
||||
|
||||
def add_indicator(self, indicator_name: str, config: Dict | None = None):
|
||||
"""添加指标计算器
|
||||
|
||||
Args:
|
||||
indicator_name: 指标名称,如 'macd', 'kdj', 'boll'
|
||||
config: 指标配置参数
|
||||
|
||||
Raises:
|
||||
ValueError: 如果指标名称不存在
|
||||
"""
|
||||
if indicator_name not in self.INDICATOR_MAP:
|
||||
raise ValueError(
|
||||
f"未知的指标类型: {indicator_name}. "
|
||||
f"支持的指标: {list(self.INDICATOR_MAP.keys())}"
|
||||
)
|
||||
|
||||
indicator_class = self.INDICATOR_MAP[indicator_name]
|
||||
self.indicators[indicator_name] = indicator_class(config)
|
||||
self.logger.info(f"添加指标: {indicator_name}, 配置: {config}")
|
||||
|
||||
def remove_indicator(self, indicator_name: str):
|
||||
"""移除指标计算器
|
||||
|
||||
Args:
|
||||
indicator_name: 指标名称
|
||||
"""
|
||||
if indicator_name in self.indicators:
|
||||
del self.indicators[indicator_name]
|
||||
self.logger.info(f"移除指标: {indicator_name}")
|
||||
|
||||
def calculate_all(
|
||||
self, kline_data: Dict[str, pd.DataFrame]
|
||||
) -> Dict[str, pd.DataFrame]:
|
||||
"""为所有股票计算所有配置的指标
|
||||
|
||||
Args:
|
||||
kline_data: K线数据字典,格式: {stock_code: DataFrame}
|
||||
|
||||
Returns:
|
||||
添加了指标列的K线数据字典
|
||||
"""
|
||||
result = {}
|
||||
|
||||
for stock_code, df in kline_data.items():
|
||||
try:
|
||||
result[stock_code] = self.calculate(df)
|
||||
self.logger.debug(f"成功计算 {stock_code} 的所有指标")
|
||||
except Exception as e:
|
||||
self.logger.error(f"计算 {stock_code} 的指标时出错: {e}")
|
||||
# 计算失败时返回原始数据
|
||||
result[stock_code] = df
|
||||
|
||||
return result
|
||||
|
||||
def calculate(
|
||||
self, df: pd.DataFrame, indicator_names: Optional[List[str]] = None
|
||||
) -> pd.DataFrame:
|
||||
"""为单个DataFrame计算指标
|
||||
|
||||
Args:
|
||||
df: K线数据DataFrame
|
||||
indicator_names: 要计算的指标名称列表,None表示计算所有已配置的指标
|
||||
|
||||
Returns:
|
||||
添加了指标列的DataFrame
|
||||
"""
|
||||
result = df.copy()
|
||||
|
||||
# 确定要计算的指标
|
||||
indicators_to_calc = indicator_names or list(self.indicators.keys())
|
||||
|
||||
# 依次计算每个指标
|
||||
for indicator_name in indicators_to_calc:
|
||||
if indicator_name not in self.indicators:
|
||||
self.logger.warning(f"指标 {indicator_name} 未配置,跳过")
|
||||
continue
|
||||
|
||||
try:
|
||||
indicator = self.indicators[indicator_name]
|
||||
result = indicator.calculate(result)
|
||||
self.logger.debug(f"成功计算指标: {indicator_name}")
|
||||
except Exception as e:
|
||||
self.logger.error(f"计算指标 {indicator_name} 时出错: {e}")
|
||||
# 继续计算其他指标
|
||||
continue
|
||||
|
||||
return result
|
||||
|
||||
def get_all_column_names(self) -> Dict[str, List[str]]:
|
||||
"""获取所有指标的列名
|
||||
|
||||
Returns:
|
||||
指标列名字典,格式: {indicator_name: [column_names]}
|
||||
"""
|
||||
return {
|
||||
name: indicator.get_column_names()
|
||||
for name, indicator in self.indicators.items()
|
||||
}
|
||||
|
||||
def get_enabled_indicators(self) -> List[str]:
|
||||
"""获取已启用的指标列表
|
||||
|
||||
Returns:
|
||||
指标名称列表
|
||||
"""
|
||||
return list(self.indicators.keys())
|
||||
|
||||
@classmethod
|
||||
def get_supported_indicators(cls) -> List[str]:
|
||||
"""获取支持的指标类型列表
|
||||
|
||||
Returns:
|
||||
支持的指标名称列表
|
||||
"""
|
||||
return list(cls.INDICATOR_MAP.keys())
|
||||
95
src/data_provider/indicator_calculator/kdj_indicator.py
Normal file
95
src/data_provider/indicator_calculator/kdj_indicator.py
Normal file
@ -0,0 +1,95 @@
|
||||
"""KDJ指标计算器"""
|
||||
|
||||
from typing import Dict, List
|
||||
import pandas as pd
|
||||
from .base_indicator import BaseIndicator
|
||||
|
||||
|
||||
class KDJIndicator(BaseIndicator):
|
||||
"""KDJ(随机指标)计算器
|
||||
|
||||
KDJ指标包含三个值:
|
||||
- K值:快速指标
|
||||
- D值:慢速指标
|
||||
- J值:乖离指标
|
||||
"""
|
||||
|
||||
def __init__(self, config: Dict | None = None):
|
||||
"""初始化KDJ指标计算器
|
||||
|
||||
Args:
|
||||
config: 配置参数,包含:
|
||||
- period: RSV计算周期,默认9
|
||||
- k_period: K值平滑周期,默认3
|
||||
- d_period: D值平滑周期,默认3
|
||||
"""
|
||||
super().__init__(config)
|
||||
|
||||
def _validate_config(self):
|
||||
"""验证配置参数"""
|
||||
# 设置默认值
|
||||
self.config.setdefault("period", 9)
|
||||
self.config.setdefault("k_period", 3)
|
||||
self.config.setdefault("d_period", 3)
|
||||
|
||||
# 验证参数
|
||||
if self.config["period"] <= 0:
|
||||
raise ValueError("period必须大于0")
|
||||
if self.config["k_period"] <= 0:
|
||||
raise ValueError("k_period必须大于0")
|
||||
if self.config["d_period"] <= 0:
|
||||
raise ValueError("d_period必须大于0")
|
||||
|
||||
def calculate(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""计算KDJ指标
|
||||
|
||||
Args:
|
||||
df: K线数据DataFrame
|
||||
|
||||
Returns:
|
||||
添加了KDJ指标列的DataFrame
|
||||
"""
|
||||
self._validate_dataframe(df)
|
||||
|
||||
# 复制DataFrame避免修改原始数据
|
||||
result = df.copy()
|
||||
|
||||
period = self.config["period"]
|
||||
k_period = self.config["k_period"]
|
||||
d_period = self.config["d_period"]
|
||||
|
||||
# 计算RSV(未成熟随机值)
|
||||
low_min = result["low"].rolling(window=period, min_periods=1).min()
|
||||
high_max = result["high"].rolling(window=period, min_periods=1).max()
|
||||
|
||||
rsv = ((result["close"] - low_min) / (high_max - low_min)) * 100
|
||||
# 处理除以0的情况
|
||||
rsv = rsv.fillna(50)
|
||||
|
||||
# 计算K值(RSV的移动平均)
|
||||
# K = (2/3) * prev_K + (1/3) * RSV
|
||||
result["kdj_k"] = rsv.ewm(alpha=1 / k_period, adjust=False).mean()
|
||||
|
||||
# 计算D值(K值的移动平均)
|
||||
# D = (2/3) * prev_D + (1/3) * K
|
||||
result["kdj_d"] = result["kdj_k"].ewm(alpha=1 / d_period, adjust=False).mean()
|
||||
|
||||
# 计算J值
|
||||
# J = 3K - 2D
|
||||
result["kdj_j"] = 3 * result["kdj_k"] - 2 * result["kdj_d"]
|
||||
|
||||
return result
|
||||
|
||||
def get_column_names(self) -> List[str]:
|
||||
"""获取KDJ指标的列名"""
|
||||
return ["kdj_k", "kdj_d", "kdj_j"]
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""指标名称"""
|
||||
return "kdj"
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
"""指标描述"""
|
||||
return "KDJ指标(随机指标)"
|
||||
95
src/data_provider/indicator_calculator/macd_indicator.py
Normal file
95
src/data_provider/indicator_calculator/macd_indicator.py
Normal file
@ -0,0 +1,95 @@
|
||||
"""MACD指标计算器"""
|
||||
|
||||
from typing import Dict, List
|
||||
import pandas as pd
|
||||
from .base_indicator import BaseIndicator
|
||||
|
||||
|
||||
class MACDIndicator(BaseIndicator):
|
||||
"""MACD(Moving Average Convergence Divergence)指标计算器
|
||||
|
||||
MACD指标包含三个值:
|
||||
- DIF(差离值):快速EMA - 慢速EMA
|
||||
- DEA(讯号线):DIF的EMA
|
||||
- MACD柱状图:(DIF - DEA) * 2
|
||||
"""
|
||||
|
||||
def __init__(self, config: Dict | None = None):
|
||||
"""初始化MACD指标计算器
|
||||
|
||||
Args:
|
||||
config: 配置参数,包含:
|
||||
- fast_period: 快速EMA周期,默认12
|
||||
- slow_period: 慢速EMA周期,默认26
|
||||
- signal_period: 信号线周期,默认9
|
||||
"""
|
||||
super().__init__(config)
|
||||
|
||||
def _validate_config(self):
|
||||
"""验证配置参数"""
|
||||
# 设置默认值
|
||||
self.config.setdefault("fast_period", 12)
|
||||
self.config.setdefault("slow_period", 26)
|
||||
self.config.setdefault("signal_period", 9)
|
||||
|
||||
# 验证参数
|
||||
if self.config["fast_period"] <= 0:
|
||||
raise ValueError("fast_period必须大于0")
|
||||
if self.config["slow_period"] <= 0:
|
||||
raise ValueError("slow_period必须大于0")
|
||||
if self.config["signal_period"] <= 0:
|
||||
raise ValueError("signal_period必须大于0")
|
||||
if self.config["fast_period"] >= self.config["slow_period"]:
|
||||
raise ValueError("fast_period必须小于slow_period")
|
||||
|
||||
def calculate(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""计算MACD指标
|
||||
|
||||
Args:
|
||||
df: K线数据DataFrame
|
||||
|
||||
Returns:
|
||||
添加了MACD指标列的DataFrame
|
||||
"""
|
||||
self._validate_dataframe(df)
|
||||
|
||||
# 复制DataFrame避免修改原始数据
|
||||
result = df.copy()
|
||||
|
||||
# 获取收盘价
|
||||
close = result["close"]
|
||||
|
||||
# 计算快速和慢速EMA
|
||||
fast_period = self.config["fast_period"]
|
||||
slow_period = self.config["slow_period"]
|
||||
signal_period = self.config["signal_period"]
|
||||
|
||||
ema_fast = close.ewm(span=fast_period, adjust=False).mean()
|
||||
ema_slow = close.ewm(span=slow_period, adjust=False).mean()
|
||||
|
||||
# 计算DIF
|
||||
result["macd_dif"] = ema_fast - ema_slow
|
||||
|
||||
# 计算DEA(DIF的EMA)
|
||||
result["macd_dea"] = (
|
||||
result["macd_dif"].ewm(span=signal_period, adjust=False).mean()
|
||||
)
|
||||
|
||||
# 计算MACD柱状图
|
||||
result["macd_histogram"] = (result["macd_dif"] - result["macd_dea"]) * 2
|
||||
|
||||
return result
|
||||
|
||||
def get_column_names(self) -> List[str]:
|
||||
"""获取MACD指标的列名"""
|
||||
return ["macd_dif", "macd_dea", "macd_histogram"]
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""指标名称"""
|
||||
return "macd"
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
"""指标描述"""
|
||||
return "MACD指标(异同移动平均线)"
|
||||
90
src/main.py
90
src/main.py
@ -1,10 +1,9 @@
|
||||
"""
|
||||
QTrade 主程序
|
||||
下载历史数据
|
||||
演示数据下载和技术指标计算功能
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
@ -20,8 +19,74 @@ from src.data_provider import DataProvider
|
||||
logger = get_logger("Main")
|
||||
|
||||
|
||||
def download_historical_data_with_indicators():
|
||||
"""下载历史数据并计算技术指标"""
|
||||
|
||||
logger.info("=" * 60)
|
||||
logger.info("开始下载历史数据并计算技术指标")
|
||||
logger.info("=" * 60)
|
||||
|
||||
# 股票列表:邮储银行、创业板ETF
|
||||
symbols = [
|
||||
"601658.SH", # 邮储银行
|
||||
"159915.SZ", # 创业板ETF
|
||||
]
|
||||
|
||||
# 时间范围:2025-12-01 到 2025-12-15
|
||||
start_date = datetime(2025, 12, 1)
|
||||
end_date = datetime(2025, 12, 15)
|
||||
|
||||
# 周期:1分钟和日线数据
|
||||
periods = ["1m", "1d"]
|
||||
|
||||
logger.info("\n下载配置:")
|
||||
logger.info(f" 股票代码: {', '.join(symbols)}")
|
||||
logger.info(f" 时间范围: {start_date.date()} ~ {end_date.date()}")
|
||||
logger.info(f" 数据周期: {', '.join(periods)}")
|
||||
|
||||
try:
|
||||
# 使用 DataProvider 下载数据并计算指标
|
||||
with DataProvider() as provider:
|
||||
# 新方法:下载、计算指标、保存一体化
|
||||
klines_with_indicators = provider.download_klines_with_indicators(
|
||||
symbols=symbols,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
periods=periods,
|
||||
calculate_indicators=True,
|
||||
save_indicators=True,
|
||||
)
|
||||
|
||||
logger.info("\n下载和指标计算结果:")
|
||||
total_records = sum(len(df) for df in klines_with_indicators.values())
|
||||
logger.info(f" 总数据集: {len(klines_with_indicators)}")
|
||||
logger.info(f" 总记录数: {total_records}")
|
||||
|
||||
# 显示详细信息
|
||||
logger.info("\n详细信息:")
|
||||
for key, df in klines_with_indicators.items():
|
||||
if not df.empty:
|
||||
indicator_cols = [col for col in df.columns if any(
|
||||
col.startswith(ind) for ind in ['macd_', 'kdj_', 'boll_']
|
||||
)]
|
||||
logger.info(f" ✓ {key}: {len(df)} 条, 指标列: {len(indicator_cols)}")
|
||||
logger.info(f" - 指标: {', '.join(indicator_cols[:5])}...")
|
||||
else:
|
||||
logger.info(f" ✗ {key}: 无数据")
|
||||
|
||||
logger.info(f"\n{'=' * 60}")
|
||||
logger.info("历史数据下载和指标计算完成")
|
||||
logger.info(f"{'=' * 60}")
|
||||
|
||||
return klines_with_indicators
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"下载失败: {e}", exc_info=True)
|
||||
raise
|
||||
|
||||
|
||||
def download_historical_data():
|
||||
"""下载历史数据"""
|
||||
"""下载历史数据(不计算指标)"""
|
||||
|
||||
logger.info("=" * 60)
|
||||
logger.info("开始下载历史数据")
|
||||
@ -196,6 +261,14 @@ def main():
|
||||
set_config(config)
|
||||
logger.info(f"✓ 配置加载完成: {config.get('app.name')}")
|
||||
|
||||
# 检查指标计算配置
|
||||
indicators_enabled = config.get("indicators.enabled", False)
|
||||
if indicators_enabled:
|
||||
enabled_indicators = config.get("indicators.enabled_indicators", [])
|
||||
logger.info(f"✓ 指标计算已启用: {', '.join(enabled_indicators)}")
|
||||
else:
|
||||
logger.info("✗ 指标计算未启用")
|
||||
|
||||
# 第一步:尝试查询已有数据(如果表不存在会报错,直接跳到下载)
|
||||
logger.info("\n" + "=" * 60)
|
||||
logger.info("第一步:查询数据库中的现有数据")
|
||||
@ -234,8 +307,15 @@ def main():
|
||||
logger.error("\n" + "=" * 60)
|
||||
return
|
||||
|
||||
# 下载数据
|
||||
download_historical_data()
|
||||
# 根据配置选择下载方式
|
||||
if indicators_enabled:
|
||||
# 下载数据并计算指标
|
||||
logger.info("使用指标计算模式下载数据...")
|
||||
download_historical_data_with_indicators()
|
||||
else:
|
||||
# 仅下载数据
|
||||
logger.info("使用普通模式下载数据...")
|
||||
download_historical_data()
|
||||
|
||||
# 第三步:验证下载的数据
|
||||
logger.info("\n" + "=" * 60)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user