Compare commits
2 Commits
ac8404a66d
...
423a2bbce5
| Author | SHA1 | Date | |
|---|---|---|---|
| 423a2bbce5 | |||
| e479a664a5 |
@ -1,4 +1,3 @@
|
||||
import os
|
||||
import datetime
|
||||
import pandas as pd
|
||||
from xtquant import xtdata
|
||||
@ -6,9 +5,9 @@ import time
|
||||
|
||||
# 导入公共配置
|
||||
from common import (
|
||||
normalize_stock_code, get_table_name, get_cache_key,
|
||||
LOG_PREFIXES, KLINE_COLUMNS, TimeFrame, DataSource,
|
||||
TIME_FORMATS, standardize_timestamp
|
||||
normalize_stock_code,
|
||||
LOG_PREFIXES, KLINE_COLUMNS, TimeFrame,
|
||||
TIME_FORMATS
|
||||
)
|
||||
|
||||
# 导入新的双层架构模块
|
||||
@ -44,11 +43,6 @@ g_end_date = current_time.strftime("%Y%m%d%H%M%S")
|
||||
|
||||
print(f"{LOG_PREFIXES['TIME']} 数据范围: {g_start_date} ~ {g_end_date}")
|
||||
|
||||
# CSV文件保存控制变量
|
||||
# 说明:设置为 True 启用CSV文件保存,False 则只保存到MySQL数据库
|
||||
# 建议:日常使用设为 False 节省磁盘空间,需要分析时临时改为 True
|
||||
g_save_csv = False # 默认不保存CSV文件,如需保存请设置为True
|
||||
|
||||
# 数据库插入模式配置
|
||||
# 说明:控制数据保存策略,提升插入性能
|
||||
# - "incremental": 增量模式,只插入新数据,跳过已存在的记录 (推荐)
|
||||
@ -187,48 +181,6 @@ def conv_time(ct):
|
||||
return time_stamp
|
||||
|
||||
|
||||
def save_dataframe_to_csv(df, stock_code, period, output_dir="data"):
|
||||
"""
|
||||
将pandas DataFrame保存为CSV文件
|
||||
使用公共配置的标准化函数确保文件名一致性
|
||||
|
||||
Args:
|
||||
df (pd.DataFrame): 要保存的pandas DataFrame对象
|
||||
stock_code (str): 股票代码,如 "601658.SH", "000001.SZ"
|
||||
period (str): 数据周期标识,如 "1m", "5m", "1d"
|
||||
output_dir (str, optional): 输出目录路径,默认为 "data"
|
||||
|
||||
Returns:
|
||||
str or None: 成功时返回保存的CSV文件完整路径;
|
||||
失败或DataFrame为空时返回None
|
||||
"""
|
||||
try:
|
||||
if df.empty:
|
||||
return None
|
||||
|
||||
# 使用公共配置标准化股票代码
|
||||
normalized_code = normalize_stock_code(stock_code)
|
||||
|
||||
# 生成CSV文件名,添加微秒以避免重复
|
||||
timestamp = datetime.datetime.now().strftime(TIME_FORMATS['COMPACT'])
|
||||
# 清理股票代码中的特殊字符,避免文件名问题
|
||||
clean_stock_code = normalized_code.replace(".", "_").replace("/", "_")
|
||||
csv_filename = f"{clean_stock_code}_{period}_{timestamp}.csv"
|
||||
csv_path = os.path.join(output_dir, csv_filename)
|
||||
|
||||
# 确保输出目录存在
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
# 保存为CSV
|
||||
df.to_csv(csv_path, encoding="utf-8-sig")
|
||||
|
||||
return csv_path
|
||||
|
||||
except Exception as e:
|
||||
print(f"{LOG_PREFIXES['ERROR']} 保存 {stock_code} 数据失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def download_stock_data(stock_code, period, start_date, end_date):
|
||||
"""
|
||||
下载单个股票的历史数据
|
||||
@ -356,32 +308,6 @@ def process_stock_data(stock_code, stock_data):
|
||||
return df
|
||||
|
||||
|
||||
def save_all_to_csv(processed_data, period, output_dir="data"):
|
||||
"""
|
||||
将所有处理过的股票数据保存为CSV文件
|
||||
|
||||
Args:
|
||||
processed_data (dict): 处理过的股票数据字典 {stock_code: DataFrame}
|
||||
period (str): 数据周期标识,用于文件命名
|
||||
output_dir (str): 输出目录路径,默认为 "data"
|
||||
|
||||
Returns:
|
||||
list: 成功保存的CSV文件路径列表
|
||||
"""
|
||||
csv_files = []
|
||||
|
||||
# 检查全局变量是否启用CSV保存
|
||||
if not g_save_csv:
|
||||
return csv_files
|
||||
|
||||
for stock_code, df in processed_data.items():
|
||||
csv_path = save_dataframe_to_csv(df, stock_code, period, output_dir)
|
||||
if csv_path:
|
||||
csv_files.append(csv_path)
|
||||
|
||||
return csv_files
|
||||
|
||||
|
||||
def save_all_to_mysql(processed_data, data_manager, current_period):
|
||||
"""
|
||||
将所有处理过的股票数据保存到MySQL数据库 - 使用新的双层架构
|
||||
@ -507,15 +433,15 @@ def main():
|
||||
数据处理模型主程序入口函数 (批量周期模式) - 使用新的双层架构
|
||||
|
||||
执行完整的股票数据处理流程,支持批量下载多个周期的数据,
|
||||
包括数据下载、格式化处理、CSV文件保存和MySQL数据库存储
|
||||
包括数据下载、格式化处理和MySQL数据库存储
|
||||
|
||||
主要执行步骤:
|
||||
1. 初始化StockDataManager
|
||||
2. 循环处理所有配置的数据周期
|
||||
3. 对每个周期下载指定股票的历史数据
|
||||
4. 对每个股票的数据进行格式化处理(时间转换、DataFrame化)
|
||||
5. 将处理后的数据保存为CSV文件和MySQL数据库
|
||||
6. 输出处理结果统计和文件路径信息
|
||||
5. 将处理后的数据保存到MySQL数据库
|
||||
6. 输出处理结果统计和信息
|
||||
|
||||
全局配置依赖:
|
||||
- g_stock_code_list: 股票代码列表,如 ["601658.SH", "000001.SZ"]
|
||||
@ -528,17 +454,15 @@ def main():
|
||||
|
||||
Returns:
|
||||
None: 该函数不返回值,所有结果通过控制台输出
|
||||
和CSV文件保存体现
|
||||
|
||||
Side Effects:
|
||||
- 在控制台输出详细的处理进度和结果
|
||||
- 在 "data" 目录下创建多个CSV文件
|
||||
- 建立xtquant数据连接和MySQL数据库连接
|
||||
- 为每个周期创建对应的数据库表
|
||||
|
||||
Raises:
|
||||
KeyboardInterrupt: 用户手动中断程序执行
|
||||
Exception: 数据下载、处理或文件保存过程中的任何异常
|
||||
Exception: 数据下载、处理或数据库保存过程中的任何异常
|
||||
|
||||
Example:
|
||||
>>> # 设置全局配置
|
||||
|
||||
@ -264,7 +264,7 @@ class SharedMemoryKlineCache:
|
||||
print(f"❌ 批量添加K线数据到共享内存失败: {e}")
|
||||
return 0
|
||||
|
||||
def get_kline_data(self, stock_code: str = None, limit: int = 100) -> dict:
|
||||
def get_kline_data(self, stock_code: Optional[str] = None, limit: int = 100) -> dict:
|
||||
"""
|
||||
从共享内存获取K线数据
|
||||
|
||||
@ -351,7 +351,7 @@ class SharedMemoryKlineCache:
|
||||
except Exception as e:
|
||||
return {'status': 'error', 'error': str(e)}
|
||||
|
||||
def clear_cache(self, stock_code: str = None) -> bool:
|
||||
def clear_cache(self, stock_code: Optional[str] = None) -> bool:
|
||||
"""清理缓存数据"""
|
||||
with self.lock:
|
||||
try:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user