chore(config): 添加环境变量示例及.gitignore更新
- 新增 .env.example,包含 Tushare API、钉钉机器人和PostgreSQL数据库配置模板 - 更新.gitignore,忽略本地配置文件如 .env.local 和 config_local.py - 添加对报表文件命名规则的支持,保留示例文件不忽略 - 删除废弃的 chart.py 及相关图表模块代码 - 新增 config/settings.py,实现从环境变量读取配置的统一接口 - 设置数据目录及缓存目录,确保目录存在,提高配置管理规范性
This commit is contained in:
0
core/common/__init__.py
Normal file
0
core/common/__init__.py
Normal file
96
core/common/db.py
Normal file
96
core/common/db.py
Normal file
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
数据库配置和连接工具
|
||||
"""
|
||||
|
||||
import psycopg2
|
||||
from psycopg2.extras import RealDictCursor
|
||||
from sqlalchemy import create_engine
|
||||
import pandas as pd
|
||||
from loguru import logger
|
||||
from typing import Optional
|
||||
|
||||
from config.settings import get_db_config
|
||||
|
||||
|
||||
class DatabaseManager:
|
||||
"""数据库管理类"""
|
||||
|
||||
def __init__(self, config: dict = None):
|
||||
self.config = config or get_db_config()
|
||||
self.engine = None
|
||||
|
||||
def get_engine(self):
|
||||
"""获取SQLAlchemy引擎"""
|
||||
if self.engine is None:
|
||||
conn_str = (
|
||||
f"postgresql://{self.config['username']}:{self.config['password']}"
|
||||
f"@{self.config['host']}:{self.config['port']}/{self.config['database']}"
|
||||
)
|
||||
self.engine = create_engine(
|
||||
conn_str,
|
||||
pool_pre_ping=True,
|
||||
pool_recycle=300,
|
||||
echo=False,
|
||||
)
|
||||
return self.engine
|
||||
|
||||
def get_connection(self):
|
||||
"""获取psycopg2连接"""
|
||||
return psycopg2.connect(
|
||||
host=self.config["host"],
|
||||
port=self.config["port"],
|
||||
database=self.config["database"],
|
||||
user=self.config["username"],
|
||||
password=self.config["password"],
|
||||
)
|
||||
|
||||
def test_connection(self) -> bool:
|
||||
"""测试数据库连接"""
|
||||
try:
|
||||
with self.get_connection() as conn:
|
||||
with conn.cursor() as cursor:
|
||||
cursor.execute("SELECT 1")
|
||||
result = cursor.fetchone()
|
||||
logger.info("数据库连接测试成功")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"数据库连接测试失败: {e}")
|
||||
return False
|
||||
|
||||
def execute_query(self, query: str, params: tuple = None) -> Optional[list]:
|
||||
"""执行查询并返回结果"""
|
||||
try:
|
||||
with self.get_connection() as conn:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cursor:
|
||||
cursor.execute(query, params)
|
||||
result = cursor.fetchall()
|
||||
return [dict(row) for row in result]
|
||||
except Exception as e:
|
||||
logger.error(f"执行查询失败: {e}")
|
||||
return None
|
||||
|
||||
def insert_dataframe(
|
||||
self, df: pd.DataFrame, table_name: str, if_exists: str = "append"
|
||||
) -> bool:
|
||||
"""将DataFrame插入到数据库表"""
|
||||
try:
|
||||
engine = self.get_engine()
|
||||
df.to_sql(
|
||||
table_name,
|
||||
engine,
|
||||
if_exists=if_exists,
|
||||
index=False,
|
||||
method="multi",
|
||||
chunksize=1000,
|
||||
)
|
||||
logger.info(f"成功插入 {len(df)} 条记录到表 {table_name}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"插入数据到表 {table_name} 失败: {e}")
|
||||
return False
|
||||
|
||||
def close(self):
|
||||
"""关闭连接"""
|
||||
if self.engine:
|
||||
self.engine.dispose()
|
||||
self.engine = None
|
||||
210
core/common/notify.py
Normal file
210
core/common/notify.py
Normal file
@@ -0,0 +1,210 @@
|
||||
"""
|
||||
通知模块 - 支持钉钉、日志等多种通知方式
|
||||
"""
|
||||
|
||||
import requests
|
||||
import time
|
||||
import hmac
|
||||
import hashlib
|
||||
import base64
|
||||
import urllib.parse
|
||||
from loguru import logger
|
||||
from typing import Optional
|
||||
|
||||
from config.settings import get_dingtalk_config
|
||||
|
||||
|
||||
class DingTalkBot:
|
||||
"""钉钉机器人类"""
|
||||
|
||||
def __init__(self, webhook: str = None, secret: str = None):
|
||||
"""
|
||||
初始化钉钉机器人
|
||||
|
||||
Args:
|
||||
webhook: 钉钉自定义机器人webhook地址
|
||||
secret: 加签密钥(可选)
|
||||
"""
|
||||
config = get_dingtalk_config()
|
||||
self.webhook = webhook or config.get("webhook", "")
|
||||
self.secret = secret or config.get("secret", "")
|
||||
|
||||
if not self.webhook:
|
||||
logger.warning("钉钉webhook未配置,消息将不会被发送")
|
||||
|
||||
def _gen_signed_url(self) -> str:
|
||||
"""生成带签名的URL"""
|
||||
if not self.secret:
|
||||
return self.webhook
|
||||
|
||||
timestamp = str(round(time.time() * 1000))
|
||||
secret_enc = self.secret.encode("utf-8")
|
||||
string_to_sign = f"{timestamp}\n{self.secret}"
|
||||
string_to_sign_enc = string_to_sign.encode("utf-8")
|
||||
hmac_code = hmac.new(
|
||||
secret_enc, string_to_sign_enc, digestmod=hashlib.sha256
|
||||
).digest()
|
||||
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
return f"{self.webhook}×tamp={timestamp}&sign={sign}"
|
||||
|
||||
def send_text(
|
||||
self, content: str, at_mobiles: list = None, is_at_all: bool = False
|
||||
) -> bool:
|
||||
"""
|
||||
发送文本消息
|
||||
|
||||
Args:
|
||||
content: 消息内容
|
||||
at_mobiles: 需要@的手机号列表
|
||||
is_at_all: 是否@所有人
|
||||
|
||||
Returns:
|
||||
bool: 是否发送成功
|
||||
"""
|
||||
if not self.webhook:
|
||||
logger.warning(f"[钉钉消息未发送] {content[:100]}...")
|
||||
return False
|
||||
|
||||
at_mobiles = at_mobiles or []
|
||||
data = {
|
||||
"msgtype": "text",
|
||||
"text": {"content": content},
|
||||
"at": {"atMobiles": at_mobiles, "isAtAll": is_at_all},
|
||||
}
|
||||
|
||||
url = self._gen_signed_url()
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=data, timeout=5)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
if result.get("errcode", -1) != 0:
|
||||
logger.error(f"钉钉消息发送失败: {result}")
|
||||
return False
|
||||
logger.info("钉钉消息发送成功")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"钉钉消息发送异常: {e}")
|
||||
return False
|
||||
|
||||
def send_markdown(
|
||||
self,
|
||||
title: str,
|
||||
text: str,
|
||||
at_mobiles: list = None,
|
||||
is_at_all: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
发送markdown消息
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
text: markdown格式的消息内容
|
||||
at_mobiles: 需要@的手机号列表
|
||||
is_at_all: 是否@所有人
|
||||
|
||||
Returns:
|
||||
bool: 是否发送成功
|
||||
"""
|
||||
if not self.webhook:
|
||||
logger.warning(f"[钉钉Markdown未发送] {title}")
|
||||
return False
|
||||
|
||||
at_mobiles = at_mobiles or []
|
||||
data = {
|
||||
"msgtype": "markdown",
|
||||
"markdown": {"title": title, "text": text},
|
||||
"at": {"atMobiles": at_mobiles, "isAtAll": is_at_all},
|
||||
}
|
||||
|
||||
url = self._gen_signed_url()
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=data, timeout=5)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
if result.get("errcode", -1) != 0:
|
||||
logger.error(f"钉钉markdown消息发送失败: {result}")
|
||||
return False
|
||||
logger.info("钉钉markdown消息发送成功")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"钉钉markdown消息发送异常: {e}")
|
||||
return False
|
||||
|
||||
|
||||
class NotificationManager:
|
||||
"""通知管理器 - 统一管理多种通知渠道"""
|
||||
|
||||
def __init__(self):
|
||||
self.dingtalk = DingTalkBot()
|
||||
|
||||
def notify(self, message: str, title: str = "系统通知", use_markdown: bool = False):
|
||||
"""
|
||||
发送通知(优先使用钉钉,失败则记录日志)
|
||||
|
||||
Args:
|
||||
message: 消息内容
|
||||
title: 消息标题(markdown模式使用)
|
||||
use_markdown: 是否使用markdown格式
|
||||
"""
|
||||
if use_markdown:
|
||||
success = self.dingtalk.send_markdown(title, message)
|
||||
else:
|
||||
success = self.dingtalk.send_text(message)
|
||||
|
||||
if not success:
|
||||
# 钉钉发送失败,记录到日志
|
||||
logger.info(f"[通知] {title}: {message}")
|
||||
|
||||
def notify_error(self, error_msg: str):
|
||||
"""发送错误通知"""
|
||||
markdown = f"""## 错误告警
|
||||
|
||||
**时间**: {time.strftime('%Y-%m-%d %H:%M:%S')}
|
||||
|
||||
**错误信息**:
|
||||
```
|
||||
{error_msg}
|
||||
```
|
||||
"""
|
||||
self.notify(markdown, title="系统错误", use_markdown=True)
|
||||
|
||||
def notify_signal(self, signals: list, signal_type: str = "CCI超卖"):
|
||||
"""
|
||||
发送交易信号通知
|
||||
|
||||
Args:
|
||||
signals: 信号列表,每项为dict包含code, name等指标
|
||||
signal_type: 信号类型名称
|
||||
"""
|
||||
if not signals:
|
||||
logger.info(f"[{signal_type}] 无信号")
|
||||
return
|
||||
|
||||
# 构建markdown表格
|
||||
if signals:
|
||||
headers = signals[0].keys()
|
||||
header_line = " | ".join(headers)
|
||||
separator = " | ".join(["---"] * len(headers))
|
||||
|
||||
rows = []
|
||||
for s in signals:
|
||||
row = " | ".join(str(v) for v in s.values())
|
||||
rows.append(row)
|
||||
|
||||
table = f"{header_line}\n{separator}\n" + "\n".join(rows)
|
||||
else:
|
||||
table = "无"
|
||||
|
||||
markdown = f"""## {signal_type}信号
|
||||
|
||||
**时间**: {time.strftime('%Y-%m-%d %H:%M:%S')}
|
||||
|
||||
**筛选结果**:
|
||||
|
||||
{table}
|
||||
|
||||
共 {len(signals)} 个标的符合筛选条件。
|
||||
"""
|
||||
self.notify(markdown, title=f"{signal_type}信号", use_markdown=True)
|
||||
190
core/common/utils.py
Normal file
190
core/common/utils.py
Normal file
@@ -0,0 +1,190 @@
|
||||
"""
|
||||
通用工具函数
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def format_date(date_str: str, output_format: str = "%Y-%m-%d") -> str:
|
||||
"""
|
||||
统一日期格式
|
||||
|
||||
Args:
|
||||
date_str: 输入日期字符串(支持 YYYY-MM-DD 或 YYYYMMDD)
|
||||
output_format: 输出格式
|
||||
|
||||
Returns:
|
||||
str: 格式化后的日期字符串
|
||||
"""
|
||||
# 尝试解析多种格式
|
||||
for fmt in ["%Y-%m-%d", "%Y%m%d", "%Y/%m/%d"]:
|
||||
try:
|
||||
dt = datetime.strptime(date_str, fmt)
|
||||
return dt.strftime(output_format)
|
||||
except ValueError:
|
||||
continue
|
||||
raise ValueError(f"无法解析日期格式: {date_str}")
|
||||
|
||||
|
||||
def get_date_range(
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
lookback_days: int = 365,
|
||||
) -> tuple[str, str]:
|
||||
"""
|
||||
获取日期范围
|
||||
|
||||
Args:
|
||||
start_date: 开始日期,None则根据lookback_days计算
|
||||
end_date: 结束日期,None则使用今天
|
||||
lookback_days: 回溯天数
|
||||
|
||||
Returns:
|
||||
tuple: (start_date, end_date) 格式为 YYYY-MM-DD
|
||||
"""
|
||||
if end_date is None:
|
||||
end = datetime.now()
|
||||
else:
|
||||
end = datetime.strptime(format_date(end_date), "%Y-%m-%d")
|
||||
|
||||
if start_date is None:
|
||||
start = end - timedelta(days=lookback_days)
|
||||
else:
|
||||
start = datetime.strptime(format_date(start_date), "%Y-%m-%d")
|
||||
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def calculate_cagr(
|
||||
nav_series: pd.Series,
|
||||
method: str = "natural_days",
|
||||
) -> float:
|
||||
"""
|
||||
计算年化收益率(CAGR)
|
||||
|
||||
Args:
|
||||
nav_series: 净值序列(index=日期)
|
||||
method: 'natural_days' 或 'trading_days'
|
||||
|
||||
Returns:
|
||||
float: CAGR值
|
||||
"""
|
||||
total_return = nav_series.iloc[-1] / nav_series.iloc[0]
|
||||
|
||||
if method == "natural_days":
|
||||
days = (nav_series.index[-1] - nav_series.index[0]).days
|
||||
years = days / 365.0
|
||||
elif method == "trading_days":
|
||||
years = len(nav_series) / 252.0
|
||||
else:
|
||||
raise ValueError(f"不支持的CAGR计算方式: {method}")
|
||||
|
||||
if years <= 0:
|
||||
return 0.0
|
||||
|
||||
return total_return ** (1 / years) - 1
|
||||
|
||||
|
||||
def calculate_max_drawdown(nav_series: pd.Series) -> tuple[float, datetime, datetime]:
|
||||
"""
|
||||
计算最大回撤
|
||||
|
||||
Returns:
|
||||
tuple: (最大回撤比例, 回撤起始日, 回撤结束日)
|
||||
"""
|
||||
cummax = nav_series.cummax()
|
||||
drawdown = (nav_series - cummax) / cummax
|
||||
|
||||
max_dd = drawdown.min()
|
||||
end_idx = drawdown.idxmin()
|
||||
start_idx = nav_series[:end_idx].idxmax()
|
||||
|
||||
return max_dd, start_idx, end_idx
|
||||
|
||||
|
||||
def calculate_sharpe(
|
||||
returns: pd.Series,
|
||||
rf: float = 0.0,
|
||||
periods: int = 252,
|
||||
) -> float:
|
||||
"""
|
||||
计算年化夏普比率
|
||||
|
||||
Args:
|
||||
returns: 日收益率序列
|
||||
rf: 无风险利率(年化)
|
||||
periods: 年化系数
|
||||
|
||||
Returns:
|
||||
float: 夏普比率
|
||||
"""
|
||||
excess_returns = returns - rf / periods
|
||||
if excess_returns.std() == 0:
|
||||
return 0.0
|
||||
return excess_returns.mean() / excess_returns.std() * np.sqrt(periods)
|
||||
|
||||
|
||||
def resample_data(
|
||||
df: pd.DataFrame,
|
||||
timeframe: str,
|
||||
time_col: str = "time",
|
||||
) -> pd.DataFrame:
|
||||
"""
|
||||
对数据进行重采样
|
||||
|
||||
Args:
|
||||
df: 原始数据
|
||||
timeframe: 目标周期 ('1D', '1W', '1M', '1Y')
|
||||
time_col: 时间列名
|
||||
|
||||
Returns:
|
||||
DataFrame: 重采样后的数据
|
||||
"""
|
||||
timeframe_map = {
|
||||
"1D": "D",
|
||||
"1W": "W",
|
||||
"1M": "M",
|
||||
"3M": "3M",
|
||||
"1Y": "Y",
|
||||
}
|
||||
|
||||
if timeframe not in timeframe_map:
|
||||
return df
|
||||
|
||||
df = df.copy()
|
||||
if time_col in df.columns:
|
||||
df[time_col] = pd.to_datetime(df[time_col])
|
||||
df.set_index(time_col, inplace=True)
|
||||
|
||||
rule = timeframe_map[timeframe]
|
||||
|
||||
resampled = (
|
||||
df.resample(rule)
|
||||
.agg(
|
||||
{
|
||||
"open": "first",
|
||||
"high": "max",
|
||||
"low": "min",
|
||||
"close": "last",
|
||||
"volume": "sum",
|
||||
}
|
||||
)
|
||||
.dropna()
|
||||
)
|
||||
|
||||
return resampled.reset_index()
|
||||
|
||||
|
||||
def safe_divide(a: float, b: float, default: float = 0.0) -> float:
|
||||
"""安全除法,避免除以0"""
|
||||
return a / b if b != 0 else default
|
||||
|
||||
|
||||
def truncate_string(s: str, max_length: int = 50, suffix: str = "...") -> str:
|
||||
"""截断字符串"""
|
||||
if len(s) <= max_length:
|
||||
return s
|
||||
return s[: max_length - len(suffix)] + suffix
|
||||
Reference in New Issue
Block a user