diff --git a/server.py b/server.py
index 26f70fde..b9addd63 100644
--- a/server.py
+++ b/server.py
@@ -549,13 +549,14 @@ def api_research_backtest():
from datetime import datetime, timedelta
version = request.args.get('strategy', 'v4.1')
period = request.args.get('period', '6m')
+ market = request.args.get('market', 'all') # all | a | hk
capital = float(request.args.get('capital', 1000000))
end_date = '2026-07-24' # 数据完整截止日
days = {'1m': 30, '6m': 185, '1y': 365, '2y': 730}.get(period, 185)
start_date = (datetime.strptime(end_date, '%Y-%m-%d') - timedelta(days=days)).strftime('%Y-%m-%d')
try:
from strategy_lab import run_backtest, analyze_trade_list, save_analysis
- result = run_backtest(version, start_date, end_date, capital)
+ result = run_backtest(version, start_date, end_date, capital, universe=market)
analysis = analyze_trade_list(result.get('trades', []), version)
save_analysis(version, analysis)
result['insights'] = analysis.get('insights', [])
diff --git a/static/index.html b/static/index.html
index 535c7eb9..c7ea616e 100644
--- a/static/index.html
+++ b/static/index.html
@@ -1934,6 +1934,8 @@ function renderResearch() {
'' +
+ '' +
'每版策略基于上一版归因分析迭代 · 点击行展开明细' +
'
' +
'';
@@ -1946,7 +1948,10 @@ async function loadStrategyList() {
const resp = await fetch('/api/research/strategies');
const data = await resp.json();
if (data.error) { listEl.innerHTML = '' + data.error + '
'; return; }
- renderStrategyTable(data.strategies || []);
+ const mkt = document.getElementById('btMarket')?.value || 'all';
+ let strats = data.strategies || [];
+ if (mkt !== 'all') strats = strats.filter(s => (s.market || 'all') === mkt || (s.market || 'all') === 'all');
+ renderStrategyTable(strats);
} catch(e) {
listEl.innerHTML = '加载失败: ' + e.message + '
';
}
@@ -2035,7 +2040,7 @@ function renderStrategyTable(strategies) {
const retCls = pf.total_return_pct == null ? '' : (pf.total_return_pct >= 0 ? 'text-green-400' : 'text-red-400');
const rowCls = 'border-b border-slate-800/50 hover:bg-slate-800/30 cursor-pointer' + (isCurrent ? ' bg-emerald-900/20 border-l-2 border-l-emerald-400' : '');
html += '' +
- '| ' + s.version + (isCurrent ? ' 当前' : '') + ' | ' +
+ '' + s.version + (isCurrent ? ' 当前' : '') + ((s.market && s.market !== 'all') ? ' ' + (s.market === 'hk' ? '港' : 'A') + '' : '') + ' | ' +
'' + (s.name || '') + (smallSample ? ' ⚠️' : '') + ' | ' +
cell('composite', s._composite, v => v, 'font-bold text-amber-300') +
cell('universality_score', (st.universality || {}).score, v => v + '/' + (st.universality || {}).months + '月') +
@@ -2063,7 +2068,8 @@ async function runStrategyBacktest(version) {
const detail = document.getElementById('strategyDetail');
detail.innerHTML = '⏳ 正在回测 ' + version + '(约15-30秒)...
';
try {
- const resp = await fetch('/api/research/backtest?strategy=' + version + '&period=' + period);
+ const mkt = document.getElementById('btMarket')?.value || 'all';
+ const resp = await fetch('/api/research/backtest?strategy=' + version + '&period=' + period + '&market=' + mkt);
const data = await resp.json();
if (data.error) { detail.innerHTML = '' + data.error + '
'; return; }
await loadStrategyList();
diff --git a/strategy_lab.py b/strategy_lab.py
index c7065ac2..560bf90b 100644
--- a/strategy_lab.py
+++ b/strategy_lab.py
@@ -258,6 +258,30 @@ STRATEGIES.update({
"v9归因反用:v7.1交易中weekly_up=False胜率78.4% vs True 60.9%——周线级回调中的日线动量回归正是本策略的核心边缘",
entry_overrides={"vol_ratio_min": 0.9, "vol_ratio_max": 2.0, "sector_slope_max": 1.0,
"hl_only": True, "rsi_delta_min": 6, "weekly_down_only": True}),
+ # ── 港股专用版本(港股通宇宙归因推导,2026-07-29)──
+ "h1.0": {
+ "version": "h1.0",
+ "name": "港股v1-高波动甜区",
+ "summary": "v7.1港股化:ATR≥2.8无上限+量比≥1.2无上限+MACD柱0~0.3+周线必须向上+恒指回调情景",
+ "hypothesis": "港股8619笔归因:ATR4.88~28胜率59%持续上涨(无过热惩罚),量比>1.86胜率57%(天量=强势),MACD柱0~0.03最佳,weekly_up=True+9pp(与A股相反须周线完好),恒指斜率回调买与A股同构",
+ "parent": "v7.1",
+ "created": "2026-07-29",
+ "config": {
+ "entry": {"min_score": 45, "min_momentum": 8,
+ "filters": {"adx_min": 20, "atr_pct_min": 2.8,
+ "roc_min": 8,
+ "macd_hist_min": 0, "macd_hist_max": 0.3,
+ "dist_ma20_min": 4,
+ "vol_ratio_min": 1.2,
+ "ma20_slope_max": 1.5,
+ "mkt_above_ma20": True, "mkt_slope_max": -0.05,
+ "hh_only": True, "hl_only": True,
+ "rsi_delta_min": 6, "weekly_up": True}},
+ "exit": {"tp_pct": 0.15, "sl_atr": 1.5, "max_hold_days": 20},
+ "sizing": {"kelly": True, "kelly_fraction": 0.5},
+ "eval_step": 1,
+ },
+ },
})
@@ -575,7 +599,7 @@ def calc_factors(bars, idx):
# ══════════════════════════════════════════════════════
# 回测引擎(配置驱动 + 12维上下文记录)
# ══════════════════════════════════════════════════════
-def run_backtest(strategy_version, start_date, end_date, capital=1000000, save=True):
+def run_backtest(strategy_version, start_date, end_date, capital=1000000, save=True, universe='all'):
strat = get_strategy(strategy_version)
cfg = strat['config']
entry_cfg, exit_cfg = cfg['entry'], cfg['exit']
@@ -597,6 +621,12 @@ def run_backtest(strategy_version, start_date, end_date, capital=1000000, save=T
""", (start_date, end_date)).fetchall()
conn.close()
+ # 市场过滤:hk=仅港股, a=仅A股, all=全部
+ if universe == 'hk':
+ stocks = [(c, n) for c, n in stocks if is_hk_code(c)]
+ elif universe == 'a':
+ stocks = [(c, n) for c, n in stocks if not is_hk_code(c)]
+
trades = []
screened = scored_n = 0
@@ -832,6 +862,7 @@ def run_backtest(strategy_version, start_date, end_date, capital=1000000, save=T
result = {
'strategy': strat['version'],
'strategy_name': strat['name'],
+ 'market': universe,
'period': f"{start_date} ~ {end_date}",
'capital': capital,
'total_stocks_screened': screened,
@@ -1095,9 +1126,14 @@ def init_table():
id INTEGER PRIMARY KEY AUTOINCREMENT,
version TEXT, name TEXT, summary TEXT, hypothesis TEXT, parent TEXT,
config_json TEXT, results_json TEXT, analysis_json TEXT,
- period TEXT, created_at TEXT
+ period TEXT, created_at TEXT, market TEXT DEFAULT 'all'
)
""")
+ # 兼容老表加 market 列
+ try:
+ conn.execute("ALTER TABLE strategy_research ADD COLUMN market TEXT DEFAULT 'all'")
+ except sqlite3.OperationalError:
+ pass
conn.commit()
conn.close()
@@ -1107,12 +1143,12 @@ def save_result(strat, result):
conn = sqlite3.connect(DB_PATH)
conn.execute("""
INSERT INTO strategy_research (version, name, summary, hypothesis, parent,
- config_json, results_json, period, created_at)
- VALUES (?,?,?,?,?,?,?,?,?)
+ config_json, results_json, period, created_at, market)
+ VALUES (?,?,?,?,?,?,?,?,?,?)
""", (strat['version'], strat['name'], strat['summary'], strat['hypothesis'],
strat.get('parent'), json.dumps(strat['config'], ensure_ascii=False),
json.dumps(result, ensure_ascii=False), result['period'],
- datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
+ datetime.now().strftime('%Y-%m-%d %H:%M:%S'), result.get('market', 'all')))
conn.commit()
conn.close()
@@ -1132,9 +1168,11 @@ def list_strategies():
init_table()
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
+ # 每个 (version, market) 组合取最新一条
rows = conn.execute("""
SELECT sr.* FROM strategy_research sr
- INNER JOIN (SELECT version, MAX(id) as max_id FROM strategy_research GROUP BY version) latest
+ INNER JOIN (SELECT version, COALESCE(market,'all') as mkt, MAX(id) as max_id
+ FROM strategy_research GROUP BY version, COALESCE(market,'all')) latest
ON sr.id = latest.max_id
ORDER BY sr.version
""").fetchall()
@@ -1147,19 +1185,21 @@ def list_strategies():
d['summary_stats'] = res.get('summary', {})
d['insights'] = (ana or {}).get('insights', [])
d['trades_count'] = len(res.get('trades', []))
+ d['market'] = d.get('market') or res.get('market') or 'all'
del d['results_json']
del d['analysis_json']
out.append(d)
- existing = {d['version'] for d in out}
+ existing = {(d['version'], d['market']) for d in out}
for v, s in STRATEGIES.items():
- if v not in existing:
+ if (v, 'all') not in existing and not any(d['version'] == v for d in out):
out.append({
'version': v, 'name': s['name'], 'summary': s['summary'],
'hypothesis': s['hypothesis'], 'parent': s.get('parent'),
'config_json': json.dumps(s['config'], ensure_ascii=False),
'summary_stats': {}, 'insights': [], 'created_at': s.get('created'),
+ 'market': 'all',
})
- out.sort(key=lambda x: x['version'])
+ out.sort(key=lambda x: (x['version'], x.get('market', 'all')))
return out