mirror of
https://github.com/NicolasBohn/NexQuant.git
synced 2026-07-29 16:37:43 +00:00
Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 944af06a87 | |||
| 97e42d7a1a | |||
| 5481e83f03 | |||
| 88c4cc4a33 | |||
| 01889a6b64 | |||
| 443c6d47b2 | |||
| b10d3512df | |||
| d75cba934e | |||
| 38fa760429 | |||
| 0ce6f6ec6d | |||
| d17d424ee9 | |||
| 5d8e53d208 | |||
| 7880a9315a | |||
| 17bba1a920 | |||
| 360df4083a | |||
| e2c2fefe9a | |||
| 32f7d66e07 | |||
| 4d6ef04411 |
@@ -14,7 +14,7 @@ jobs:
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Run Bandit (Security Scan)
|
||||
uses: PyCQA/bandit-action@v1
|
||||
@@ -25,9 +25,9 @@ jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.10"
|
||||
cache: "pip"
|
||||
|
||||
@@ -36,11 +36,11 @@ jobs:
|
||||
steps:
|
||||
# Checkout the repository to the GitHub Actions runner
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis
|
||||
- name: Run Codacy Analysis CLI
|
||||
uses: codacy/codacy-analysis-cli-action@d840f886c4bd4edc059706d09c6a1586111c540b
|
||||
uses: codacy/codacy-analysis-cli-action@562ee3e92b8e92df8b67e0a5ff8aa8e261919c08
|
||||
env:
|
||||
JAVA_TOOL_OPTIONS: "-Dfile.encoding=UTF-8"
|
||||
with:
|
||||
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
name: Validate Commit Messages
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -25,10 +25,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
@@ -64,7 +64,7 @@ jobs:
|
||||
|
||||
- name: Upload docs artifact
|
||||
if: github.ref == 'refs/heads/main'
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
uses: actions/upload-pages-artifact@v5
|
||||
with:
|
||||
path: docs/_build/html
|
||||
|
||||
|
||||
@@ -16,10 +16,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
|
||||
@@ -19,9 +19,9 @@ jobs:
|
||||
python-version: ["3.10", "3.11"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: "pip"
|
||||
@@ -49,9 +49,9 @@ jobs:
|
||||
name: Dependency Audit
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.10"
|
||||
cache: "pip"
|
||||
|
||||
@@ -19,10 +19,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "1.2.2"
|
||||
".": "1.3.3"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,44 @@
|
||||
# Changelog
|
||||
|
||||
## [1.3.3](https://github.com/TPTBusiness/Predix/compare/v1.3.2...v1.3.3) (2026-04-25)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **backtest:** replace broken MC permutation test with binomial win-rate test ([c38d894](https://github.com/TPTBusiness/Predix/commit/c38d89478f586825bfca5715a96ca70ccd8791a3))
|
||||
* **factors:** detect and correct look-ahead bias in daily-constant factors ([eb490a4](https://github.com/TPTBusiness/Predix/commit/eb490a461b66cbd815ae53ac5205115754712432))
|
||||
* **factors:** extend look-ahead rules to session factors and add intraday-factor guidance ([c24c100](https://github.com/TPTBusiness/Predix/commit/c24c100442d6487686c0578de0b32d240fcbf215))
|
||||
* **loop:** compress old experiment history in proposal prompt to reduce context size ([4bf90a9](https://github.com/TPTBusiness/Predix/commit/4bf90a905ba8b2aba2a818191c19998088cccaaf))
|
||||
* **strategies:** guard against None IC in acceptance check, disable slow wf_rolling ([2197f52](https://github.com/TPTBusiness/Predix/commit/2197f52150a50ef38d9e70991d7e48c8c30caec4))
|
||||
* **strategies:** handle None ic/sharpe/dd in rejected strategy log output ([ad2ad3a](https://github.com/TPTBusiness/Predix/commit/ad2ad3ab3360ea75ed3bbc90c12098b9c5cc0114))
|
||||
|
||||
## [1.3.2](https://github.com/TPTBusiness/Predix/compare/v1.3.1...v1.3.2) (2026-04-23)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **strategies:** guard against None IC in acceptance check, disable slow wf_rolling ([2197f52](https://github.com/TPTBusiness/Predix/commit/2197f52150a50ef38d9e70991d7e48c8c30caec4))
|
||||
* **strategies:** handle None ic/sharpe/dd in rejected strategy log output ([ad2ad3a](https://github.com/TPTBusiness/Predix/commit/ad2ad3ab3360ea75ed3bbc90c12098b9c5cc0114))
|
||||
|
||||
## [1.3.1](https://github.com/TPTBusiness/Predix/compare/v1.3.0...v1.3.1) (2026-04-21)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **deps:** bump python-dotenv to >=1.2.2 (CVE symlink overwrite) ([126ae7d](https://github.com/TPTBusiness/Predix/commit/126ae7d5fb556b677d09d10221862a0d648d697a))
|
||||
|
||||
## [1.3.0](https://github.com/TPTBusiness/Predix/compare/v1.2.2...v1.3.0) (2026-04-21)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **backtest:** add rolling walk-forward validation and Monte Carlo trade permutation test ([637a94c](https://github.com/TPTBusiness/Predix/commit/637a94c1d987da763869f4f9b73372a3f37d873c))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **security:** resolve all 30 Bandit security alerts (B301, B614, B104) ([ce5983d](https://github.com/TPTBusiness/Predix/commit/ce5983d9d59c4c34341fb1ec749e44bbcfc4a1c4))
|
||||
|
||||
## [1.2.2](https://github.com/TPTBusiness/Predix/compare/v1.2.1...v1.2.2) (2026-04-19)
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ ignore_missing_imports = true
|
||||
module = "llama"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
addopts = "-l -s --durations=0"
|
||||
addopts = "-l -s --durations=0 -m 'not slow'"
|
||||
log_cli = true
|
||||
log_cli_level = "info"
|
||||
log_date_format = "%Y-%m-%d %H:%M:%S"
|
||||
|
||||
@@ -11,16 +11,23 @@ from .vbt_backtest import (
|
||||
FTMO_MAX_LEVERAGE,
|
||||
FTMO_RISK_PER_TRADE,
|
||||
OOS_START_DEFAULT,
|
||||
WF_IS_YEARS,
|
||||
WF_OOS_YEARS,
|
||||
WF_STEP_YEARS,
|
||||
backtest_from_forward_returns,
|
||||
backtest_signal,
|
||||
backtest_signal_ftmo,
|
||||
monte_carlo_trade_pvalue,
|
||||
walk_forward_rolling,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'BacktestMetrics', 'FactorBacktester', 'ResultsDatabase',
|
||||
'CorrelationAnalyzer', 'PortfolioOptimizer', 'AdvancedRiskManager',
|
||||
'backtest_signal', 'backtest_signal_ftmo', 'backtest_from_forward_returns',
|
||||
'monte_carlo_trade_pvalue', 'walk_forward_rolling',
|
||||
'DEFAULT_BARS_PER_YEAR', 'DEFAULT_TXN_COST_BPS',
|
||||
'FTMO_INITIAL_CAPITAL', 'FTMO_MAX_DAILY_LOSS', 'FTMO_MAX_TOTAL_LOSS',
|
||||
'FTMO_MAX_LEVERAGE', 'FTMO_RISK_PER_TRADE', 'OOS_START_DEFAULT',
|
||||
'WF_IS_YEARS', 'WF_OOS_YEARS', 'WF_STEP_YEARS',
|
||||
]
|
||||
|
||||
@@ -342,6 +342,129 @@ def _apply_ftmo_mask(
|
||||
|
||||
OOS_START_DEFAULT = "2024-01-01"
|
||||
|
||||
# Rolling walk-forward default windows (IS years, OOS years, step years)
|
||||
WF_IS_YEARS = 3
|
||||
WF_OOS_YEARS = 1
|
||||
WF_STEP_YEARS = 1
|
||||
|
||||
|
||||
def monte_carlo_trade_pvalue(
|
||||
trade_pnl: pd.Series,
|
||||
n_permutations: int = 1000,
|
||||
seed: int = 0,
|
||||
) -> float:
|
||||
"""
|
||||
Monte Carlo permutation test on trade-level P&L.
|
||||
|
||||
Runs a one-sided binomial test on trade-level win rate.
|
||||
|
||||
Tests H0: win_rate = 0.5 (random trading) against H1: win_rate > 0.5.
|
||||
The ``n_permutations`` parameter is kept for API compatibility but is unused.
|
||||
|
||||
p < 0.05 → win rate is significantly above 50%, indicating a genuine per-trade edge.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
trade_pnl : pd.Series
|
||||
Per-trade net returns (output of ``_compute_trade_pnl``).
|
||||
n_permutations : int
|
||||
Number of random permutations (default 1000).
|
||||
seed : int
|
||||
RNG seed for reproducibility.
|
||||
|
||||
Returns
|
||||
-------
|
||||
float
|
||||
p-value in [0, 1]. Lower is better.
|
||||
"""
|
||||
if len(trade_pnl) < 2:
|
||||
return 1.0
|
||||
trades = trade_pnl.values.copy()
|
||||
# Binomial test: is the win rate significantly above 50%?
|
||||
# p = probability of observing >= n_wins out of n_trades under null (win_rate=0.5).
|
||||
# Low p → strategy has a significant positive edge per trade.
|
||||
from scipy.stats import binomtest
|
||||
n_wins = int((trades > 0).sum())
|
||||
n_total = len(trades)
|
||||
result = binomtest(n_wins, n_total, p=0.5, alternative="greater")
|
||||
return float(result.pvalue)
|
||||
|
||||
|
||||
def walk_forward_rolling(
|
||||
close: pd.Series,
|
||||
signal: pd.Series,
|
||||
leverage: float,
|
||||
txn_cost_bps: float = DEFAULT_TXN_COST_BPS,
|
||||
bars_per_year: int = DEFAULT_BARS_PER_YEAR,
|
||||
is_years: int = WF_IS_YEARS,
|
||||
oos_years: int = WF_OOS_YEARS,
|
||||
step_years: int = WF_STEP_YEARS,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Rolling walk-forward validation: multiple IS/OOS windows shifted by ``step_years``.
|
||||
|
||||
Each window runs an independent FTMO simulation on the IS and OOS slices.
|
||||
Produces aggregate OOS statistics to measure cross-time consistency.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict with keys:
|
||||
wf_n_windows, wf_oos_sharpe_mean, wf_oos_sharpe_std,
|
||||
wf_oos_monthly_return_mean, wf_oos_consistency (fraction of windows
|
||||
with OOS Sharpe > 0), wf_windows (list of per-window dicts)
|
||||
"""
|
||||
if not isinstance(close.index, pd.DatetimeIndex):
|
||||
return {"wf_n_windows": 0}
|
||||
|
||||
start_year = close.index[0].year
|
||||
end_year = close.index[-1].year
|
||||
|
||||
windows = []
|
||||
yr = start_year
|
||||
while True:
|
||||
is_start = pd.Timestamp(f"{yr}-01-01")
|
||||
is_end = pd.Timestamp(f"{yr + is_years}-01-01")
|
||||
oos_end = pd.Timestamp(f"{yr + is_years + oos_years}-01-01")
|
||||
if oos_end.year > end_year + 1:
|
||||
break
|
||||
is_mask = (close.index >= is_start) & (close.index < is_end)
|
||||
oos_mask = (close.index >= is_end) & (close.index < oos_end)
|
||||
if is_mask.sum() < 1000 or oos_mask.sum() < 1000:
|
||||
yr += step_years
|
||||
continue
|
||||
|
||||
window: Dict[str, Any] = {
|
||||
"is_start": str(is_start.date()),
|
||||
"is_end": str(is_end.date()),
|
||||
"oos_start": str(is_end.date()),
|
||||
"oos_end": str(oos_end.date()),
|
||||
}
|
||||
for mask, prefix in [(is_mask, "is"), (oos_mask, "oos")]:
|
||||
close_s = close.loc[mask]
|
||||
signal_s = signal.loc[mask]
|
||||
masked_s, _ = _apply_ftmo_mask(signal_s, close_s, leverage, txn_cost_bps)
|
||||
r = backtest_signal(close=close_s, signal=masked_s,
|
||||
txn_cost_bps=txn_cost_bps, bars_per_year=bars_per_year)
|
||||
window[f"{prefix}_sharpe"] = r.get("sharpe", 0.0)
|
||||
window[f"{prefix}_monthly_return_pct"] = r.get("monthly_return_pct", 0.0)
|
||||
window[f"{prefix}_n_trades"] = r.get("n_trades", 0)
|
||||
windows.append(window)
|
||||
yr += step_years
|
||||
|
||||
if not windows:
|
||||
return {"wf_n_windows": 0}
|
||||
|
||||
oos_sharpes = [w["oos_sharpe"] for w in windows]
|
||||
oos_monthly = [w["oos_monthly_return_pct"] for w in windows]
|
||||
return {
|
||||
"wf_n_windows": len(windows),
|
||||
"wf_oos_sharpe_mean": float(np.mean(oos_sharpes)),
|
||||
"wf_oos_sharpe_std": float(np.std(oos_sharpes)),
|
||||
"wf_oos_monthly_return_mean": float(np.mean(oos_monthly)),
|
||||
"wf_oos_consistency": float(np.mean([s > 0 for s in oos_sharpes])),
|
||||
"wf_windows": windows,
|
||||
}
|
||||
|
||||
|
||||
def backtest_signal_ftmo(
|
||||
close: pd.Series,
|
||||
@@ -354,6 +477,8 @@ def backtest_signal_ftmo(
|
||||
bars_per_year: int = DEFAULT_BARS_PER_YEAR,
|
||||
forward_returns: Optional[pd.Series] = None,
|
||||
oos_start: Optional[str] = OOS_START_DEFAULT,
|
||||
wf_rolling: bool = False,
|
||||
mc_n_permutations: int = 0,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
FTMO-compliant backtest of a strategy signal on EUR/USD.
|
||||
@@ -385,6 +510,13 @@ def backtest_signal_ftmo(
|
||||
Maximum leverage (default 30 = FTMO 1:30).
|
||||
oos_start : str or None
|
||||
Start of out-of-sample period (ISO date). None disables OOS split.
|
||||
wf_rolling : bool
|
||||
If True, run rolling walk-forward validation (multiple IS/OOS windows).
|
||||
Results are stored under ``wf_*`` keys. Default False.
|
||||
mc_n_permutations : int
|
||||
Number of Monte Carlo trade permutations. 0 = disabled (default).
|
||||
When > 0, computes ``mc_pvalue``: fraction of permuted sequences whose
|
||||
total return >= real total return. p < 0.05 indicates a genuine edge.
|
||||
"""
|
||||
stop_price = stop_pips * FTMO_PIP
|
||||
leverage_by_risk = risk_pct / (stop_price / eurusd_price)
|
||||
@@ -440,6 +572,28 @@ def backtest_signal_ftmo(
|
||||
result["is_n_bars"] = int(is_mask.sum())
|
||||
result["oos_n_bars"] = int(oos_mask.sum())
|
||||
|
||||
# Rolling walk-forward validation
|
||||
if wf_rolling:
|
||||
wf = walk_forward_rolling(
|
||||
close=close,
|
||||
signal=signal,
|
||||
leverage=leverage,
|
||||
txn_cost_bps=txn_cost_bps,
|
||||
bars_per_year=bars_per_year,
|
||||
)
|
||||
result.update(wf)
|
||||
|
||||
# Monte Carlo trade permutation test
|
||||
if mc_n_permutations > 0:
|
||||
position = masked_signal.shift(1).fillna(0)
|
||||
bar_ret = close.pct_change().fillna(0)
|
||||
txn_cost = txn_cost_bps / 10_000.0
|
||||
position_change = position.diff().abs().fillna(position.abs())
|
||||
strat_ret = position * bar_ret - position_change * txn_cost
|
||||
trade_pnl = _compute_trade_pnl(position, strat_ret)
|
||||
result["mc_pvalue"] = monte_carlo_trade_pvalue(trade_pnl, mc_n_permutations)
|
||||
result["mc_n_permutations"] = mc_n_permutations
|
||||
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ evolving_strategy_factor_implementation_v1_system: |-
|
||||
- ALWAYS use `min_periods=N` where N equals the window size in rolling calculations (e.g., `.rolling(20, min_periods=20)`)
|
||||
- ALWAYS handle infinite values after division: `.replace([np.inf, -np.inf], np.nan)` before saving results
|
||||
- ALWAYS use `groupby(level=1)` or `groupby('instrument')` before rolling operations on MultiIndex dataframes
|
||||
- Process the COMPLETE date range (2020-2026), do NOT filter by date
|
||||
- Process the COMPLETE date range available in the HDF5 file (do NOT filter by date — the file may contain 2024 debug data or full 2020-2026 data)
|
||||
- Use `groupby().transform()` instead of `groupby().apply()` for single-column assignments
|
||||
|
||||
Notice that you should not add any other text before or after the json format.
|
||||
|
||||
@@ -123,8 +123,8 @@ model_cls = AntiSymmetricConv
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
node_features = torch.load("node_features.pt")
|
||||
edge_index = torch.load("edge_index.pt")
|
||||
node_features = torch.load("node_features.pt", weights_only=True)
|
||||
edge_index = torch.load("edge_index.pt", weights_only=True)
|
||||
|
||||
# Model instantiation and forward pass
|
||||
model = AntiSymmetricConv(in_channels=node_features.size(-1))
|
||||
|
||||
@@ -78,8 +78,8 @@ model_cls = DirGNNConv
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
node_features = torch.load("node_features.pt")
|
||||
edge_index = torch.load("edge_index.pt")
|
||||
node_features = torch.load("node_features.pt", weights_only=True)
|
||||
edge_index = torch.load("edge_index.pt", weights_only=True)
|
||||
|
||||
# Model instantiation and forward pass
|
||||
model = DirGNNConv(MessagePassing())
|
||||
|
||||
@@ -187,8 +187,8 @@ model_cls = GPSConv
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
node_features = torch.load("node_features.pt")
|
||||
edge_index = torch.load("edge_index.pt")
|
||||
node_features = torch.load("node_features.pt", weights_only=True)
|
||||
edge_index = torch.load("edge_index.pt", weights_only=True)
|
||||
|
||||
# Model instantiation and forward pass
|
||||
model = GPSConv(channels=node_features.size(-1), conv=MessagePassing())
|
||||
|
||||
@@ -170,8 +170,8 @@ class LINKX(torch.nn.Module):
|
||||
model_cls = LINKX
|
||||
|
||||
if __name__ == "__main__":
|
||||
node_features = torch.load("node_features.pt")
|
||||
edge_index = torch.load("edge_index.pt")
|
||||
node_features = torch.load("node_features.pt", weights_only=True)
|
||||
edge_index = torch.load("edge_index.pt", weights_only=True)
|
||||
|
||||
# Model instantiation and forward pass
|
||||
model = LINKX(
|
||||
|
||||
@@ -102,8 +102,8 @@ class PMLP(torch.nn.Module):
|
||||
model_cls = PMLP
|
||||
|
||||
if __name__ == "__main__":
|
||||
node_features = torch.load("node_features.pt")
|
||||
edge_index = torch.load("edge_index.pt")
|
||||
node_features = torch.load("node_features.pt", weights_only=True)
|
||||
edge_index = torch.load("edge_index.pt", weights_only=True)
|
||||
|
||||
# Model instantiation and forward pass
|
||||
model = PMLP(
|
||||
|
||||
@@ -1180,8 +1180,8 @@ model_cls = ViSNet
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
node_features = torch.load("node_features.pt")
|
||||
edge_index = torch.load("edge_index.pt")
|
||||
node_features = torch.load("node_features.pt", weights_only=True)
|
||||
edge_index = torch.load("edge_index.pt", weights_only=True)
|
||||
|
||||
# Model instantiation and forward pass
|
||||
model = ViSNet()
|
||||
|
||||
@@ -125,8 +125,8 @@ class AntiSymmetricConv(torch.nn.Module):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
node_features = torch.load("node_features.pt")
|
||||
edge_index = torch.load("edge_index.pt")
|
||||
node_features = torch.load("node_features.pt", weights_only=True)
|
||||
edge_index = torch.load("edge_index.pt", weights_only=True)
|
||||
|
||||
# Model instantiation and forward pass
|
||||
model = AntiSymmetricConv(in_channels=node_features.size(-1))
|
||||
|
||||
+6
-6
@@ -85,12 +85,12 @@ def preprocess_script():
|
||||
This method applies the preprocessing steps to the training, validation, and test datasets.
|
||||
"""
|
||||
if os.path.exists("/kaggle/input/X_train.pkl"):
|
||||
X_train = pd.read_pickle("/kaggle/input/X_train.pkl")
|
||||
X_valid = pd.read_pickle("/kaggle/input/X_valid.pkl")
|
||||
y_train = pd.read_pickle("/kaggle/input/y_train.pkl")
|
||||
y_valid = pd.read_pickle("/kaggle/input/y_valid.pkl")
|
||||
X_test = pd.read_pickle("/kaggle/input/X_test.pkl")
|
||||
others = pd.read_pickle("/kaggle/input/others.pkl")
|
||||
X_train = pd.read_pickle("/kaggle/input/X_train.pkl") # nosec B301
|
||||
X_valid = pd.read_pickle("/kaggle/input/X_valid.pkl") # nosec B301
|
||||
y_train = pd.read_pickle("/kaggle/input/y_train.pkl") # nosec B301
|
||||
y_valid = pd.read_pickle("/kaggle/input/y_valid.pkl") # nosec B301
|
||||
X_test = pd.read_pickle("/kaggle/input/X_test.pkl") # nosec B301
|
||||
others = pd.read_pickle("/kaggle/input/others.pkl") # nosec B301
|
||||
|
||||
return X_train, X_valid, y_train, y_valid, X_test, *others
|
||||
X_train, X_valid, y_train, y_valid = prepreprocess()
|
||||
|
||||
+5
-5
@@ -82,11 +82,11 @@ def preprocess_script():
|
||||
This method applies the preprocessing steps to the training, validation, and test datasets.
|
||||
"""
|
||||
if os.path.exists("X_train.pkl"):
|
||||
X_train = pd.read_pickle("X_train.pkl")
|
||||
X_valid = pd.read_pickle("X_valid.pkl")
|
||||
y_train = pd.read_pickle("y_train.pkl")
|
||||
y_valid = pd.read_pickle("y_valid.pkl")
|
||||
X_test = pd.read_pickle("X_test.pkl")
|
||||
X_train = pd.read_pickle("X_train.pkl") # nosec B301
|
||||
X_valid = pd.read_pickle("X_valid.pkl") # nosec B301
|
||||
y_train = pd.read_pickle("y_train.pkl") # nosec B301
|
||||
y_valid = pd.read_pickle("y_valid.pkl") # nosec B301
|
||||
X_test = pd.read_pickle("X_test.pkl") # nosec B301
|
||||
return X_train, X_valid, y_train, y_valid, X_test
|
||||
|
||||
X_train, X_valid, y_train, y_valid, test, status_encoder, test_ids = prepreprocess()
|
||||
|
||||
+6
-6
@@ -73,12 +73,12 @@ def preprocess_script():
|
||||
This method applies the preprocessing steps to the training, validation, and test datasets.
|
||||
"""
|
||||
if os.path.exists("/kaggle/input/X_train.pkl"):
|
||||
X_train = pd.read_pickle("/kaggle/input/X_train.pkl")
|
||||
X_valid = pd.read_pickle("/kaggle/input/X_valid.pkl")
|
||||
y_train = pd.read_pickle("/kaggle/input/y_train.pkl")
|
||||
y_valid = pd.read_pickle("/kaggle/input/y_valid.pkl")
|
||||
X_test = pd.read_pickle("/kaggle/input/X_test.pkl")
|
||||
others = pd.read_pickle("/kaggle/input/others.pkl")
|
||||
X_train = pd.read_pickle("/kaggle/input/X_train.pkl") # nosec B301
|
||||
X_valid = pd.read_pickle("/kaggle/input/X_valid.pkl") # nosec B301
|
||||
y_train = pd.read_pickle("/kaggle/input/y_train.pkl") # nosec B301
|
||||
y_valid = pd.read_pickle("/kaggle/input/y_valid.pkl") # nosec B301
|
||||
X_test = pd.read_pickle("/kaggle/input/X_test.pkl") # nosec B301
|
||||
others = pd.read_pickle("/kaggle/input/others.pkl") # nosec B301
|
||||
y_train = pd.Series(y_train).reset_index(drop=True)
|
||||
y_valid = pd.Series(y_valid).reset_index(drop=True)
|
||||
|
||||
|
||||
@@ -29,6 +29,83 @@ from rdagent.scenarios.qlib.experiment.model_experiment import QlibModelExperime
|
||||
DIRNAME = Path(__file__).absolute().resolve().parent
|
||||
DIRNAME_local = Path.cwd()
|
||||
|
||||
|
||||
def _shift_daily_constant_factor_if_needed(factor_col: "pd.Series", factor_name: str) -> "pd.Series":
|
||||
"""Detect and fix look-ahead bias in daily-constant factors.
|
||||
|
||||
A factor is "daily-constant" when every minute bar within the same calendar
|
||||
day carries an identical value. This happens when LLM code computes a daily
|
||||
aggregate (e.g. today's log return) and forward-fills it across all intraday
|
||||
bars without shifting — meaning the end-of-day value is visible at 00:00.
|
||||
|
||||
Fix: shift by one trading day so that the value assigned to day T is the
|
||||
aggregate computed from day T-1, eliminating the forward-looking information.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
notnull = factor_col.dropna()
|
||||
if len(notnull) < 200:
|
||||
return factor_col
|
||||
|
||||
datetimes = notnull.index.get_level_values("datetime")
|
||||
dates = datetimes.normalize()
|
||||
|
||||
# Sample up to 50 random days and check intra-day uniqueness
|
||||
unique_dates = pd.Series(dates.unique())
|
||||
sample_dates = unique_dates.sample(min(50, len(unique_dates)), random_state=42)
|
||||
|
||||
daily_unique_counts = []
|
||||
for d in sample_dates:
|
||||
mask = dates == d
|
||||
vals = notnull.values[mask]
|
||||
if len(vals) > 1:
|
||||
daily_unique_counts.append(len(np.unique(vals[~np.isnan(vals)])))
|
||||
|
||||
if not daily_unique_counts:
|
||||
return factor_col
|
||||
|
||||
# If >90% of sampled days have exactly 1 unique value → daily-constant
|
||||
fraction_constant = sum(1 for c in daily_unique_counts if c == 1) / len(daily_unique_counts)
|
||||
if fraction_constant < 0.90:
|
||||
return factor_col # Intraday factor — no shift needed
|
||||
|
||||
logger.warning(
|
||||
f"[LookAheadFix] Factor '{factor_name}' is daily-constant "
|
||||
f"({fraction_constant:.0%} of days). Applying 1-day shift to remove look-ahead bias."
|
||||
)
|
||||
|
||||
# Shift: for each instrument, map daily values forward by 1 trading day
|
||||
instruments = factor_col.index.get_level_values("instrument").unique()
|
||||
shifted_parts = []
|
||||
for inst in instruments:
|
||||
inst_series = factor_col.xs(inst, level="instrument")
|
||||
# Get one value per calendar day (the first non-null bar)
|
||||
inst_dt = inst_series.index.normalize()
|
||||
daily_vals = inst_series.groupby(inst_dt).first()
|
||||
# Shift by 1 day
|
||||
daily_vals_shifted = daily_vals.shift(1)
|
||||
# Forward-fill back to minute bars
|
||||
minute_idx = inst_series.index
|
||||
minute_dates = minute_idx.normalize()
|
||||
shifted_minute = minute_dates.map(daily_vals_shifted)
|
||||
shifted_s = pd.Series(
|
||||
shifted_minute.values,
|
||||
index=pd.MultiIndex.from_arrays(
|
||||
[inst_series.index, [inst] * len(inst_series)],
|
||||
names=["datetime", "instrument"],
|
||||
),
|
||||
name=factor_col.name,
|
||||
)
|
||||
shifted_parts.append(shifted_s)
|
||||
|
||||
return pd.concat(shifted_parts).sort_index()
|
||||
|
||||
except Exception as e:
|
||||
logger.debug(f"[LookAheadFix] Could not apply daily shift for '{factor_name}': {e}")
|
||||
return factor_col
|
||||
|
||||
|
||||
# TODO: supporting multiprocessing and keep previous results
|
||||
|
||||
|
||||
@@ -391,8 +468,19 @@ class QlibFactorRunner(CachedRunner[QlibFactorExperiment]):
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
# Get workspace path
|
||||
workspace_path = exp.experiment_workspace.workspace_path
|
||||
# Get workspace path — factor code and result.h5 live in sub_workspace_list[0],
|
||||
# not in experiment_workspace (which is the Qlib template workspace).
|
||||
workspace_path = None
|
||||
if exp.sub_workspace_list:
|
||||
for ws in exp.sub_workspace_list:
|
||||
if ws is not None and hasattr(ws, 'workspace_path'):
|
||||
candidate = ws.workspace_path / "result.h5"
|
||||
if candidate.exists():
|
||||
workspace_path = ws.workspace_path
|
||||
break
|
||||
if workspace_path is None:
|
||||
# Fallback to experiment_workspace
|
||||
workspace_path = exp.experiment_workspace.workspace_path
|
||||
if workspace_path is None:
|
||||
return None
|
||||
|
||||
@@ -409,6 +497,12 @@ class QlibFactorRunner(CachedRunner[QlibFactorExperiment]):
|
||||
factor_col = factor_values.iloc[:, 0]
|
||||
factor_name = factor_values.columns[0]
|
||||
|
||||
# Detect and fix look-ahead bias in daily-constant factors.
|
||||
# If a factor has the same value for all minute bars within each calendar day
|
||||
# it was computed from same-day data (e.g. today's close return at 00:00).
|
||||
# Fix: shift by 1 trading day so value at day T = aggregate of day T-1.
|
||||
factor_col = _shift_daily_constant_factor_if_needed(factor_col, factor_name)
|
||||
|
||||
# Load source data for forward returns
|
||||
data_path = (
|
||||
Path(__file__).parent.parent.parent.parent.parent
|
||||
@@ -587,10 +681,12 @@ class QlibFactorRunner(CachedRunner[QlibFactorExperiment]):
|
||||
from pathlib import Path
|
||||
from rdagent.components.backtesting import ResultsDatabase
|
||||
|
||||
# Get factor name from hypothesis
|
||||
# Get factor name: prefer hypothesis, fallback to result Series 'factor_name' key
|
||||
factor_name = "unknown"
|
||||
if hasattr(exp, 'hypothesis') and exp.hypothesis is not None:
|
||||
factor_name = getattr(exp.hypothesis, 'hypothesis', 'unknown')
|
||||
if factor_name == 'unknown' and isinstance(result, pd.Series) and 'factor_name' in result.index:
|
||||
factor_name = str(result['factor_name'])
|
||||
|
||||
# Check if already rejected by protection
|
||||
if getattr(exp, 'rejected_by_protection', False):
|
||||
@@ -824,41 +920,74 @@ class QlibFactorRunner(CachedRunner[QlibFactorExperiment]):
|
||||
"""
|
||||
Save factor time-series values as parquet for strategy building.
|
||||
|
||||
This is essential for walk-forward validation and strategy combination.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
factor_name : str
|
||||
Name of the factor
|
||||
exp : QlibFactorExperiment
|
||||
The experiment with factor values
|
||||
Reruns the factor code on the FULL 6-year dataset so the parquet covers
|
||||
the complete backtest range (not just the debug 2024 subset).
|
||||
"""
|
||||
import os as _os
|
||||
import subprocess
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
# Get workspace path
|
||||
workspace_path = exp.experiment_workspace.workspace_path
|
||||
# factor.py lives in sub_workspace_list[0], not experiment_workspace
|
||||
workspace_path = None
|
||||
if exp.sub_workspace_list:
|
||||
for ws in exp.sub_workspace_list:
|
||||
if ws is not None and hasattr(ws, 'workspace_path'):
|
||||
fp = ws.workspace_path / "factor.py"
|
||||
if fp.exists():
|
||||
workspace_path = ws.workspace_path
|
||||
break
|
||||
if workspace_path is None:
|
||||
workspace_path = exp.experiment_workspace.workspace_path
|
||||
if workspace_path is None:
|
||||
return
|
||||
|
||||
result_h5 = workspace_path / "result.h5"
|
||||
if not result_h5.exists():
|
||||
factor_py = workspace_path / "factor.py"
|
||||
if not factor_py.exists():
|
||||
return
|
||||
|
||||
# Read factor values
|
||||
project_root = Path(__file__).parent.parent.parent.parent.parent
|
||||
full_data = (
|
||||
project_root
|
||||
/ "git_ignore_folder"
|
||||
/ "factor_implementation_source_data"
|
||||
/ "intraday_pv.h5"
|
||||
)
|
||||
if not full_data.exists():
|
||||
return
|
||||
|
||||
# Run factor code on full data in a temp workspace
|
||||
import pandas as pd
|
||||
df = pd.read_hdf(str(result_h5), key="data")
|
||||
with tempfile.TemporaryDirectory(prefix="predix_fullval_") as tmp_dir:
|
||||
tmp = Path(tmp_dir)
|
||||
shutil.copy(str(factor_py), str(tmp / "factor.py"))
|
||||
shutil.copy(str(full_data), str(tmp / "intraday_pv.h5"))
|
||||
|
||||
ret = subprocess.run(
|
||||
["python", "factor.py"],
|
||||
cwd=str(tmp),
|
||||
capture_output=True,
|
||||
timeout=300,
|
||||
)
|
||||
if ret.returncode != 0:
|
||||
# Fall back to debug-data result if full-data run fails
|
||||
result_h5 = workspace_path / "result.h5"
|
||||
if not result_h5.exists():
|
||||
return
|
||||
df = pd.read_hdf(str(result_h5), key="data")
|
||||
else:
|
||||
result_h5_full = tmp / "result.h5"
|
||||
if not result_h5_full.exists():
|
||||
return
|
||||
df = pd.read_hdf(str(result_h5_full), key="data")
|
||||
|
||||
if df is None or df.empty:
|
||||
return
|
||||
|
||||
# Get the factor series (first column)
|
||||
series = df.iloc[:, 0]
|
||||
series.name = factor_name
|
||||
|
||||
# Save to results/factors/values/
|
||||
project_root = Path(__file__).parent.parent.parent.parent.parent
|
||||
|
||||
# Parallel run isolation
|
||||
parallel_run_id = _os.getenv("PARALLEL_RUN_ID", "0")
|
||||
if parallel_run_id != "0":
|
||||
values_dir = project_root / "results" / "runs" / f"run{parallel_run_id}" / "factors" / "values"
|
||||
@@ -866,16 +995,11 @@ class QlibFactorRunner(CachedRunner[QlibFactorExperiment]):
|
||||
values_dir = project_root / "results" / "factors" / "values"
|
||||
|
||||
values_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Safe filename
|
||||
safe_name = factor_name.replace("/", "_").replace("\\", "_").replace(" ", "_")[:100]
|
||||
parquet_path = values_dir / f"{safe_name}.parquet"
|
||||
series.to_frame().to_parquet(str(parquet_path))
|
||||
|
||||
# Save as parquet (with datetime index)
|
||||
series.to_parquet(str(parquet_path))
|
||||
|
||||
except Exception as e:
|
||||
# Don't let factor value saving break the main workflow
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _log_result_warnings(self, factor_name: str, result, metrics: dict) -> None:
|
||||
|
||||
@@ -23,14 +23,25 @@ $low: low price at 1-minute bar.
|
||||
$volume: volume at 1-minute bar (tick volume for FX).
|
||||
|
||||
## Important Notes for 1min Data
|
||||
- 96 bars = 1 trading day (24 hours for FX)
|
||||
- 1 bar = 1 minute (confirmed)
|
||||
- 16 bars = 16 minutes
|
||||
- 4 bars = 4 minutes
|
||||
- 1 bar = 1 minute
|
||||
- 60 bars = 1 hour
|
||||
- ~1440 bars = 1 full trading day (FX trades nearly 24h, Mon 00:00 - Fri 22:00 UTC approx.)
|
||||
- Typical bars per calendar day: ~1200-1440 (varies by weekday, holidays have fewer)
|
||||
- Do NOT assume 96 bars/day — the actual count depends on the date
|
||||
- Data range: 2020-01-01 to 2026-03-20
|
||||
- Instrument: EURUSD
|
||||
- Timezone: UTC
|
||||
|
||||
## IMPORTANT: Bars per Day Correction
|
||||
The dataset has approximately 1440 bars per full trading day (1 bar = 1 minute, ~24h of FX trading).
|
||||
Some older documentation incorrectly stated "96 bars = 1 day" — this is WRONG. Always use:
|
||||
- 60 bars = 1 hour
|
||||
- 480 bars = 8 hours (London session 08:00-16:00 UTC)
|
||||
- 180 bars = 3 hours (London/NY overlap 13:00-16:00 UTC)
|
||||
Use datetime hour filtering (e.g., `df[df.index.get_level_values('datetime').hour.between(8, 15)]`)
|
||||
to select session bars — do NOT use bar-count offsets to define sessions.
|
||||
|
||||
## Session Times (UTC)
|
||||
- Asian: 00:00-08:00 UTC (low volatility)
|
||||
- London: 08:00-16:00 UTC (high volatility)
|
||||
|
||||
@@ -104,7 +104,7 @@ qlib_factor_strategy: |-
|
||||
result_df.columns = ['daily_volume_price_divergence']
|
||||
```
|
||||
|
||||
4. **Process ALL data — do not filter dates**: The source HDF5 contains data from 2020-01-01 to 2026-03-20. Do NOT filter to a single year. If your output has only 314 entries (one year of daily data), the factor will be rejected. Expected output: ~1500+ daily entries for 2020-2026.
|
||||
4. **Process ALL data — do not filter dates**: The source HDF5 contains data from 2020-01-01 to 2026-03-20 (development runs may use a 2024-only debug dataset with ~300 entries, which is acceptable). Do NOT filter to a single year in your code. Write your code to process whatever date range is available in the HDF5 file — do not hardcode date filters. Expected output for production data: ~1500+ daily entries for 2020-2026. Expected output for debug data: ~300 daily entries for 2024. Both are valid.
|
||||
|
||||
5. **Use `transform()` instead of `apply()` for per-group calculations**: `transform()` preserves the original index while `apply()` may reduce the number of rows unexpectedly:
|
||||
```python
|
||||
@@ -121,6 +121,35 @@ qlib_factor_strategy: |-
|
||||
assert result_df.index.names == ['datetime', 'instrument'], f"Index names must be ['datetime', 'instrument'], got {result_df.index.names}"
|
||||
```
|
||||
|
||||
7. **NEVER use same-day aggregations as the factor value — always shift by 1 day**: If your factor computes a daily aggregate (e.g. daily close return, daily OHLC range, daily volume), that aggregate is only known at end-of-day. Using it at the start of the same day is look-ahead bias. You MUST shift the daily aggregate by 1 day before forward-filling to minute bars:
|
||||
```python
|
||||
# WRONG: look-ahead bias! Today's close return is not known at 00:00
|
||||
daily_ret = df['$close'].groupby(level='instrument').resample('1D', level='datetime').last().pct_change()
|
||||
result_df['my_factor'] = daily_ret.groupby(level='instrument').transform(lambda x: x.reindex(df.index.get_level_values('datetime'), method='ffill'))
|
||||
|
||||
# CORRECT: shift by 1 trading day so factor value at day T = aggregate of day T-1
|
||||
daily_close = df.groupby([df.index.get_level_values('datetime').normalize(), df.index.get_level_values('instrument')])['$close'].last()
|
||||
daily_close.index.names = ['date', 'instrument']
|
||||
daily_ret = daily_close.groupby(level='instrument').pct_change().shift(1) # <-- shift(1) is MANDATORY
|
||||
# then map back to minute bars via ffill
|
||||
```
|
||||
This rule applies to ALL daily aggregations: returns, OHLC stats, volume, momentum, slopes, etc.
|
||||
**Session-based aggregations (London, NY, Asian session returns) are also daily aggregations** — the London
|
||||
session (08:00-16:00 UTC) ends at 16:00, so its return must be shifted by 1 day before use.
|
||||
Intraday rolling factors (e.g. 30-min rolling std computed at bar t using only bars t-N..t-1) do NOT need this shift.
|
||||
|
||||
8. **PREFER pure intraday rolling factors**: Factors that use only a trailing window of recent bars (e.g.
|
||||
rolling(30).mean() of returns, RSI(14), Bollinger Band z-score) have NO look-ahead risk and vary every
|
||||
minute. These are the best candidates for short-horizon (60-180 bar) prediction. Examples:
|
||||
- Rolling 15-min / 30-min / 60-min return momentum (15, 30, 60 bars respectively)
|
||||
- Rolling volatility (std of returns over 20-60 bars)
|
||||
- Distance of close from N-bar moving average (z-score)
|
||||
- RSI or similar oscillators computed on 1-min bars
|
||||
- VWAP deviation (requires volume — use $volume column)
|
||||
Always use `.shift(1)` on the lagged window (e.g. `rolling(N).mean().shift(1)`) to avoid using the
|
||||
current bar's own price in its own feature value.
|
||||
NOTE: 1 bar = 1 minute. The data has ~1440 bars per full trading day. Do NOT use 96 as a day proxy.
|
||||
|
||||
qlib_factor_output_format: |-
|
||||
Your output should be a pandas dataframe similar to the following example information:
|
||||
<class 'pandas.core.frame.DataFrame'>
|
||||
|
||||
@@ -152,9 +152,41 @@ class QlibQuantHypothesisGen(FactorAndModelHypothesisGen):
|
||||
factor_inserted = True
|
||||
if len(specific_trace.hist) > 0:
|
||||
specific_trace.hist.reverse()
|
||||
hypothesis_and_feedback = T("scenarios.qlib.prompts:hypothesis_and_feedback").r(
|
||||
trace=specific_trace,
|
||||
)
|
||||
# Keep only the 2 most recent experiments in full detail; compress older ones
|
||||
# to brief bullet points to stay within the LLM context window.
|
||||
FULL_DETAIL_COUNT = 2
|
||||
old_hist = specific_trace.hist[:-FULL_DETAIL_COUNT] if len(specific_trace.hist) > FULL_DETAIL_COUNT else []
|
||||
recent_hist = specific_trace.hist[-FULL_DETAIL_COUNT:] if len(specific_trace.hist) > FULL_DETAIL_COUNT else specific_trace.hist
|
||||
|
||||
parts = []
|
||||
if old_hist:
|
||||
summary_lines = ["## Earlier experiments (summarized):"]
|
||||
for exp, fb in old_hist:
|
||||
factor_names = []
|
||||
for task in exp.sub_tasks:
|
||||
if task is not None and hasattr(task, "factor_name"):
|
||||
factor_names.append(task.factor_name)
|
||||
elif task is not None and hasattr(task, "model_type"):
|
||||
factor_names.append(getattr(task, "model_type", "model"))
|
||||
names_str = ", ".join(factor_names) if factor_names else "unknown"
|
||||
ic_str = ""
|
||||
try:
|
||||
if exp.result is not None:
|
||||
ic_val = exp.result.loc["IC"] if "IC" in exp.result.index else ""
|
||||
ic_str = f" IC={ic_val:.4f}" if ic_val != "" else ""
|
||||
except Exception:
|
||||
pass
|
||||
decision_str = "PASS" if fb.decision else "FAIL"
|
||||
obs_short = (fb.observations or "")[:120].replace("\n", " ")
|
||||
summary_lines.append(f"- [{decision_str}]{ic_str} {names_str}: {obs_short}")
|
||||
parts.append("\n".join(summary_lines))
|
||||
|
||||
if recent_hist:
|
||||
recent_trace = Trace(specific_trace.scen)
|
||||
recent_trace.hist = recent_hist
|
||||
parts.append(T("scenarios.qlib.prompts:hypothesis_and_feedback").r(trace=recent_trace))
|
||||
|
||||
hypothesis_and_feedback = "\n\n".join(parts)
|
||||
else:
|
||||
hypothesis_and_feedback = "No previous hypothesis and feedback available."
|
||||
|
||||
|
||||
@@ -391,7 +391,7 @@ def set_baseline():
|
||||
return jsonify({"baseline_score": score, "status": "set"})
|
||||
|
||||
|
||||
def run_server(task: str, base_model: str, workspace: str, host: str = "0.0.0.0", port: int = 5000):
|
||||
def run_server(task: str, base_model: str, workspace: str, host: str = "127.0.0.1", port: int = 5000):
|
||||
"""启动服务器"""
|
||||
init_server(task, base_model, workspace)
|
||||
logger.info(f"Grading Server | task={task} | {host}:{port}")
|
||||
@@ -435,7 +435,7 @@ class LocalServerContext(GradingServerContext):
|
||||
logger.info(f"[Local Mode] Starting evaluation server on port {self.port}...")
|
||||
self.server = init_server(self.task, self.base_model, self.workspace)
|
||||
|
||||
self._http_server = make_server("0.0.0.0", self.port, app, threaded=True)
|
||||
self._http_server = make_server("0.0.0.0", self.port, app, threaded=True) # nosec B104 — intentional: Docker sandbox requires all-interface binding
|
||||
self._thread = threading.Thread(target=self._http_server.serve_forever, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
@@ -488,7 +488,7 @@ if __name__ == "__main__":
|
||||
parser.add_argument("--base-model", type=str, default="")
|
||||
parser.add_argument("--workspace", type=str, default=".")
|
||||
parser.add_argument("--port", type=int, default=5000)
|
||||
parser.add_argument("--host", type=str, default="0.0.0.0")
|
||||
parser.add_argument("--host", type=str, default="127.0.0.1")
|
||||
args = parser.parse_args()
|
||||
|
||||
run_server(args.task, args.base_model, args.workspace, args.host, args.port)
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ tables
|
||||
tree-sitter-python
|
||||
tree-sitter
|
||||
|
||||
python-dotenv
|
||||
python-dotenv>=1.2.2 # CVE: symlink following allows arbitrary file overwrite
|
||||
|
||||
# infrastructure related.
|
||||
docker
|
||||
|
||||
@@ -198,6 +198,55 @@ def scan_factors(workspace_dir: Path, skip_evaluated: bool = True) -> List[Facto
|
||||
return factors
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Look-ahead bias detection for daily-constant factors
|
||||
# ---------------------------------------------------------------------------
|
||||
def _shift_daily_constant_factor_if_needed(factor_col: "pd.Series", factor_name: str) -> "pd.Series":
|
||||
"""Detect daily-constant factors (look-ahead bias) and shift by 1 trading day."""
|
||||
sample_days = factor_col.index.get_level_values("datetime").normalize().unique()
|
||||
if len(sample_days) < 10:
|
||||
return factor_col
|
||||
rng = np.random.default_rng(42)
|
||||
days_to_check = rng.choice(sample_days, size=min(50, len(sample_days)), replace=False)
|
||||
constant_count = 0
|
||||
for day in days_to_check:
|
||||
day_mask = factor_col.index.get_level_values("datetime").normalize() == day
|
||||
day_vals = factor_col[day_mask].dropna()
|
||||
if len(day_vals) == 0:
|
||||
continue
|
||||
if day_vals.nunique() == 1:
|
||||
constant_count += 1
|
||||
fraction_constant = constant_count / len(days_to_check)
|
||||
if fraction_constant < 0.90:
|
||||
return factor_col
|
||||
# Shift by 1 trading day per instrument
|
||||
import logging
|
||||
logging.getLogger(__name__).info(
|
||||
"Factor '%s' is %.0f%% daily-constant — shifting 1 trading day to fix look-ahead bias",
|
||||
factor_name, fraction_constant * 100,
|
||||
)
|
||||
instruments = factor_col.index.get_level_values("instrument").unique() if "instrument" in factor_col.index.names else [None]
|
||||
shifted_parts = []
|
||||
for instr in instruments:
|
||||
if instr is not None:
|
||||
mask = factor_col.index.get_level_values("instrument") == instr
|
||||
col_instr = factor_col[mask]
|
||||
else:
|
||||
col_instr = factor_col
|
||||
dates = col_instr.index.get_level_values("datetime").normalize()
|
||||
trading_days = dates.unique().sort_values()
|
||||
day_first = col_instr.groupby(dates).first()
|
||||
day_first_shifted = day_first.shift(1)
|
||||
day_first_shifted.index = pd.to_datetime(day_first_shifted.index)
|
||||
day_map = day_first_shifted.reindex(pd.to_datetime(trading_days)).values
|
||||
new_vals = pd.Series(
|
||||
day_map[np.searchsorted(trading_days.values, dates.values)],
|
||||
index=col_instr.index,
|
||||
)
|
||||
shifted_parts.append(new_vals)
|
||||
return pd.concat(shifted_parts).sort_index()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Factor evaluator
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -263,6 +312,7 @@ def evaluate_factor_full(factor: FactorInfo, full_data: pd.DataFrame,
|
||||
result = pd.read_hdf(str(result_file), key="data")
|
||||
total_count = len(result)
|
||||
factor_val = result.iloc[:, 0]
|
||||
factor_val = _shift_daily_constant_factor_if_needed(factor_val, factor.factor_name)
|
||||
non_null_count = factor_val.notna().sum()
|
||||
|
||||
if non_null_count < 1000:
|
||||
|
||||
@@ -250,7 +250,7 @@ Hard requirements:
|
||||
- NO global mean/std — always use rolling(window).mean() with shift(1) to avoid look-ahead bias"""
|
||||
|
||||
else:
|
||||
system_prompt = f"""You are a quantitative trading expert specializing in EUR/USD intraday strategies.
|
||||
system_prompt = f"""You are a quantitative trading expert specializing in EUR/USD daily swing strategies.
|
||||
|
||||
CRITICAL RULES for {STYLE_DESC} (forward horizon: {FORWARD_BARS} bars = ~{FORWARD_BARS/60:.1f} hours):
|
||||
1. ONLY use the factors listed below - no others!
|
||||
@@ -258,15 +258,27 @@ CRITICAL RULES for {STYLE_DESC} (forward horizon: {FORWARD_BARS} bars = ~{FORWAR
|
||||
3. Create a pandas Series called 'signal' with values: 1 (long), -1 (short), 0 (neutral)
|
||||
4. signal.index MUST match close.index
|
||||
5. signal.name must be 'signal'
|
||||
6. IMPORTANT: factors are DAILY values broadcast to every 1-minute bar — they change once per day.
|
||||
Use daily-level logic: compare today's factor value to a rolling daily mean (window 5-20 DAYS).
|
||||
To get daily rolling mean: group by date, take first value per day, compute rolling, then reindex back.
|
||||
Example: dates = factors[col].index.get_level_values('datetime').normalize()
|
||||
daily_vals = factors[col].groupby(dates).first()
|
||||
daily_mean = daily_vals.rolling(10).mean().shift(1)
|
||||
daily_signal = (daily_vals > daily_mean).astype(int) * 2 - 1
|
||||
signal = daily_signal.reindex(dates).values (broadcast back to minute bars)
|
||||
7. The signal should change roughly once per day — this produces ~250-500 trades over 6 years.
|
||||
8. Keep conditions SIMPLE: one factor above/below its N-day rolling average. Avoid combining 3+ conditions.
|
||||
|
||||
Output ONLY valid JSON with these fields:
|
||||
{{"strategy_name": "short_name", "factor_names": ["f1", "f2"], "description": "one sentence", "code": "python code"}}"""
|
||||
|
||||
user_prompt = f"""Create a EUR/USD trading strategy using these factors:
|
||||
user_prompt = f"""Create a EUR/USD SWING trading strategy (hold ~{FORWARD_BARS/60:.0f} hours) using these factors:
|
||||
|
||||
{factor_list}
|
||||
|
||||
{f'Previous feedback: {feedback}' if feedback else 'First attempt - be creative!'}"""
|
||||
{f'Previous feedback: {feedback}' if feedback else 'First attempt - be creative!'}
|
||||
|
||||
Use daily-level signal logic (factor above/below rolling daily mean). Signal changes once per day."""
|
||||
|
||||
api = APIBackend()
|
||||
response = api.build_messages_and_create_chat_completion(
|
||||
@@ -371,6 +383,8 @@ signal.fillna(0).to_pickle('signal.pkl')
|
||||
txn_cost_bps=TXN_COST_BPS,
|
||||
forward_returns=fwd_returns,
|
||||
oos_start=OOS_START_DEFAULT,
|
||||
wf_rolling=False, # too slow on 2M bars — run via rebacktest script instead
|
||||
mc_n_permutations=50,
|
||||
)
|
||||
|
||||
# ============================================================================
|
||||
@@ -567,9 +581,18 @@ def main(target_count=10):
|
||||
progress.update(task, advance=1)
|
||||
continue
|
||||
|
||||
# Check acceptance criteria — OOS must be profitable (primary filter)
|
||||
if (abs(ic) > MIN_IC and sharpe > MIN_SHARPE and trades > MIN_TRADES and dd > MAX_DRAWDOWN
|
||||
and oos_sharpe > 0.0 and oos_monthly > 0.0):
|
||||
# Monte Carlo p-value (edge significance)
|
||||
mc_pvalue = bt_result.get('mc_pvalue')
|
||||
|
||||
# Rolling walk-forward metrics
|
||||
wf_consistency = bt_result.get('wf_oos_consistency')
|
||||
wf_sharpe_mean = bt_result.get('wf_oos_sharpe_mean')
|
||||
|
||||
# Check acceptance criteria — OOS must be profitable + statistically significant
|
||||
mc_ok = mc_pvalue is None or mc_pvalue < 0.20 # lenient: top 20% non-random
|
||||
wf_ok = wf_consistency is None or wf_consistency >= 0.5 # ≥50% of WF windows profitable
|
||||
if (abs(ic or 0) > MIN_IC and sharpe > MIN_SHARPE and trades > MIN_TRADES and dd > MAX_DRAWDOWN
|
||||
and oos_sharpe > 0.0 and oos_monthly > 0.0 and mc_ok and wf_ok):
|
||||
# ACCEPT
|
||||
strategy['real_backtest'] = bt_result
|
||||
strategy['metrics'] = bt_result
|
||||
@@ -583,7 +606,7 @@ def main(target_count=10):
|
||||
'ohlcv_only': OHLCV_ONLY,
|
||||
'engine': 'ftmo_v2',
|
||||
'txn_cost_bps': TXN_COST_BPS,
|
||||
# Walk-forward OOS metrics
|
||||
# Walk-forward OOS split
|
||||
'oos_sharpe': bt_result.get('oos_sharpe'),
|
||||
'oos_monthly_return_pct': bt_result.get('oos_monthly_return_pct'),
|
||||
'oos_max_drawdown': bt_result.get('oos_max_drawdown'),
|
||||
@@ -592,6 +615,15 @@ def main(target_count=10):
|
||||
'is_sharpe': bt_result.get('is_sharpe'),
|
||||
'is_monthly_return_pct': bt_result.get('is_monthly_return_pct'),
|
||||
'oos_start': bt_result.get('oos_start'),
|
||||
# Rolling walk-forward
|
||||
'wf_n_windows': bt_result.get('wf_n_windows'),
|
||||
'wf_oos_sharpe_mean': wf_sharpe_mean,
|
||||
'wf_oos_sharpe_std': bt_result.get('wf_oos_sharpe_std'),
|
||||
'wf_oos_monthly_return_mean': bt_result.get('wf_oos_monthly_return_mean'),
|
||||
'wf_oos_consistency': wf_consistency,
|
||||
# Monte Carlo significance
|
||||
'mc_pvalue': mc_pvalue,
|
||||
'mc_n_permutations': bt_result.get('mc_n_permutations'),
|
||||
}
|
||||
|
||||
fname = f"{int(time.time())}_{strategy['strategy_name']}.json"
|
||||
@@ -614,12 +646,17 @@ def main(target_count=10):
|
||||
f"IC={ic:.4f}, Sharpe={sharpe:.3f}, Trades={trades}, DD={dd:.1%}")
|
||||
else:
|
||||
oos_info = f"OOS_Sharpe={oos_sharpe:+.2f} OOS_Mon={oos_monthly:+.2f}%" if oos_sharpe is not None else ""
|
||||
_log.info(f"REJECTED IC={ic:.4f} Sharpe={sharpe:.2f} Trades={trades} DD={dd:.1%} {oos_info}")
|
||||
mc_info = f" MC_p={mc_pvalue:.2f}" if mc_pvalue is not None else ""
|
||||
wf_info = f" WF_consistency={wf_consistency:.0%}" if wf_consistency is not None else ""
|
||||
_ic = ic or 0; _sh = sharpe or 0; _dd = dd or 0
|
||||
_log.info(f"REJECTED IC={_ic:.4f} Sharpe={_sh:.2f} Trades={trades} DD={_dd:.1%} {oos_info}{mc_info}{wf_info}")
|
||||
feedback_history.append(
|
||||
f"Failed: IC={ic:.4f}, Sharpe={sharpe:.2f}, Trades={trades}, DD={dd:.1%}, "
|
||||
f"OOS_Sharpe={oos_sharpe:+.2f}, OOS_Monthly={oos_monthly:+.2f}%. "
|
||||
f"Need |IC|>{MIN_IC}, Sharpe>{MIN_SHARPE}, Trades>{MIN_TRADES}, "
|
||||
f"OOS_Sharpe>0 AND OOS_Monthly>0 — strategy must generalise to unseen data (2024+)."
|
||||
f"Failed: IC={_ic:.4f}, Sharpe={_sh:.2f}, Trades={trades}, DD={_dd:.1%}, "
|
||||
f"OOS_Sharpe={oos_sharpe:+.2f}, OOS_Monthly={oos_monthly:+.2f}%"
|
||||
+ (f", MC_p={mc_pvalue:.2f}" if mc_pvalue is not None else "")
|
||||
+ (f", WF_consistency={wf_consistency:.0%}" if wf_consistency is not None else "")
|
||||
+ f". Need |IC|>{MIN_IC}, Sharpe>{MIN_SHARPE}, Trades>{MIN_TRADES}, "
|
||||
f"OOS_Sharpe>0, OOS_Monthly>0, MC_p<0.20, WF_consistency≥50%."
|
||||
)
|
||||
|
||||
progress.update(task, advance=1)
|
||||
|
||||
@@ -188,6 +188,8 @@ def rebacktest_one(
|
||||
close=close_a,
|
||||
signal=signal,
|
||||
txn_cost_bps=txn_cost_bps,
|
||||
wf_rolling=True,
|
||||
mc_n_permutations=200,
|
||||
)
|
||||
result["status_detail"] = result.pop("status")
|
||||
result["status"] = "ok"
|
||||
@@ -264,6 +266,15 @@ def main() -> None:
|
||||
"oos_win_rate": bt.get("oos_win_rate"),
|
||||
"oos_n_trades": bt.get("oos_n_trades"),
|
||||
"oos_start": bt.get("oos_start"),
|
||||
# Rolling walk-forward
|
||||
"wf_n_windows": bt.get("wf_n_windows"),
|
||||
"wf_oos_sharpe_mean": bt.get("wf_oos_sharpe_mean"),
|
||||
"wf_oos_sharpe_std": bt.get("wf_oos_sharpe_std"),
|
||||
"wf_oos_monthly_return_mean": bt.get("wf_oos_monthly_return_mean"),
|
||||
"wf_oos_consistency": bt.get("wf_oos_consistency"),
|
||||
# Monte Carlo significance
|
||||
"mc_pvalue": bt.get("mc_pvalue"),
|
||||
"mc_n_permutations": bt.get("mc_n_permutations"),
|
||||
}
|
||||
data["sharpe_ratio"] = bt.get("sharpe")
|
||||
data["max_drawdown"] = bt.get("max_drawdown")
|
||||
@@ -299,6 +310,12 @@ def main() -> None:
|
||||
"oos_monthly_pct": bt.get("oos_monthly_return_pct"),
|
||||
"oos_dd": bt.get("oos_max_drawdown"),
|
||||
"oos_trades": bt.get("oos_n_trades"),
|
||||
# Rolling walk-forward
|
||||
"wf_n_windows": bt.get("wf_n_windows"),
|
||||
"wf_oos_sharpe_mean": bt.get("wf_oos_sharpe_mean"),
|
||||
"wf_oos_consistency": bt.get("wf_oos_consistency"),
|
||||
# Monte Carlo
|
||||
"mc_pvalue": bt.get("mc_pvalue"),
|
||||
}
|
||||
if "annualized_return" in bt:
|
||||
row["new_annual_return_cagr"] = bt["annualized_return"]
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
"""
|
||||
Tests for backtest_signal_ftmo and walk-forward OOS validation.
|
||||
|
||||
Covers:
|
||||
- FTMO daily/total loss limits
|
||||
- Risk-based leverage calculation
|
||||
- OOS split returns independent IS and OOS metrics
|
||||
- OOS uses fresh FTMO simulation (not contaminated by IS losses)
|
||||
- Monte Carlo permutation test helper
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from rdagent.components.backtesting.vbt_backtest import (
|
||||
OOS_START_DEFAULT,
|
||||
backtest_signal_ftmo,
|
||||
FTMO_MAX_DAILY_LOSS,
|
||||
FTMO_MAX_TOTAL_LOSS,
|
||||
monte_carlo_trade_pvalue,
|
||||
walk_forward_rolling,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.fixture
|
||||
def close_2yr() -> pd.Series:
|
||||
"""~3 months of synthetic 1-min EUR/USD (enough bars for all leverage/FTMO tests)."""
|
||||
np.random.seed(42)
|
||||
n = 90 * 1440 # 90 days × 1440 min
|
||||
idx = pd.date_range("2022-01-01", periods=n, freq="1min")
|
||||
price = 1.10 + np.cumsum(np.random.randn(n) * 0.00005)
|
||||
return pd.Series(price, index=idx)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def close_6yr() -> pd.Series:
|
||||
"""Synthetic data crossing the 2024-01-01 IS/OOS boundary.
|
||||
|
||||
120 days starting 2023-09-01 → ends ~2024-01-01, giving ~30 days of OOS data.
|
||||
Small enough to keep tests fast.
|
||||
"""
|
||||
np.random.seed(7)
|
||||
n = 150 * 1440 # 2023-09-01 + 150d ≈ 2024-01-28 → ~28 days of OOS data
|
||||
idx = pd.date_range("2023-09-01", periods=n, freq="1min")
|
||||
price = 1.10 + np.cumsum(np.random.randn(n) * 0.00005)
|
||||
return pd.Series(price, index=idx)
|
||||
|
||||
|
||||
def _random_signal(index: pd.Index, seed: int = 0) -> pd.Series:
|
||||
np.random.seed(seed)
|
||||
return pd.Series(np.random.choice([-1.0, 0.0, 1.0], size=len(index)), index=index)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# FTMO leverage tests
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_ftmo_result_contains_leverage_fields(close_2yr):
|
||||
signal = _random_signal(close_2yr.index)
|
||||
r = backtest_signal_ftmo(close_2yr, signal, oos_start=None)
|
||||
assert "ftmo_leverage" in r
|
||||
assert "ftmo_risk_pct" in r
|
||||
assert "ftmo_stop_pips" in r
|
||||
assert r["ftmo_leverage"] > 0
|
||||
|
||||
|
||||
def test_ftmo_leverage_capped_at_max(close_2yr):
|
||||
signal = _random_signal(close_2yr.index)
|
||||
# With very tight stop (1 pip) risk_pct=0.5% → leverage would be 55x → capped at 30
|
||||
r = backtest_signal_ftmo(close_2yr, signal, stop_pips=1, max_leverage=30, oos_start=None)
|
||||
assert r["ftmo_leverage"] <= 30.0
|
||||
|
||||
|
||||
def test_ftmo_zero_signal_produces_no_trades(close_2yr):
|
||||
signal = pd.Series(0.0, index=close_2yr.index)
|
||||
r = backtest_signal_ftmo(close_2yr, signal, oos_start=None)
|
||||
assert r["n_trades"] == 0
|
||||
assert r["total_return"] == 0.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OOS split tests
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_oos_split_produces_is_and_oos_keys(close_6yr):
|
||||
signal = _random_signal(close_6yr.index)
|
||||
r = backtest_signal_ftmo(close_6yr, signal, oos_start="2024-01-01")
|
||||
|
||||
assert "is_sharpe" in r
|
||||
assert "oos_sharpe" in r
|
||||
assert "is_monthly_return_pct" in r
|
||||
assert "oos_monthly_return_pct" in r
|
||||
assert "is_n_bars" in r
|
||||
assert "oos_n_bars" in r
|
||||
assert r["oos_start"] == "2024-01-01"
|
||||
|
||||
|
||||
def test_oos_split_bars_sum_to_total(close_6yr):
|
||||
signal = _random_signal(close_6yr.index)
|
||||
r = backtest_signal_ftmo(close_6yr, signal, oos_start="2024-01-01")
|
||||
assert r["is_n_bars"] + r["oos_n_bars"] == len(close_6yr)
|
||||
|
||||
|
||||
def test_oos_none_disables_split(close_6yr):
|
||||
signal = _random_signal(close_6yr.index)
|
||||
r = backtest_signal_ftmo(close_6yr, signal, oos_start=None)
|
||||
assert "is_sharpe" not in r
|
||||
assert "oos_sharpe" not in r
|
||||
|
||||
|
||||
def test_oos_is_independent_of_is_losses(close_6yr):
|
||||
"""OOS must use a fresh FTMO simulation — IS blowup must not zero OOS trades."""
|
||||
# Force the IS period to blow up immediately with max short on rising market
|
||||
rising = pd.Series(
|
||||
np.linspace(1.0, 2.0, len(close_6yr)),
|
||||
index=close_6yr.index,
|
||||
)
|
||||
always_short = pd.Series(-1.0, index=close_6yr.index)
|
||||
|
||||
r = backtest_signal_ftmo(rising, always_short, oos_start="2024-01-01")
|
||||
|
||||
# IS should be wiped out (total loss limit hit), but OOS must still trade
|
||||
assert r.get("oos_n_trades", 0) is not None
|
||||
assert r.get("oos_n_bars", 0) > 0
|
||||
|
||||
|
||||
def test_oos_default_start_matches_constant(close_6yr):
|
||||
signal = _random_signal(close_6yr.index)
|
||||
r = backtest_signal_ftmo(close_6yr, signal)
|
||||
assert r.get("oos_start") == OOS_START_DEFAULT
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Monte Carlo permutation test helper
|
||||
# ---------------------------------------------------------------------------
|
||||
def _monte_carlo_pvalue(close: pd.Series, signal: pd.Series, n_permutations: int = 200, seed: int = 0) -> float:
|
||||
"""
|
||||
Estimate p-value: fraction of random permutations that beat the real Sharpe.
|
||||
p < 0.05 → strategy has statistically significant edge.
|
||||
"""
|
||||
real_r = backtest_signal_ftmo(close, signal, oos_start=None)
|
||||
real_sharpe = real_r.get("sharpe", 0.0) or 0.0
|
||||
|
||||
rng = np.random.default_rng(seed)
|
||||
beat = 0
|
||||
signal_vals = signal.values.copy()
|
||||
for _ in range(n_permutations):
|
||||
perm = rng.permutation(signal_vals)
|
||||
perm_signal = pd.Series(perm, index=signal.index)
|
||||
perm_r = backtest_signal_ftmo(close, perm_signal, oos_start=None)
|
||||
if (perm_r.get("sharpe") or 0.0) >= real_sharpe:
|
||||
beat += 1
|
||||
return beat / n_permutations
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_random_signal_has_no_edge(close_2yr):
|
||||
"""A purely random signal should NOT beat most permutations."""
|
||||
signal = _random_signal(close_2yr.index, seed=42)
|
||||
pval = _monte_carlo_pvalue(close_2yr, signal, n_permutations=50)
|
||||
# Random vs random: p-value should be near 0.5 (not significant)
|
||||
assert pval > 0.10, f"Random signal unexpectedly significant: p={pval:.2f}"
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_perfect_signal_is_significant(close_2yr):
|
||||
"""An oracle signal on hourly bars should beat random permutations significantly.
|
||||
|
||||
Per-minute oracle trading is unprofitable due to FTMO transaction costs, so we
|
||||
use 60-bar held positions (≈1h) where each directional move is large enough to
|
||||
cover the spread.
|
||||
"""
|
||||
bar_ret = close_2yr.pct_change().fillna(0)
|
||||
# Hourly oracle: sign of 60-bar future return, broadcast to all 60 minute bars
|
||||
hourly_ret = bar_ret.rolling(60).sum().shift(-60).fillna(0)
|
||||
perfect = pd.Series(np.sign(hourly_ret), index=close_2yr.index)
|
||||
pval = _monte_carlo_pvalue(close_2yr, perfect, n_permutations=50)
|
||||
assert pval < 0.30, f"Hourly oracle signal should beat random permutations: p={pval:.2f}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# FTMO metrics in result dict
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_ftmo_result_has_equity_and_profit(close_2yr):
|
||||
signal = _random_signal(close_2yr.index)
|
||||
r = backtest_signal_ftmo(close_2yr, signal, oos_start=None)
|
||||
assert "ftmo_end_equity" in r
|
||||
assert "ftmo_monthly_profit" in r
|
||||
assert r["ftmo_end_equity"] > 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Monte Carlo trade permutation tests
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_mc_pvalue_in_result(close_2yr):
|
||||
signal = _random_signal(close_2yr.index)
|
||||
r = backtest_signal_ftmo(close_2yr, signal, oos_start=None, mc_n_permutations=50)
|
||||
assert "mc_pvalue" in r
|
||||
assert 0.0 <= r["mc_pvalue"] <= 1.0
|
||||
assert r["mc_n_permutations"] == 50
|
||||
|
||||
|
||||
def test_mc_pvalue_disabled_by_default(close_2yr):
|
||||
signal = _random_signal(close_2yr.index)
|
||||
r = backtest_signal_ftmo(close_2yr, signal, oos_start=None)
|
||||
assert "mc_pvalue" not in r
|
||||
|
||||
|
||||
def test_mc_zero_trades_returns_one(close_2yr):
|
||||
"""Zero-signal → no trades → p-value must be 1.0 (no edge)."""
|
||||
trade_pnl = pd.Series([], dtype=float)
|
||||
assert monte_carlo_trade_pvalue(trade_pnl, n_permutations=10) == 1.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Rolling walk-forward tests
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_wf_rolling_keys_in_result(close_6yr):
|
||||
signal = _random_signal(close_6yr.index)
|
||||
r = backtest_signal_ftmo(close_6yr, signal, oos_start="2024-01-01", wf_rolling=True)
|
||||
# With only ~150 days of data, windows may be 0 — just check key presence
|
||||
assert "wf_n_windows" in r
|
||||
|
||||
|
||||
def test_wf_rolling_disabled_by_default(close_6yr):
|
||||
signal = _random_signal(close_6yr.index)
|
||||
r = backtest_signal_ftmo(close_6yr, signal, oos_start="2024-01-01")
|
||||
assert "wf_n_windows" not in r
|
||||
|
||||
|
||||
def test_wf_consistency_range(close_6yr):
|
||||
"""wf_oos_consistency must be in [0, 1] when windows exist."""
|
||||
signal = _random_signal(close_6yr.index)
|
||||
r = backtest_signal_ftmo(close_6yr, signal, oos_start="2024-01-01", wf_rolling=True)
|
||||
c = r.get("wf_oos_consistency")
|
||||
if c is not None:
|
||||
assert 0.0 <= c <= 1.0
|
||||
Reference in New Issue
Block a user