Download app.py from pigracing/zg: direct link, hf CLI and curl.
- Browser
- Download file 75.5 kB
-
https://huggingface.co/spaces/pigracing/zg/resolve/main/app.py
- Command line
-
hf download hf://spaces/pigracing/zg/app.py
-
curl -L -o app.py https://huggingface.co/spaces/pigracing/zg/resolve/main/app.py
75.5 kB
# TANZG 量价分析引擎 - Flask 后端
from flask import Flask, request, jsonify, send_from_directory
import akshare as ak
import pandas as pd
import requests
import json
import math
import os
import time
import re
import threading
import queue
from datetime import datetime
from analyzer import full_analysis, search_stock_by_name, parse_ts_code, get_stock_kline, get_augmented_kline, get_fund_flow_data, get_chip_data
from database import save_report, get_history, get_history_by_id, delete_history, _to_native
from database import save_recommendation, get_recommendation_history, get_recommendation_by_id
from database import get_watchlist, add_to_watchlist, remove_from_watchlist, update_watchlist_order, move_watchlist_item, watchlist_exists
# V2.0.0: 华尔街量化模型集成
from wallstreet import analyze_wallstreet
from backtest_integration import quick_backtest
def _sanitize(obj):
"""递归将 NaN/Inf/numpy 类型转换为 None 或 Python 原生类型"""
# 先做 numpy→原生类型转换
obj = _to_native(obj)
# 再处理 NaN/Inf
if isinstance(obj, dict):
return {k: _sanitize(v) for k, v in obj.items()}
if isinstance(obj, list):
return [_sanitize(x) for x in obj]
if isinstance(obj, float):
if math.isnan(obj) or math.isinf(obj):
return None
return obj
__version__ = 'V2.1.1'
app = Flask(__name__)
CONFIG_FILE = 'stock_config.json'
SINA_HEADERS = {
'Referer': 'https://finance.sina.com.cn',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
# ==================== Sina 直连 API ====================
def sina_quote(codes):
"""通过 Sina 实时行情接口获取多只股票/指数实时数据"""
if not codes:
return {}
syms = ','.join(codes)
url = f'https://hq.sinajs.cn/list={syms}'
try:
r = requests.get(url, headers=SINA_HEADERS, timeout=10)
r.encoding = 'gb18030'
except Exception:
return {}
result = {}
for line in r.text.strip().split('\n'):
m = re.search(r'hq_str_(\w+)="([^"]+)"', line)
if not m:
continue
sym = m.group(1)
fields = m.group(2).split(',')
if len(fields) < 5:
continue
try:
name = fields[0]
if sym.startswith(('s_sh', 's_sz', 'gb_')):
price = float(fields[1])
if sym.startswith('gb_'):
# 美股格式: name, price, pct%, datetime, change_abs, ...
# fields: [0]=name [1]=price [2]=pct% [3]=datetime [4]=change_abs
pct = float(fields[2]) if len(fields) > 2 else 0
change = float(fields[4]) if len(fields) > 4 else 0
vol = 0
amount = 0
else:
# A股指数格式(6字段): name, price, change_abs, pct%, vol, amount
# fields: [0]=name [1]=price [2]=change_abs [3]=pct% [4]=vol [5]=amount
change = float(fields[2]) if len(fields) > 2 else 0
pct = float(fields[3]) if len(fields) > 3 else 0
vol = float(fields[4]) if len(fields) > 4 else 0
amount = float(fields[5]) if len(fields) > 5 else 0
result[sym] = _sanitize({
'name': name, 'price': price, 'open': 0,
'high': 0, 'low': 0,
'prev_close': round(price - change, 2),
'change': round(change, 2),
'pct_change': round(pct, 2), 'volume': int(vol),
'amount': amount, 'time': '',
})
else:
# 个股格式(33字段): name,open,prev_close,price,high,low,bid1,ask1,vol,amount,...,date,time,flag
# [0]=名称 [1]=开盘 [2]=昨收 [3]=当前价 [4]=最高 [5]=最低
# [6]=买一 [7]=卖一 [8]=成交量(手) [9]=成交额(元) [30]=日期 [31]=时间
prev_close = float(fields[2])
open_p = float(fields[1])
close_p = float(fields[3])
high = float(fields[4]) if len(fields) > 4 else close_p
low = float(fields[5]) if len(fields) > 5 else close_p
vol = float(fields[8]) if len(fields) > 8 else 0
amount = float(fields[9]) if len(fields) > 9 else 0
pct = (close_p - prev_close) / prev_close * 100 if prev_close else 0
change = close_p - prev_close
result[sym] = _sanitize({
'name': name, 'price': close_p, 'open': open_p,
'high': high, 'low': low,
'prev_close': prev_close, 'change': round(change, 2),
'pct_change': round(pct, 2), 'volume': int(vol),
'amount': amount, 'time': fields[31] if len(fields) > 31 else '',
})
except (ValueError, IndexError):
continue
return result
# ==================== BaoStock 备用数据源 ====================
try:
import baostock as bs
BAOSTOCK_AVAILABLE = True
except ImportError:
BAOSTOCK_AVAILABLE = False
bs = None
_bs_lock = threading.Lock()
def _bs_login():
"""登录baostock(线程安全)"""
if not BAOSTOCK_AVAILABLE:
return False
try:
with _bs_lock:
result = bs.login()
return result.error_code == '0'
except Exception:
return False
def _bs_logout():
"""登出baostock"""
if not BAOSTOCK_AVAILABLE:
return
try:
with _bs_lock:
bs.logout()
except Exception:
pass
def baostock_quote(ts_codes):
"""通过 BaoStock 获取股票实时行情(备用数据源)
Args:
ts_codes: 如 ['sh.600000', 'sz.000001'] 或 ['600000.SH', '000001.SZ']
Returns:
dict: {sina_sym: {name, price, open, high, low, prev_close, change, pct_change, volume, time}}
"""
if not BAOSTOCK_AVAILABLE or not ts_codes:
return {}
# 转换格式:600000.SH -> sh.600000
def _to_bs(code):
code = code.strip()
if '.' not in code:
return None
sym, market = code.split('.')
# BaoStock格式: sh.600000, sz.000001
bs_sym = f"{market.lower()}.{sym}"
return bs_sym
bs_codes = [_to_bs(c) for c in ts_codes]
bs_codes = [c for c in bs_codes if c]
if not _bs_login():
return {}
result = {}
try:
for bs_code in bs_codes:
try:
rs = bs.query_history_k_data_plus(
bs_code,
"date,code,open,high,low,close,volume,amount,turn",
f"date={datetime.now().strftime('%Y-%m-%d')}",
timeout=5
)
if rs.error_code == '0' and rs.realtime_data:
row = rs.realtime_data[0]
# 获取上一个交易日数据用于计算涨跌幅
rs_prev = bs.query_history_k_data_plus(
bs_code,
"date,close,prev_close",
f"end_date={datetime.now().strftime('%Y-%m-%d')},frequency=d,count=2",
timeout=5
)
prev_close = None
if rs_prev.error_code == '0':
data = rs_prev.data
if len(data) >= 2:
prev_close = float(data[1][2]) # 前一行是前一天
name = ''
try:
rs_name = bs.query_stock_basic(code=bs_code)
if rs_name.error_code == '0':
name = rs_name.basket_data[0].get('stock_name', '') if hasattr(rs_name, 'basket_data') and rs_name.basket_data else ''
except Exception:
pass
close = float(row[4]) # close是第5个字段(0-indexed=4)
if prev_close is None:
prev_close = close
change = round(close - prev_close, 2)
pct = (close - prev_close) / prev_close * 100 if prev_close else 0
# 转换回sina格式的symbol
parts = bs_code.split('.')
sina_sym = f"{parts[0]}{parts[1]}"
result[sina_sym] = _sanitize({
'name': name,
'price': close,
'open': float(row[2]) if row[2] else close,
'high': float(row[3]) if row[3] else close,
'low': float(row[4]) if row[4] else close,
'prev_close': prev_close,
'change': change,
'pct_change': round(pct, 2),
'volume': int(float(row[6])) if row[6] else 0,
'amount': float(row[7]) if row[7] else 0,
'time': row[0],
'source': 'baostock'
})
except Exception:
continue
finally:
_bs_logout()
return result
def get_stock_quote(codes):
"""获取行情数据,优先使用Sina,Sina失败时使用BaoStock备用
Args:
codes: Sina格式的股票代码列表,如 ['sh600000', 'sz000001']
Returns:
dict: {sina_sym: {name, price, ...}}
"""
# 优先使用Sina
result = sina_quote(codes)
if result:
return result
# Sina失败,尝试BaoStock
if not BAOSTOCK_AVAILABLE:
return {}
# 转换Sina格式到ts_code格式: sh600000 -> 600000.SH
ts_codes = []
for code in codes:
code = code.strip()
if code.startswith('sh'):
ts_codes.append(f"{code[2:]}.SH")
elif code.startswith('sz'):
ts_codes.append(f"{code[2:]}.SZ")
elif code.startswith('s_sh'):
ts_codes.append(f"{code[4:]}.SH")
elif code.startswith('s_sz'):
ts_codes.append(f"{code[4:]}.SZ")
if not ts_codes:
return {}
return baostock_quote(ts_codes)
def get_china_indices():
"""A股主要指数实时行情"""
codes = ['s_sh000001', 's_sz399001', 's_sz399006', 's_sh000688']
names = {'s_sh000001': '上证指数', 's_sz399001': '深证成指',
's_sz399006': '创业板指', 's_sh000688': '科创50'}
data = get_stock_quote(codes)
results = []
for sym, info in data.items():
results.append({
'code': sym.replace('s_', '').upper(),
'name': names.get(sym, info.get('name', '')),
'price': info['price'],
'change': info['change'],
'pct_change': info['pct_change'],
'market': 'cn'
})
return results
def get_us_indices():
"""美股主要指数实时行情"""
codes = ['gb_ndx', 'gb_dji']
names = {'gb_ndx': '纳斯达克100', 'gb_dji': '道琼斯'}
data = get_stock_quote(codes)
results = []
for sym, info in data.items():
# 过滤无效数据(价格过低说明数据源异常)
if info['price'] < 100:
continue
results.append({
'code': sym.upper(), 'name': names.get(sym, info.get('name', '')),
'price': info['price'], 'change': info['change'],
'pct_change': info['pct_change'], 'market': 'us'
})
return results
@app.route('/api/indices', methods=['GET'])
def api_indices():
cn = get_china_indices()
us = get_us_indices()
return jsonify({
'cn': cn, 'us': us,
'timestamp': datetime.now().strftime('%H:%M:%S')
})
# ==================== 关注股票 ====================
# 数据来源常量
DATA_SOURCE = '新浪财经'
@app.route('/api/watchlist', methods=['GET', 'POST'])
@app.route('/api/watch_stocks', methods=['GET', 'POST']) # 兼容旧路由
def api_watch_stocks():
if request.method == 'POST':
body = request.get_json()
if 'watch_stocks' in body:
# 批量更新模式(拖拽排序)
update_watchlist_order(body['watch_stocks'])
return jsonify({'ok': True, 'data_source': DATA_SOURCE})
elif 'code' in body:
raw = body['code'].strip()
ts_code = raw
# 如果是中文名称,先查询代码
if not re.match(r'^\d{6}', raw):
ts_code = search_stock_by_name(raw)
if not ts_code:
return jsonify({'error': f'无法识别股票名称:{raw}'}), 400
ts_code = ts_code.strip().upper()
# 补全市场后缀
if '.' not in ts_code:
if ts_code.startswith(('000', '002', '003', '300')):
ts_code = f'{ts_code}.SZ'
elif ts_code.startswith(('600', '601', '603', '688')):
ts_code = f'{ts_code}.SH'
else:
ts_code = f'{ts_code}.SZ'
# 检查是否已存在
if watchlist_exists(ts_code):
return jsonify({'error': f'{ts_code} 已在关注列表中'}), 400
# 获取完整行情
c, m = parse_ts_code(ts_code)
sym = f'{m}{c}'
q = get_stock_quote([sym]).get(sym, {})
name = q.get('name', ts_code)
vol = q.get('volume', 0)
vol_w = round(vol / 10000, 2) if vol else 0
# 添加到数据库
add_to_watchlist(ts_code, name)
# 返回完整行情数据,供前端立即渲染
return jsonify({
'ok': True,
'ts_code': ts_code,
'code': ts_code,
'name': name,
'price': q.get('price', 0),
'pct_change': q.get('pct_change', 0),
'change': q.get('change', 0),
'high': q.get('high', 0),
'low': q.get('low', 0),
'vol_w': vol_w,
'vol_ratio': None,
'time': q.get('time', ''),
'data_source': DATA_SOURCE,
})
return jsonify({'ok': True, 'data_source': DATA_SOURCE})
# GET 请求:获取关注列表
stocks = get_watchlist()
# 获取实时行情
codes = [s['ts_code'] for s in stocks]
sina_syms = []
for code in codes:
c, m = parse_ts_code(code)
sina_syms.append(f'{m}{c}')
quotes = get_stock_quote(sina_syms)
result = []
for s in stocks:
c, m = parse_ts_code(s['ts_code'])
sym = f'{m}{c}'
q = quotes.get(sym, {})
vol = q.get('volume', 0)
vol_w = round(vol / 10000, 2) if vol else 0
result.append({
'code': s['ts_code'],
'ts_code': s['ts_code'],
'name': s.get('name', q.get('name', '')),
'price': q.get('price', 0),
'pct_change': q.get('pct_change', 0),
'change': q.get('change', 0),
'high': q.get('high', 0),
'low': q.get('low', 0),
'time': q.get('time', ''),
'vol_w': vol_w,
'vol_ratio': None,
'data_source': DATA_SOURCE,
})
return jsonify(_sanitize(result))
@app.route('/api/watchlist/<path:ts_code>', methods=['DELETE'])
@app.route('/api/watch_stocks/<path:ts_code>', methods=['DELETE']) # 兼容旧路由
def api_delete_watchlist(ts_code):
remove_from_watchlist(ts_code)
return jsonify({'ok': True, 'data_source': DATA_SOURCE})
@app.route('/api/watchlist/move', methods=['POST'])
def api_move_watchlist():
"""移动关注股票位置
body: {ts_code: 'xxx.SZ', direction: 'up'|'down'}
"""
body = request.get_json()
ts_code = body.get('ts_code')
direction = body.get('direction')
if not ts_code or direction not in ['up', 'down']:
return jsonify({'error': '参数错误'}), 400
ok, msg = move_watchlist_item(ts_code, direction)
if ok:
return jsonify({'ok': True, 'message': msg, 'data_source': DATA_SOURCE})
else:
return jsonify({'error': msg}), 400
# ==================== 分析引擎 ====================
@app.route('/api/signal/<path:ts_code>', methods=['GET'])
def api_signal(ts_code):
"""轻量端点:只返回信号分析,不写 DB(供关注列表信号列使用)"""
try:
report = full_analysis(ts_code)
return jsonify(_sanitize({
'ts_code': ts_code,
'signal': report.get('signal', '观望'),
'signal_emoji': report.get('signal_emoji', '🟡'),
'signal_class': (
'signal-buy' if report.get('signal') == '买入' else
'signal-reduce' if report.get('signal') == '减仓/清仓' else
'signal-risk' if report.get('signal') == '风险警惕' else 'signal-watch'
),
'rules_count': len(report.get('trigger_rules', {})),
}))
except Exception as e:
return jsonify(_sanitize({
'ts_code': ts_code, 'signal': '-', 'signal_emoji': '-',
'signal_class': 'signal-watch', 'rules_count': 0,
}))
# ==================== 量化推荐 ====================
def _call_with_timeout(fn, timeout=30):
"""在子线程执行函数,超时则抛异常"""
q = queue.Queue()
def _w():
try:
q.put(('ok', fn()))
except Exception as e:
q.put(('err', str(e)))
t = threading.Thread(target=_w, daemon=True)
t.start()
t.join(timeout=timeout)
if t.is_alive():
raise TimeoutError(f"执行超时({timeout}s)")
if q.empty():
raise RuntimeError("无返回结果")
tag, val = q.get_nowait()
if tag == 'err':
raise RuntimeError(val)
return val
def get_recommendations():
"""获取量化推荐(使用 Sina 实时接口 + akshare 备用):
1. 获取全量行情筛选候选股(akshare,不可靠时用 Sina)
2. 分析热点板块(Sina)
3. 获取候选股实时行情(Sina),综合评分推荐 3 只
"""
result = {
'created_at': datetime.now().strftime('%Y-%m-%d %H:%M'),
'sentiment': '中性',
'sentiment_label': '市场情绪中性',
'hot_sectors': [],
'stocks': [],
'raw_report': '',
}
# ── 步骤0:获取候选股票池(Sina 分批拉取) ───────────────────
candidate_codes = _get_candidate_pool()
# ── 步骤1:获取候选股实时行情(Sina) ────────────────────────
stock_data = []
if candidate_codes:
def _to_sina(c):
c = str(c).strip()
return ('sh' + c) if c.startswith('6') else ('sz' + c)
batch = ','.join(_to_sina(c) for c in candidate_codes[:50])
try:
resp = requests.get(
'https://hq.sinajs.cn/list=' + batch,
headers={'Referer': 'https://finance.sina.com.cn', 'User-Agent': 'Mozilla/5.0'},
timeout=15
)
resp.encoding = 'gbk'
for line in resp.text.splitlines():
m = re.search(r'hq_str_(\w+)=\"([^\"]+)\"', line)
if not m:
continue
sym = m.group(1).upper()
fields = m.group(2).split(',')
if len(fields) < 10:
continue
try:
name = fields[0]
close = float(fields[1]) if fields[1] else 0.0
prev_close = float(fields[3]) if fields[3] else close
if close <= 0 or prev_close <= 0:
continue
pct = round((close - prev_close) / prev_close * 100, 2)
vol_w = round(float(fields[8]) / 1e4, 2) if fields[8] else 0.0
stock_data.append({
'sym': sym,
'name': name,
'close': close,
'open': float(fields[2]) if fields[2] else close,
'high': float(fields[4]) if fields[4] else close,
'low': float(fields[5]) if fields[5] else close,
'pct': pct,
'change': round(close - prev_close, 2),
'vol_w': vol_w,
'amount': float(fields[9]) if fields[9] else 0.0,
'prev_close': prev_close,
})
except (ValueError, IndexError):
continue
except Exception:
pass
# ── 步骤2:情绪分析 ────────────────────────────────────────────
up_list = [s for s in stock_data if s['pct'] > 0]
dn_list = [s for s in stock_data if s['pct'] < 0]
total = len(stock_data)
if total > 0:
ratio = (len(up_list) - len(dn_list)) / total
if ratio > 0.15:
result['sentiment'] = '看多'
result['sentiment_label'] = f'市场情绪偏多(涨 {len(up_list)} / 跌 {len(dn_list)})'
elif ratio < -0.15:
result['sentiment'] = '看空'
result['sentiment_label'] = f'市场情绪偏空(跌 {len(dn_list)} / 涨 {len(up_list)})'
else:
result['sentiment'] = '中性'
result['sentiment_label'] = f'市场情绪中性(涨 {len(up_list)} / 跌 {len(dn_list)})'
# ── 步骤3:热点板块(Sina) ──────────────────────────────────
hot_sectors = _get_hot_sectors_sina()
result['hot_sectors'] = hot_sectors
top_sector = hot_sectors[0]['name'] if hot_sectors else '科技'
# ── 步骤4:综合评分选股 ────────────────────────────────────
# V1.7.2: 取消价格区间控制,增加买入信号过滤
for s in stock_data:
# 量能放大
vol_score = min(s['vol_w'] / 500, 1.0) if s['vol_w'] > 0 else 0
# 综合分:涨幅权重 + 量能权重
s['_score'] = s['pct'] * 0.7 + vol_score * 10
# 先按评分排序
stock_data.sort(key=lambda x: x['_score'], reverse=True)
candidates = stock_data[:15] # 取前15名做信号检查
# V1.7.2: 检查信号是否为"买入"
from analyzer import full_analysis as _fa
picks = []
for s in candidates:
if len(picks) >= 4:
break
sym = s['sym']
# 转换为 ts_code 格式
code_part = sym.replace('SH', '').replace('SZ', '').replace('sh', '').replace('sz', '')
market = 'SH' if 'SH' in sym.upper() or code_part.startswith(('6', '9')) else 'SZ'
ts_code = f'{code_part}.{market}'
try:
report = _fa(ts_code)
if report.get('signal') == '买入':
picks.append({
'ts_code': sym,
'name': s['name'],
'price': round(s['close'], 2),
'pct_change': round(s['pct'], 2),
'market_cap': 0,
'pe': 0,
'sector': top_sector,
'reasons': _build_reasons(s['pct'], hot_sectors, result['sentiment']),
'risk': _build_risk(s['pct']),
})
except Exception:
continue
result['stocks'] = picks
result['raw_report'] = _build_raw_report(result)
return result
def _get_candidate_pool():
"""获取候选股票池:akshare获取,过滤市值100亿~1000亿 + 目标行业板块"""
pool = []
# V1.7.2: 目标行业板块
TARGET_SECTORS = ['AI应用', '半导体', '芯片', '机器人', '新能源', '云计算', '算力', '有色金属', '稀有金属', '商业航天']
# 尝试 akshare(不可靠时回退)
try:
df = _call_with_timeout(lambda: ak.stock_zh_a_spot_em(), timeout=15)
if df is not None and len(df) > 100:
cap_col = '总市值' if '总市值' in df.columns else None
pe_col = '市盈率' if '市盈率' in df.columns else None
# V1.7.2: 市值范围100亿~1000亿
if cap_col:
df = df[(df[cap_col] > 1e10) & (df[cap_col] < 1e11)].copy()
if pe_col:
df = df[(df[pe_col] > 0) & (df[pe_col] < 200)].copy()
# V1.7.2: 尝试用akshare行业板块数据筛选目标行业
sector_codes = set()
try:
# 获取所有行业板块
board_df = _call_with_timeout(lambda: ak.stock_board_industry_name_em(), timeout=10)
if board_df is not None and len(board_df) > 0:
target_keywords = ['AI', '半导体', '芯片', '机器人', '新能源', '云计算', '算力', '有色', '稀土', '航天']
for _, b_row in board_df.iterrows():
b_name = str(b_row.get('板块名称', ''))
if any(kw in b_name for kw in target_keywords):
try:
cons_df = _call_with_timeout(
lambda bn=b_name: ak.stock_board_industry_cons_em(symbol=bn), timeout=8)
if cons_df is not None and '代码' in cons_df.columns:
for _, c_row in cons_df.iterrows():
sector_codes.add(str(c_row['代码']))
except Exception:
pass
except Exception:
pass
if len(sector_codes) > 10:
# 先用行业板块过滤候选股
df_filtered = df[df['代码'].isin(sector_codes)]
if len(df_filtered) > 0:
df = df_filtered
if len(df) > 3:
for _, row in df.head(50).iterrows():
code = str(row.get('代码', ''))
if len(code) == 6:
pool.append(code)
return pool
except Exception:
pass
# 回退:使用 Sina 市场概况获取沪深主要股票(目标行业相关)
return [
'300308', '300782', '300750', '300274', '300014', '688001', '603501', '603986',
'603019', '000063', '000977', '002230', '002049', '002371', '600584', '688981',
'300661', '300502', '301236', '000425', '002721', '300251',
]
def _get_hot_sectors_sina():
"""通过 Sina 财经板块接口获取热点板块"""
sectors = []
try:
resp = requests.get(
'https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeDataSimple?page=1&num=10&sort=changepercent&asc=0&node=bk_hy&symbol=&_s_r_a=page',
headers={'Referer': 'https://finance.sina.com.cn', 'User-Agent': 'Mozilla/5.0'},
timeout=8
)
data = resp.json()
for item in (data or [])[:6]:
sectors.append({
'name': str(item.get('symbol', '')),
'pct': float(item.get('changepercent', 0)),
'fund': '-',
})
except Exception:
pass
return sectors
def _build_reasons(pct, sectors, sentiment):
reasons = []
if pct > 3:
reasons.append('近期涨幅较强,资金关注度高')
elif pct > 0:
reasons.append('走势偏强,处于上升通道')
else:
reasons.append('股价处于相对低位,值得关注')
if sectors:
reasons.append(f'所属{sectors[0]["name"]}板块近期表现活跃')
if sentiment == '看多':
reasons.append('市场整体情绪偏多,利于多头')
else:
reasons.append('建议控制仓位,防范回调风险')
return reasons
def _build_risk(pct):
if abs(pct) > 7:
return '波动剧烈,注意止损'
elif pct > 5:
return '短期涨幅较大,谨慎追高'
elif pct < -3:
return '已出现较大回调,注意支撑位'
return '注意基本面变化,合理止损'
def _build_raw_report(rec):
lines = [f"# 量化推荐报告 {rec['created_at']}\n",
f"## 市场情绪:{rec['sentiment_label']}\n"]
if rec['hot_sectors']:
lines.append("## 热点板块\n")
for s in rec['hot_sectors']:
lines.append(f"- {s['name']} 涨跌:{s['pct']:+.1f}% 主力:{s['fund']}\n")
lines.append("\n## 推荐股票\n")
for i, s in enumerate(rec['stocks'], 1):
lines.append(f"### {i}. {s['name']} {s['ts_code']}\n")
lines.append(f"| 指标 | 数值 |\n|------|------|\n")
lines.append(f"| 最新价 | ¥{s['price']} |\n")
lines.append(f"| 涨跌幅 | {s['pct_change']:+.2f}% |\n")
lines.append(f"| 市值 | {s['market_cap']}亿 |\n")
lines.append(f"| 市盈率 | {s['pe']} |\n")
lines.append(f"| 所属板块 | {s['sector']} |\n")
lines.append(f"**推荐理由**:{';'.join(s['reasons'])}\n")
lines.append(f"**风险提示**:{s['risk']}\n\n")
lines.append("\n⚠️ 仅供参考,不构成投资建议。\n")
return ''.join(lines)
@app.route('/api/recommend', methods=['GET'])
def api_recommend():
"""获取最新量化推荐(不写 DB)"""
try:
rec = get_recommendations()
return jsonify(_sanitize(rec))
except Exception as e:
return jsonify({'error': f'推荐获取失败: {e}'}), 500
@app.route('/api/recommend/save', methods=['POST'])
def api_recommend_save():
"""获取并保存量化推荐到历史"""
try:
rec = get_recommendations()
rid = save_recommendation(rec)
rec['id'] = rid
return jsonify(_sanitize(rec))
except Exception as e:
return jsonify({'error': f'推荐失败: {e}'}), 500
@app.route('/api/recommend/history', methods=['GET'])
def api_recommend_history():
"""查询推荐历史"""
limit = request.args.get('limit', 20, type=int)
rows = get_recommendation_history(limit)
# 反序列化 JSON 字符串字段
for r in rows:
for f in ('hot_sectors', 'stocks'):
if r.get(f):
try:
r[f] = json.loads(r[f])
except (json.JSONDecodeError, TypeError):
pass
return jsonify(_sanitize(rows))
@app.route('/api/recommend/<int:rid>/watch/<path:ts_code>', methods=['POST'])
def api_recommend_to_watch(rid, ts_code):
"""将推荐中的某只股票加入关注列表"""
row = get_recommendation_by_id(rid)
if not row:
return jsonify({'error': '推荐记录不存在'}), 404
stocks = []
try:
stocks = json.loads(row.get('stocks', '[]'))
except (json.JSONDecodeError, TypeError):
pass
target = next((s for s in stocks if s['ts_code'] == ts_code), None)
if not target:
return jsonify({'error': f'推荐中未找到 {ts_code}'}), 404
# 获取实时行情后写入配置
q = queue.Queue()
def _w():
import requests as _req
_r = _req.get(
'https://hq.sinajs.cn/list=' + ts_code,
headers={'Referer': 'https://finance.sina.com.cn'},
timeout=8
)
raw = _r.text
raw = re.sub(r'/\*.*?\*/', '', raw)
m = re.search(r'="([^"]+)"', raw)
if not m:
raise ValueError('Sina 返回空')
fields = m.group(1).split(',')
name = fields[0]
close_p = float(fields[1]) if fields[1] else 0.0
open_p = float(fields[2]) if fields[2] else 0.0
vol = int(float(fields[8])) if fields[8] else 0
amount = float(fields[9]) if fields[9] else 0.0
prev_close = float(fields[3]) if fields[3] else close_p
change = round(close_p - prev_close, 2)
pct = round(change / prev_close * 100, 2) if prev_close else 0.0
q.put({'ts_code': ts_code, 'name': name, 'price': close_p,
'open': open_p, 'high': float(fields[4]) if fields[4] else close_p,
'low': float(fields[5]) if fields[5] else close_p,
'prev_close': prev_close, 'change': change,
'pct_change': pct, 'volume': vol, 'amount': amount})
t = threading.Thread(target=_w, daemon=True)
t.start(); t.join(timeout=10)
if t.is_alive() or q.empty():
# 回退:直接用推荐数据
quote = target
else:
quote = q.get_nowait()
# 使用数据库检查是否已存在
if watchlist_exists(ts_code):
return jsonify({'ok': True, 'msg': f'{quote.get("name", ts_code)} 已在关注列表'})
# 添加到数据库
add_to_watchlist(ts_code, quote.get('name', target['name']))
return jsonify({'ok': True, 'ts_code': ts_code, 'name': quote.get('name', target['name']), 'data_source': DATA_SOURCE})
# ==================== 实时行情 API(V1.6.6) ====================
@app.route('/api/quote', methods=['GET'])
def api_quote():
"""实时行情查询:输入股票代码/名称,返回最新行情数据"""
query = request.args.get('code', '').strip()
if not query:
return jsonify({'error': '请输入股票代码或名称'}), 400
# 解析股票代码
ts_code = search_stock_by_name(query)
if not ts_code:
if re.match(r'^\d{6}', query):
c, m = parse_ts_code(query)
ts_code = f'{c.upper()}.{m.upper()}'
if not ts_code:
return jsonify({'error': f'无法识别股票: {query}'}), 400
# 获取实时行情
c, m = parse_ts_code(ts_code)
sym = f'{m}{c}'
q = get_stock_quote([sym]).get(sym, {})
if not q:
return jsonify({'error': '获取行情失败'}), 500
vol = q.get('volume', 0)
vol_w = round(vol / 10000, 2) if vol else 0
# V1.6.8: 数据时间校验
data_time = q.get('time', '')
now = datetime.now()
today_str = now.strftime('%Y-%m-%d')
# 判断是否为当前交易时段数据:A股交易时间 9:30-15:00(盘中),15:00-15:30(集合竞价)
# 如果数据时间与当前时间在合理范围内则视为已验证
data_verified = False
if data_time:
try:
h, m_val, s = data_time.split(':')
data_minutes = int(h) * 60 + int(m_val)
now_minutes = now.hour * 60 + now.minute
# 盘中或收盘后30分钟内都视为已验证
if 570 <= data_minutes <= 930 and abs(now_minutes - data_minutes) <= 60:
data_verified = True
# 收盘后(15:00后)看到的数据带15:00时间戳也算已验证
if data_minutes >= 900 and now_minutes >= 900:
data_verified = True
except Exception:
pass
return jsonify(_sanitize({
'ts_code': ts_code,
'code': ts_code,
'name': q.get('name', ts_code),
'price': q.get('price', 0),
'pct_change': q.get('pct_change', 0),
'change': q.get('change', 0),
'open': q.get('open', 0),
'high': q.get('high', 0),
'low': q.get('low', 0),
'prev_close': q.get('prev_close', 0),
'volume': q.get('volume', 0),
'vol_w': vol_w,
'time': data_time,
'data_time': today_str + ' ' + data_time,
'data_verified': data_verified,
'data_source': DATA_SOURCE,
}))
@app.route('/api/analyze', methods=['POST'])
def api_analyze():
body = request.get_json()
# 兼容前端传 code 或 query 字段
query = (body.get('query') or body.get('code') or '').strip()
if not query:
return jsonify({'error': '请输入股票代码或名称'}), 400
# 名称解析(带超时保护)
ts_code = search_stock_by_name(query)
if not ts_code:
# 尝试直接解析六位代码(支持带或不带 .SH/.SZ 后缀)
if re.match(r'^\d{6}', query):
c, m = parse_ts_code(query)
ts_code = f'{c.upper()}.{m.upper()}'
if not ts_code:
return jsonify({'error': f'无法识别股票: {query}'}), 400
# V1.7.1: 先获取实时行情 — 优先AKSHARE(东方财富API直调,极速),备用新浪/baostock
c, m = parse_ts_code(ts_code)
sym = f'{m}{c}'
code_str = ts_code.split('.')[0]
# 尝试AKSHARE/东方财富API获取个股实时行情(极速单股查询)
quote = {}
akshare_source = DATA_SOURCE
try:
# 东方财富个股实时行情API(AKSHARE底层接口)
em_secid = '0.' + code_str if m == 'sz' else '1.' + code_str
em_url = f'https://push2.eastmoney.com/api/qt/stock/get?secid={em_secid}&fields=f43,f44,f45,f46,f47,f48,f49,f50,f51,f52,f57,f58,f170,f171,f57'
em_headers = {'User-Agent': 'Mozilla/5.0', 'Referer': 'https://quote.eastmoney.com/'}
em_resp = requests.get(em_url, headers=em_headers, timeout=8)
em_data = em_resp.json()
em_data2 = em_data.get('data', {})
if em_data2 and em_data2.get('f43', 0) > 0:
# 东方财富API价格单位为分(厘),需除以100转换为元
price = float(em_data2['f43']) / 100.0
pct = float(em_data2.get('f170', 0)) / 100.0
prev_close = float(em_data2.get('f60', 0)) / 100.0 if em_data2.get('f60', 0) > 0 else 0
quote = {
'price': price,
'pct_change': pct,
'open': float(em_data2.get('f46', 0)) / 100.0,
'high': float(em_data2.get('f44', 0)) / 100.0,
'low': float(em_data2.get('f45', 0)) / 100.0,
'prev_close': prev_close,
'volume': float(em_data2.get('f47', 0)) * 100, # 手转股
'amount': float(em_data2.get('f48', 0)), # 成交额元
'time': datetime.now().strftime('%H:%M:%S'),
'name': str(em_data2.get('f58', '')),
'turnover_rate': float(em_data2.get('f168', 0)) / 100.0 if em_data2.get('f168') else 0,
'total_mv': float(em_data2.get('f20', 0)) / 1e8 if em_data2.get('f20') else 0,
}
if prev_close > 0:
quote['change'] = round(price - prev_close, 2)
akshare_source = 'AKSHARE数据库'
except Exception:
pass
# AKSHARE获取失败,使用原有的Sina方式,再用baostock备用
if not quote or not quote.get('price', 0):
quote = get_stock_quote([sym]).get(sym, {})
akshare_source = DATA_SOURCE
# 如果Sina也获取不到,用baostock备用
if not quote or not quote.get('price', 0):
try:
from analyzer import parse_ts_code as _ptc
c2, m2 = _ptc(ts_code)
bs_sym = f'{m2}{c2}'
baostock_data = baostock_quote([ts_code])
if baostock_data:
# baostock返回的key可能不同,尝试多种格式匹配
# 修复:增加更严格的匹配逻辑,防止格式不一致导致的数据匹配错误
ts_code_simple = ts_code.split('.')[0] # 如 000001
target_keys = [
ts_code, # 000001.SZ
bs_sym, # sz000001
ts_code_simple, # 000001
f'{c2}.{m2.upper()}', # 000001.SZ (标准化)
]
for bk, bv in baostock_data.items():
# 精确匹配:检查key是否在目标key列表中
if bk in target_keys:
if bv and bv.get('price', 0) > 0:
quote = bv
akshare_source = 'BaoStock'
break
# 部分匹配:作为后备方案(保持兼容性)
elif c2 in bk or ts_code_simple in bk:
if bv and bv.get('price', 0) > 0:
quote = bv
akshare_source = 'BaoStock'
break
except Exception as e:
print(f'BaoStock数据处理失败: {e}')
pass
data_time = quote.get('time', '')
now = datetime.now()
today_str = now.strftime('%Y-%m-%d')
data_verified = False
if data_time:
try:
h, mv, s = str(data_time).split(':')
data_min = int(h)*60+int(mv)
now_min = now.hour*60+now.minute
if 570 <= data_min <= 930 and abs(now_min-data_min) <= 60:
data_verified = True
if data_min >= 900 and now_min >= 900:
data_verified = True
except Exception:
pass
# 执行分析
report = full_analysis(ts_code)
if 'error' in report:
return jsonify(report), 500
# V2.1.1: 华尔街多维量化分析(含增强K线+资金流+筹码)
try:
kline_df = get_augmented_kline(ts_code, days=365)
report['_kline_count'] = len(kline_df) if kline_df is not None else 0
if kline_df is not None and len(kline_df) >= 60:
fund_flow_df = get_fund_flow_data(ts_code, days=365)
chip_data = get_chip_data(ts_code)
ws_result = analyze_wallstreet(kline_df, fund_flow_df)
ws_result['_chip_data_source'] = '真实数据' if chip_data else '近似估算'
report['wallstreet'] = ws_result
bt_result = quick_backtest(kline_df, lookback_days=250)
report['backtest'] = bt_result
else:
report['wallstreet'] = {'error': f'K线数据不足({len(kline_df) if kline_df is not None else 0}行)'}
report['backtest'] = {'error': '数据不足'}
except Exception as e:
import traceback
report['wallstreet'] = {'error': f'分析异常: {str(e)[:200]}'}
report['backtest'] = {'error': f'回测异常: {str(e)[:100]}'}
# V1.7.1: 用实时行情数据覆盖报告中的实时字段
if quote:
# V1.7.2: 保留昨日收盘数据(来自full_analysis的K线数据)
report['yest_close'] = report.get('latest_close', 0)
report['yest_pct_change'] = report.get('pct_change', 0)
report['prev_close'] = quote.get('prev_close', 0)
vol = quote.get('volume', 0)
vol_w = round(vol / 10000, 2) if vol else report.get('vol_w', 0)
report['latest_close'] = quote.get('price', report.get('latest_close', 0))
report['high'] = quote.get('high', report.get('high', 0))
report['low'] = quote.get('low', report.get('low', 0))
report['open'] = quote.get('open', report.get('open', 0))
report['pct_change'] = quote.get('pct_change', report.get('pct_change', 0))
report['vol_w'] = vol_w
report['turnover_rate'] = quote.get('turnover_rate', None)
report['total_mv'] = quote.get('total_mv', None)
# 保存历史
saved_id = save_report(report)
report['id'] = saved_id
report['engine_version'] = __version__
# V1.7.1: 数据来源和时间校验信息
report['data_source'] = akshare_source
report['data_time'] = today_str + ' ' + str(data_time) if data_time else ''
report['data_verified'] = data_verified
return jsonify(_sanitize(report))
@app.route('/api/history', methods=['GET'])
def api_history():
limit = int(request.args.get('limit', 100))
history = get_history(limit=limit)
return jsonify(history)
@app.route('/api/history/<int:report_id>', methods=['GET'])
def api_history_id(report_id):
report = get_history_by_id(report_id)
if not report:
return jsonify({'error': '记录不存在'}), 404
# 反序列化 JSON 字符串字段(存入 DB 时序列化了)
for field in ('high_volume_days', 'trigger_rules', 'kline_10d', 'raw_data'):
if field in report and report[field]:
try:
report[field] = json.loads(report[field])
except (json.JSONDecodeError, TypeError):
pass
# 从 raw_data 补算 amount_bn(renderReport 需要)
if 'amount_bn' not in report and 'raw_data' in report and report['raw_data']:
rows = report['raw_data']
if isinstance(rows, list) and len(rows) > 0:
latest = rows[0]
report['amount_bn'] = round(latest.get('amount', 0) / 1e8, 2)
return jsonify(_sanitize(report))
@app.route('/api/history/<int:report_id>', methods=['DELETE'])
def api_delete_history(report_id):
delete_history(report_id)
return jsonify({'ok': True})
# ==================== 交易日判断 ====================
# 中国法定节假日(需每年更新)
_CN_HOLIDAYS = {
# 2025
'2025-01-01', '2025-01-28', '2025-01-29', '2025-01-30',
'2025-01-31', '2025-02-03', '2025-02-04',
'2025-04-04', '2025-05-01', '2025-05-02', '2025-05-05',
'2025-06-02', '2025-10-01', '2025-10-02', '2025-10-03',
'2025-10-06', '2025-10-07', '2025-10-08',
# 2026
'2026-01-01', '2026-01-26', '2026-01-27', '2026-01-28',
'2026-01-29', '2026-01-30', '2026-02-02', '2026-02-03',
'2026-04-06', '2026-05-01', '2026-05-04', '2026-05-05',
'2026-06-19', '2026-10-01', '2026-10-02', '2026-10-05',
'2026-10-06', '2026-10-07', '2026-10-08',
}
def is_cn_trading_time():
"""判断当前是否为A股交易时间(交易日 9:30-11:30 / 13:00-15:00)"""
now = datetime.now()
date_str = now.strftime('%Y-%m-%d')
weekday = now.weekday() # 0=Mon … 6=Sun
# 周末非交易日
if weekday >= 5:
return False, 'weekend'
# 节假日非交易日
if date_str in _CN_HOLIDAYS:
return False, 'holiday'
h, m = now.hour, now.minute
total_min = h * 60 + m
AM_START = 9 * 60 + 30 # 570
AM_END = 11 * 60 + 30 # 690
PM_START = 13 * 60 + 0 # 780
PM_END = 15 * 60 + 0 # 900
if AM_START <= total_min < AM_END or PM_START <= total_min < PM_END:
return True, 'trading'
# 盘前/盘后
if total_min < AM_START:
return False, 'pre_market'
if AM_END <= total_min < PM_START:
return False, 'noon_break'
return False, 'after_market'
def is_open_time():
"""判断是否为开盘时段(9:30~9:35)"""
now = datetime.now()
weekday = now.weekday()
if weekday >= 5:
return False
date_str = now.strftime('%Y-%m-%d')
if date_str in _CN_HOLIDAYS:
return False
h, m = now.hour, now.minute
return h == 9 and 30 <= m <= 35
def is_close_time():
"""判断是否为收盘时段(14:50~15:00)"""
now = datetime.now()
weekday = now.weekday()
if weekday >= 5:
return False
date_str = now.strftime('%Y-%m-%d')
if date_str in _CN_HOLIDAYS:
return False
h, m = now.hour, now.minute
return h == 14 and 50 <= m <= 59 or (h == 15 and m == 0)
@app.route('/api/trading_status', methods=['GET'])
def api_trading_status():
"""返回当前A股交易状态,供前端决定是否启动自动刷新"""
is_trading, phase = is_cn_trading_time()
now = datetime.now()
return jsonify({
'is_trading': is_trading,
'phase': phase, # weekend/holiday/pre_market/trading/noon_break/after_market
'is_open': is_open_time(), # 开盘时段(9:30~9:35)
'is_close': is_close_time(), # 收盘时段(14:50~15:00)
'time': now.strftime('%H:%M:%S'),
'date': now.strftime('%Y-%m-%d'),
'weekday': now.weekday(),
})
@app.route('/api/search', methods=['GET'])
def api_search():
"""搜索股票,返回搜索结果列表供前端验证"""
query = request.args.get('q', '').strip()
if not query:
return jsonify({'error': '请输入搜索关键词', 'results': []})
results = []
# 如果是6位数字代码,直接验证
if re.match(r'^\d{6}$', query):
try:
from analyzer import parse_ts_code, get_stock_quote
ts_code, market = parse_ts_code(query)
full_code = ts_code.upper() + '.' + market.upper()
# 通过行情接口获取股票名称和价格
quote = get_stock_quote(full_code)
name = quote.get('name', ts_code) if quote else ts_code
results.append({
'name': name,
'code': ts_code,
'ts_code': full_code,
'market': market.upper(),
'price': quote.get('price', 0) if quote else 0
})
except Exception as e:
return jsonify({'error': f'无法获取股票信息: {str(e)}', 'results': []})
else:
# 通过名称搜索
from analyzer import _search_sina_with_timeout, _search_akshare_with_timeout
# Sina 搜索(逗号分隔格式)
sina_result = _search_sina_with_timeout(query, timeout_sec=5.0)
if sina_result:
parts = sina_result.split(';')
for part in parts:
if not part.strip():
continue
segs = part.split(',')
if len(segs) >= 4:
found_name = segs[0].strip()
code = segs[2].strip()
sym = segs[3].strip() # 格式如 sz002916
if not code or len(code) != 6:
continue
# 从符号中提取市场
if sym.startswith('sz'):
market = 'SZ'
elif sym.startswith('sh'):
market = 'SH'
else:
market = 'SZ' if code.startswith(('000', '002', '003', '300')) else 'SH'
ts_code = f'{code}.{market}'
results.append({
'name': found_name,
'code': code,
'ts_code': ts_code,
'market': market
})
# 限制返回数量
if len(results) >= 5:
break
# akshare 备用搜索
if not results:
df = _search_akshare_with_timeout(query, timeout_sec=6.0)
if df is not None:
# 精确匹配
exact = df[df['名称'] == query]
for _, row in exact.iterrows():
code = str(row['代码'])
market = 'SZ' if code.startswith(('000', '002', '003', '300')) else 'SH'
results.append({
'name': row['名称'],
'code': code,
'ts_code': f'{code}.{market}',
'market': market
})
# 模糊匹配
if len(results) < 5:
fuzzy = df[df['名称'].str.contains(query, na=False)]
for _, row in fuzzy.iterrows():
code = str(row['代码'])
market = 'SZ' if code.startswith(('000', '002', '003', '300')) else 'SH'
ts_code = f'{code}.{market}'
if not any(r['ts_code'] == ts_code for r in results):
results.append({
'name': row['名称'],
'code': code,
'ts_code': ts_code,
'market': market
})
if len(results) >= 5:
break
# 硬编码备用
if not results:
known = {
'深南电路': '002916.SZ',
'壹网壹创': '300792.SZ',
'天桥起重': '002523.SZ',
'蜂助手': '301382.SZ',
'宏昌科技': '301008.SZ',
'贵州茅台': '600519.SH',
'宁德时代': '300750.SZ',
'比亚迪': '002594.SZ',
'东方财富': '300059.SZ',
'中信证券': '600030.SH',
'中红医疗': '300981.SZ',
}
for name, ts_code in known.items():
if query in name:
code, market = ts_code.split('.')
results.append({
'name': name,
'code': code,
'ts_code': ts_code,
'market': market
})
if not results:
return jsonify({'error': f'未找到股票: {query}', 'results': []})
return jsonify({'results': results})
# ==================== 静态文件 ====================
# ==================== 新闻分类与信号判断 ====================
NEWS_CATEGORIES = {
'geopolitical': {
'name': '国际地缘',
'keywords': ['美国', '欧洲', '俄罗斯', '乌克兰', '中东', '以色列', '伊朗', '朝鲜', '中美', '贸易战', '关税', '制裁', '外交', 'G7', 'G20', '联合国', '北约', '欧盟', '黎巴嫩', '空袭', '停火', '冲突', '战争', '军事', '国防', '武装'],
'bullish_keywords': ['合作', '降息', '宽松', '谈判', '达成', '签署', '开放', '利好'],
'bearish_keywords': ['制裁', '加税', '摩擦', '对抗', '封锁', '冲突', '战争', '退出', '脱钩'],
},
'policy': {
'name': '财经政策',
'keywords': ['央行', '降准', '降息', '麻辣粉', '酸辣粉', 'LPR', '美联储', '鲍威尔', '财政', '证监会', '银保监', '政策', '救市', '利好', '利空', '注册制', '量化', 'IPO'],
'bullish_keywords': ['降息', '降准', '宽松', '利好', '支持', '鼓励', '扶持', '增量', '扩大', '改革', '牛市'],
'bearish_keywords': ['加息', '收紧', '利空', '调控', '限制', '严监管', 'IPO加速', '扩容'],
},
'stock': {
'name': '个股行情',
'keywords': ['涨停', '跌停', '龙头', '妖股', '白马', '业绩', '年报', '季报', '分红', '送转', '回购', '减持', '增持', '定增', '并购', '重组'],
'bullish_keywords': ['涨停', '业绩增长', '超预期', '增持', '回购', '分红', '送转', '利好', '突破', '创新高'],
'bearish_keywords': ['跌停', '业绩下滑', '亏损', '减持', '暴雷', '造假', '退市', 'ST', '预警'],
},
'oil': {
'name': '原油行情',
'keywords': ['原油', '石油', 'OPEC', 'WTI', '布伦特', 'Brent', '油价', '天然气', '能源', '原油期货', '国际油价', '原油价格', 'EIA', 'API库存', '沙特', '俄罗斯', '石油公司', '壳牌', '埃克森', '美孚', 'bp', 'BP', 'Petroleum', 'Oil', 'oil price', 'crude', '加拿大', '油气', '天然气', 'LNG', '燃油', '航空燃油', '石油', '油气'],
'bullish_keywords': ['减产', '供应紧张', '库存下降', '需求增长', '突破', '上涨', '大涨', '创新高'],
'bearish_keywords': ['增产', '供应过剩', '库存增加', '需求下降', '下跌', '崩盘', '大跌', '创新低'],
},
'gold': {
'name': '黄金行情',
'keywords': ['黄金', '白银', '贵金属', 'COMEX', '避险', '美元指数', '美联储', '黄金期货', '国际金价', '现货黄金', '黄金价格', '伦敦金', '纽约金', '央行购金', 'Gold', 'gold', 'XAU', '金价', '黄金ETF', '黄金股', '金矿', '央行增持', '贵金属', '贵金属', '铜价', '铜'],
'bullish_keywords': ['避险', '降息预期', '突破', '创新高', '央行增持', '美元走弱', '大涨', '飙升'],
'bearish_keywords': ['美元走强', '加息', '避险消退', '下跌', '回调', '大跌', '回落'],
},
'rate': {
'name': '利率汇率',
'keywords': ['利率', '美联储', '加息', '降息', '美元指数', '人民币', '汇率', '美债', '国债收益率', 'Libor', 'Shibor', 'LPR', 'FOMC', '鲍威尔', '美联储主席', '货币政策', '紧缩', '宽松', '利率决议', '联邦基金', '联邦公开市场', 'Fed', 'fed rate', '美元', '美元汇率', '人民币汇率'],
'bullish_keywords': ['降息', '宽松', '人民币升值', '利好', '美债上涨'],
'bearish_keywords': ['加息', '收紧', '人民币贬值', '美债下跌', '利空'],
},
'crypto': {
'name': '数字货币',
'keywords': ['比特币', 'BTC', 'ETH', '以太坊', '加密货币', '数字货币', '区块链', 'Web3', 'Coinbase', 'Binance', 'DOGE', 'SOL', '加密', 'Crypto', 'crypto', 'bitcoin', 'ethereum', '区块链', '数字资产', '虚拟货币', '稳定币', 'NFT', 'DeFi', 'Web3'],
'bullish_keywords': ['突破', '牛市', '机构入场', 'ETF', '批准', '新高', 'DeFi', '暴涨'],
'bearish_keywords': ['暴跌', '监管', '禁止', 'SEC', 'CFTC', '黑客', '被盗', '熊市', '崩盘'],
},
}
# 新闻数据源配置(单源模式)
NEWS_SOURCE = 'https://feed.mix.sina.com.cn/api/roll/get'
def classify_news(title, source):
"""根据标题关键词判断新闻类别和A股影响信号"""
title_lower = title.lower()
title_full = title + ' ' + source # 也包含来源
# 判断类别(按优先级排序)
category = 'other'
category_priority = ['geopolitical', 'oil', 'gold', 'rate', 'crypto', 'policy', 'stock']
for cat_key in category_priority:
if cat_key not in NEWS_CATEGORIES:
continue
cat_info = NEWS_CATEGORIES[cat_key]
for kw in cat_info['keywords']:
if kw in title_full or kw.lower() in title_lower:
category = cat_key
break
if category != 'other':
break
# 判断信号
signal = 'neutral' # neutral / bullish / bearish
cat_info = NEWS_CATEGORIES.get(category, {})
# 先检查利空关键词
for kw in (cat_info.get('bearish_keywords', []) if cat_info else []):
if kw in title_full:
signal = 'bearish'
break
# 再检查利好关键词(优先级更高)
if signal != 'bearish':
for kw in (cat_info.get('bullish_keywords', []) if cat_info else []):
if kw in title_full:
signal = 'bullish'
break
return category, signal
@app.route('/api/news', methods=['GET'])
def api_news():
"""获取新浪财经实时新闻(A股/财经资讯),分类并给出A股影响信号"""
try:
# 获取关注股票列表用于过滤个股资讯
watch_stocks = []
try:
watch_stocks = get_watchlist()
except:
pass
# 获取关注股票名称列表
watch_names = [w.get('name', '') for w in watch_stocks if w.get('name')]
watch_codes = [w.get('ts_code', '').split('.')[0] for w in watch_stocks if w.get('ts_code')]
# 获取新闻数据(单源模式)
news_data = []
headers = {
'Referer': 'https://finance.sina.com.cn/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
}
try:
resp = requests.get(NEWS_SOURCE,
params={'pageid': 153, 'lid': 2516, 'num': 100, 'versionNumber': '1.2.4', 'page': 1},
headers=headers, timeout=12)
data = resp.json()
news_data = data.get('result', {}).get('data', []) or []
except:
news_data = []
# 按类别分组
categorized = {k: [] for k in NEWS_CATEGORIES.keys()}
categorized['stock'] = [] # 个股行情板块单独处理
categorized['other'] = []
uncategorized_items = []
stock_news = [] # 存储与关注股票相关的资讯
for it in news_data:
if not isinstance(it, dict):
continue
# 解析时间戳
ctime_str = ''
ctime = it.get('ctime', '')
if ctime:
try:
ts = int(ctime)
dt = datetime.fromtimestamp(ts)
ctime_str = dt.strftime('%H:%M')
except (ValueError, OSError):
pass
title = it.get('title', '')
source = it.get('media_name') or it.get('source') or ''
category, signal = classify_news(title, source)
# 检查是否与关注股票相关
is_stock_related = False
matched_stock = ''
for name in watch_names:
if name and len(name) >= 2 and name in title:
is_stock_related = True
matched_stock = name
break
# 也检查股票代码
if not is_stock_related:
for code in watch_codes:
if code and len(code) == 6 and ('(' + code + ')' in title or code in title):
is_stock_related = True
matched_stock = code
break
if is_stock_related:
stock_news.append({
'time': ctime_str,
'title': title,
'source': source,
'url': it.get('url', ''),
'category': 'stock',
'signal': signal,
'signal_text': '看多' if signal == 'bullish' else '看空' if signal == 'bearish' else '中性',
'signal_emoji': '📈' if signal == 'bullish' else '📉' if signal == 'bearish' else '➡️',
'matched_stock': matched_stock,
})
continue # 已添加到个股行情,跳过常规分类
item = {
'time': ctime_str,
'title': title,
'source': source,
'url': it.get('url', ''),
'category': category,
'signal': signal,
'signal_text': '看多' if signal == 'bullish' else '看空' if signal == 'bearish' else '中性',
'signal_emoji': '📈' if signal == 'bullish' else '📉' if signal == 'bearish' else '➡️',
}
if category == 'other':
uncategorized_items.append(item)
else:
categorized[category].append(item)
# 将个股资讯添加到个股行情板块
categorized['stock'] = stock_news
# V1.7.1: 从东方财富获取关注股票个股新闻,丰富资讯来源
if watch_names:
try:
em_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Referer': 'https://www.eastmoney.com/',
}
for s in watch_stocks:
s_name = s.get('name', '')
s_code = s.get('ts_code', '').split('.')[0]
if not s_name or len(s_name) < 2:
continue
try:
# 使用东方财富搜索API获取个股新闻
em_url = f'https://search-api-web.eastmoney.com/search/jsonp?cb=jQuery¶m=%7B%22uid%22%3A%22%22%2C%22keyword%22%3A%22{s_name}%22%2C%22type%22%3A%5B%22cmsArticleWebOld%22%5D%2C%22client%22%3A%22web%22%2C%22clientType%22%3A%22web%22%7D'
em_resp = requests.get(em_url, headers=em_headers, timeout=5)
em_text = em_resp.text
# 解析JSONP响应
em_match = re.search(r'jQuery\((.+)\)', em_text)
if em_match:
import json
em_data = json.loads(em_match.group(1))
em_articles = em_data.get('data', {}).get('list', [])[:3]
for art in em_articles:
e_title = art.get('title', '') or art.get('art_title', '')
if not e_title:
continue
# 判断信号
e_sig = 'neutral'
e_emoji = '➡️'
e_title_lower = e_title.lower()
if any(kw in e_title_lower for kw in ['涨', '增', '利好', '突破', '涨停']):
e_sig = 'bullish'
e_emoji = '📈'
elif any(kw in e_title_lower for kw in ['跌', '减', '利空', '风险', '跌停']):
e_sig = 'bearish'
e_emoji = '📉'
categorized['stock'].append({
'time': '',
'title': e_title,
'source': '东方财富',
'url': art.get('url', '') or art.get('art_url', ''),
'category': 'stock',
'signal': e_sig,
'signal_text': '看多' if e_sig == 'bullish' else '看空' if e_sig == 'bearish' else '中性',
'signal_emoji': e_emoji,
'matched_stock': s_code,
})
except Exception:
continue
except Exception:
pass
# V1.6.9: 个股行情板块 - 获取关注股票的实时行情数据
if watch_stocks:
sina_syms = []
for s in watch_stocks:
c, m = parse_ts_code(s['ts_code'])
sina_syms.append(f'{m}{c}')
if sina_syms:
quotes = get_stock_quote(sina_syms)
stock_quotes = []
for s in watch_stocks:
c, m = parse_ts_code(s['ts_code'])
sym = f'{m}{c}'
q = quotes.get(sym, {})
if q and q.get('price', 0) > 0:
pct = q.get('pct_change', 0)
if pct > 0:
sig = 'bullish'
sig_emoji = '📈'
elif pct < 0:
sig = 'bearish'
sig_emoji = '📉'
else:
sig = 'neutral'
sig_emoji = '➡️'
stock_quotes.append({
'time': q.get('time', ''),
'title': f"{q.get('name', s.get('name', ''))} ({s['ts_code']}) {q.get('price', 0):.2f} {q.get('pct_change', 0):.2f}%",
'source': DATA_SOURCE,
'url': '',
'category': 'stock',
'signal': sig,
'signal_text': '看多' if sig == 'bullish' else '看空' if sig == 'bearish' else '中性',
'signal_emoji': sig_emoji,
'price': q.get('price', 0),
'pct_change': q.get('pct_change', 0),
'matched_stock': s['ts_code'],
})
# 将实时行情数据合并到个股行情板块(行情在前,新闻在后)
categorized['stock'] = stock_quotes + categorized['stock']
# 如果其他类太多,合并到财经政策
if len(uncategorized_items) > 10:
categorized['policy'].extend(uncategorized_items[:15])
uncategorized_items = uncategorized_items[15:]
return jsonify({
'categories': categorized,
'all_items': categorized['other'] + uncategorized_items, # 未分类的放all_items
'timestamp': datetime.now().strftime('%H:%M:%S'),
})
except Exception as e:
return jsonify({'categories': {}, 'all_items': [], 'error': str(e), 'timestamp': datetime.now().strftime('%H:%M:%S')}), 500
@app.route('/')
def index():
return send_from_directory('templates', 'index.html')
# ==================== V2.0.0: 华尔街量化模型专用接口 ====================
@app.route('/api/wallstreet/<path:ts_code>', methods=['GET'])
def api_wallstreet(ts_code):
"""仅获取华尔街量化模型分析结果"""
try:
from analyzer import get_stock_kline
kline = get_stock_kline(ts_code, days=365)
if kline is None or len(kline) < 60:
return jsonify({'error': 'K线数据不足'}), 400
ws = analyze_wallstreet(kline)
return jsonify(_sanitize(ws))
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/backtest/<path:ts_code>', methods=['GET'])
def api_backtest(ts_code):
"""单股快速回测"""
try:
kline = get_stock_kline(ts_code, days=500)
if kline is None or len(kline) < 100:
return jsonify({'error': '数据不足'}), 400
bt = quick_backtest(kline, lookback_days=250)
return jsonify(_sanitize(bt))
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/signal_history/<path:ts_code>', methods=['GET'])
def api_signal_history(ts_code):
"""获取该股票历史分析信号(量化报告中记录的买入/卖出信号)"""
try:
from database import get_history
all_history = get_history(limit=200)
signals = []
for h in all_history:
if not h.get('ts_code') or ts_code not in str(h.get('ts_code', '')):
continue
signal_text = h.get('signal', '观望')
signal_level = '买入' if signal_text == '买入' else '卖出' if '清仓' in signal_text else '观望'
signals.append({
'date': h.get('created_at', ''),
'price': h.get('latest_close', 0),
'signal': signal_text,
'signal_level': signal_level,
})
return jsonify(_sanitize(signals[-50:]))
except Exception as e:
return jsonify({'error': str(e), 'signals': []}), 200
@app.route('/api/stock_news/<path:ts_code>', methods=['GET'])
def api_stock_news(ts_code):
"""按股票名称搜索最新新闻(含多空分析)"""
try:
import requests as _req
# 获取股票名称
c, m = parse_ts_code(ts_code)
sym = f'{m}{c}'
q = get_stock_quote([sym]).get(sym, {})
stock_name = q.get('name', '')
if not stock_name or stock_name == ts_code:
# 从关注列表获取
watchlist = get_watchlist()
for w in watchlist:
if w.get('ts_code', '').upper() == ts_code.upper():
stock_name = w.get('name', '')
break
if not stock_name:
stock_name = ts_code.split('.')[0]
# 搜索新闻
news_list = []
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Referer': 'https://finance.sina.com.cn/',
}
# 新浪搜索
try:
search_url = f'https://search.sina.com.cn/news?q={stock_name}&range=title&c=news&sort=time'
sr = _req.get(search_url, headers=headers, timeout=8)
sr.encoding = 'utf-8'
items = re.findall(
r'<h2><a href="([^"]+)"[^>]*target="_blank">(.*?)</a></h2>',
sr.text, re.DOTALL
)
for url, title in items[:8]:
clean_title = re.sub(r'<[^>]+>', '', title).strip()
# 多空分析
signal = 'neutral'
if any(kw in clean_title for kw in ['涨', '增', '利好', '突破', '涨停', '强势', '牛']):
signal = 'bullish'
elif any(kw in clean_title for kw in ['跌', '减', '利空', '风险', '跌停', '预警', '崩']):
signal = 'bearish'
news_list.append({
'title': clean_title,
'url': url,
'source': '新浪财经',
'signal': signal,
'signal_text': '利好' if signal == 'bullish' else '利空' if signal == 'bearish' else '中性',
})
except Exception:
pass
# 东方财富搜索
if len(news_list) < 5:
try:
em_url = f'https://search-api-web.eastmoney.com/search/jsonp?param=%7B%22uid%22%3A%22%22%2C%22keyword%22%3A%22{stock_name}%22%2C%22type%22%3A%5B%22cmsArticleWebOld%22%5D%2C%22client%22%3A%22web%22%2C%22clientType%22%3A%22web%22%7D'
em_r = _req.get(em_url, headers=headers, timeout=5)
em_match = re.search(r'jQuery\((.+)\)', em_r.text)
if em_match:
import json
em_data = json.loads(em_match.group(1))
for art in em_data.get('data', {}).get('list', [])[:8]:
title = art.get('title', '') or art.get('art_title', '')
if not title:
continue
clean_title = re.sub(r'<[^>]+>', '', title).strip()
signal = 'neutral'
if any(kw in clean_title for kw in ['涨', '增', '利好', '突破', '涨停']):
signal = 'bullish'
elif any(kw in clean_title for kw in ['跌', '减', '利空', '风险', '跌停']):
signal = 'bearish'
dup = any(n['title'] == clean_title for n in news_list)
if not dup:
news_list.append({
'title': clean_title,
'url': art.get('url', '') or art.get('art_url', ''),
'source': '东方财富',
'signal': signal,
'signal_text': '利好' if signal == 'bullish' else '利空' if signal == 'bearish' else '中性',
})
except Exception:
pass
return jsonify(_sanitize({
'stock_name': stock_name,
'ts_code': ts_code,
'news': news_list[:12],
}))
except Exception as e:
return jsonify({'error': str(e), 'news': []}), 200
if __name__ == '__main__':
print(f'TANZG {__version__} 启动中...')
port = int(os.getenv('PORT', '5002'))
print(f'访问地址: http://localhost:{port}')
print(f'华尔街多维量化模型已集成 | 回测引擎已集成')
app.run(host='0.0.0.0', port=port, debug=False)
# TANZG 量价分析引擎 - Flask 后端
from flask import Flask, request, jsonify, send_from_directory
import akshare as ak
import pandas as pd
import requests
import json
import math
import os
import time
import re
import threading
import queue
from datetime import datetime
from analyzer import full_analysis, search_stock_by_name, parse_ts_code, get_stock_kline, get_augmented_kline, get_fund_flow_data, get_chip_data
from database import save_report, get_history, get_history_by_id, delete_history, _to_native
from database import save_recommendation, get_recommendation_history, get_recommendation_by_id
from database import get_watchlist, add_to_watchlist, remove_from_watchlist, update_watchlist_order, move_watchlist_item, watchlist_exists
# V2.0.0: 华尔街量化模型集成
from wallstreet import analyze_wallstreet
from backtest_integration import quick_backtest
def _sanitize(obj):
"""递归将 NaN/Inf/numpy 类型转换为 None 或 Python 原生类型"""
# 先做 numpy→原生类型转换
obj = _to_native(obj)
# 再处理 NaN/Inf
if isinstance(obj, dict):
return {k: _sanitize(v) for k, v in obj.items()}
if isinstance(obj, list):
return [_sanitize(x) for x in obj]
if isinstance(obj, float):
if math.isnan(obj) or math.isinf(obj):
return None
return obj
__version__ = 'V2.1.1'
app = Flask(__name__)
CONFIG_FILE = 'stock_config.json'
SINA_HEADERS = {
'Referer': 'https://finance.sina.com.cn',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
# ==================== Sina 直连 API ====================
def sina_quote(codes):
"""通过 Sina 实时行情接口获取多只股票/指数实时数据"""
if not codes:
return {}
syms = ','.join(codes)
url = f'https://hq.sinajs.cn/list={syms}'
try:
r = requests.get(url, headers=SINA_HEADERS, timeout=10)
r.encoding = 'gb18030'
except Exception:
return {}
result = {}
for line in r.text.strip().split('\n'):
m = re.search(r'hq_str_(\w+)="([^"]+)"', line)
if not m:
continue
sym = m.group(1)
fields = m.group(2).split(',')
if len(fields) < 5:
continue
try:
name = fields[0]
if sym.startswith(('s_sh', 's_sz', 'gb_')):
price = float(fields[1])
if sym.startswith('gb_'):
# 美股格式: name, price, pct%, datetime, change_abs, ...
# fields: [0]=name [1]=price [2]=pct% [3]=datetime [4]=change_abs
pct = float(fields[2]) if len(fields) > 2 else 0
change = float(fields[4]) if len(fields) > 4 else 0
vol = 0
amount = 0
else:
# A股指数格式(6字段): name, price, change_abs, pct%, vol, amount
# fields: [0]=name [1]=price [2]=change_abs [3]=pct% [4]=vol [5]=amount
change = float(fields[2]) if len(fields) > 2 else 0
pct = float(fields[3]) if len(fields) > 3 else 0
vol = float(fields[4]) if len(fields) > 4 else 0
amount = float(fields[5]) if len(fields) > 5 else 0
result[sym] = _sanitize({
'name': name, 'price': price, 'open': 0,
'high': 0, 'low': 0,
'prev_close': round(price - change, 2),
'change': round(change, 2),
'pct_change': round(pct, 2), 'volume': int(vol),
'amount': amount, 'time': '',
})
else:
# 个股格式(33字段): name,open,prev_close,price,high,low,bid1,ask1,vol,amount,...,date,time,flag
# [0]=名称 [1]=开盘 [2]=昨收 [3]=当前价 [4]=最高 [5]=最低
# [6]=买一 [7]=卖一 [8]=成交量(手) [9]=成交额(元) [30]=日期 [31]=时间