### Full Usage Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/StressTest.md A complete example demonstrating the setup and execution of a backtest, including fetching data, calculating indicators, simulating trades, and preparing P&L results for StressTest. ```python from backtest_engine import ( simulate_trades, fetch_aggvault, atr, StressTest, MonteCarloDD, LONG ) import numpy as np # シミュレーション実行 ts, o, h, l, c, _ = fetch_aggvault("EURUSD", "1h", "2024-01-01", "2025-01-01") atr_vals = atr(h, l, c, 14) signal_bars = np.array([100, 250, 400], dtype=np.int32) sl_distances = atr_vals[signal_bars] * 1.5 tp_distances = atr_vals[signal_bars] * 3.0 results = simulate_trades( h, l, c, signal_bars, np.ones(3, dtype=np.int8), # LONG sl_distances, tp_distances, max_hold=100, ) ``` -------------------------------- ### Usage Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/simulate_trades_hires.md An example demonstrating how to use simulate_trades_hires with 1-hour signals and 1-minute execution bars. ```python from backtest_engine import fetch_aggvault, simulate_trades_hires, rsi, atr # シグナル生成は1時間足 ts_1h, o_1h, h_1h, l_1h, c_1h, _ = fetch_aggvault( "EURUSD", "1h", "2024-01-01", "2025-01-01" ) rsi_vals = rsi(c_1h, 14) atr_vals = atr(h_1h, l_1h, c_1h, 14) # シグナル定義 signal_bars = np.where(rsi_vals < 30)[0] # RSI < 30のバーをロング directions = np.array([1] * len(signal_bars), dtype=np.int8) # LONG sl_distances = atr_vals[signal_bars] * 1.5 tp_distances = atr_vals[signal_bars] * 3.0 # 約定シミュレーションは1分足 ts_1m, o_1m, h_1m, l_1m, c_1m, _ = fetch_aggvault( "EURUSD", "1m", "2024-01-01", "2025-01-01" ) # コスト計算 from backtest_engine import BrokerCost cost = BrokerCost.tradeview_ilc() instruments = ["EURUSD"] * len(signal_bars) entry_costs = cost.per_trade_cost(instruments, sl_distances) # 高解像度シミュレーション results = simulate_trades_hires( signal_timestamps=ts_1h, signal_bars=signal_bars, directions=directions, sl_distances=sl_distances, tp_distances=tp_distances, max_hold=48, # 1時間足で48本 = 2日 signal_bar_minutes=60, # シグナルは1時間足 exec_timestamps=ts_1m, exec_opens=o_1m, exec_highs=h_1m, exec_lows=l_1m, exec_closes=c_1m, exec_bar_minutes=1, # 約定は1分足 entry_costs=entry_costs, ) print(f"PF (hires): {results.profit_factor:.2f}") print(f"Win rate: {results.win_rate:.1%}") ``` -------------------------------- ### Combined WFA and CSCV Usage Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/WalkForward_CSCV.md Example showing how to integrate WalkForward and CSCV results, passing them to GateKeeper for validation. ```python from backtest_engine import WalkForward, CSCV, GateKeeper # WFA 実行 wf = WalkForward(n_bars=len(close), is_ratio=0.7, n_splits=5, anchored=False) wfa_result = wf.run(param_grid, evaluate_fn) # CSCV 実行 cscv = CSCV(n_splits=10) cscv_result = cscv.run(param_grid, evaluate_fn, n_bars=len(close)) # GateKeeper の Gate 3 に渡す gk = GateKeeper( strategy_name="RSI Reversal v3", n_bars=len(close), ) gate3_result = gk.gate3_validate(wfa_result, cscv_result) print(f"Gate 3: {'PASS' if gate3_result.passed else 'FAIL'}") ``` -------------------------------- ### WalkForward run method example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/WalkForward_CSCV.md Example demonstrating how to use the WalkForward class to perform walk-forward analysis, including data fetching, parameter grid definition, evaluation function, and execution. ```python from backtest_engine import WalkForward, fetch_aggvault, rsi, simulate_trades, atr, LONG import numpy as np # データ取得 ts, o, h, l, c, _ = fetch_aggvault("EURUSD", "1h", "2024-01-01", "2025-01-01") atr_vals = atr(h, l, c, 14) rsi_vals = rsi(c, 14) # パラメータグリッド param_grid = [ {"rsi_lower": 25, "rsi_upper": 35}, {"rsi_lower": 30, "rsi_upper": 40}, {"rsi_lower": 20, "rsi_upper": 40}, ] # 評価関数 def evaluate_fn(params, start_bar, end_bar): """指定バー範囲で戦略を評価。利益率(メトリクス)を返す。""" lo = params["rsi_lower"] hi = params["rsi_upper"] signal_mask = ((rsi_vals[start_bar:end_bar] < lo) | (rsi_vals[start_bar:end_bar] > hi)) signal_indices = np.where(signal_mask)[0] + start_bar if len(signal_indices) == 0: return 0.0 results = simulate_trades( h[start_bar:end_bar+1], l[start_bar:end_bar+1], c[start_bar:end_bar+1], signal_indices.astype(np.int32) - start_bar, np.ones(len(signal_indices), dtype=np.int8), # LONG atr_vals[signal_indices] * 1.5, atr_vals[signal_indices] * 3.0, max_hold=100, ) return results.profit_factor # 高いほど良い # WFA 実行 wf = WalkForward(n_bars=len(c), is_ratio=0.7, n_splits=5, anchored=False) wfa_result = wf.run(param_grid, evaluate_fn) print(f"OOS 平均: {wfa_result['oos_mean']:.3f}R") print(f"OOS std: {wfa_result['oos_std']:.3f}R") print(f"IS/OOS 比: {wfa_result['is_oos_ratio']:.2f}") print(f"OOS 勝率: {wfa_result['oos_positive_frac']:.1%}") ``` -------------------------------- ### CSCV run method example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/WalkForward_CSCV.md Example demonstrating how to use the CSCV class to estimate the probability of backtest overfitting (PBO), including parameter grid, evaluation function, and execution. ```python from backtest_engine import CSCV # パラメータグリッド(複数パラメータセット) param_grid = [ {"period": 7}, {"period": 14}, {"period": 21}, ] # 同じ evaluate_fn を使用 cscv = CSCV(n_splits=10) cscv_result = cscv.run(param_grid, evaluate_fn, n_bars=len(close)) pbo = cscv_result["pbo"] print(f"PBO(過学習確率): {pbo:.1%}") if pbo < 0.5: print("✓ 過学習の可能性は低い") else: print("⚠ 過学習の可能性が高い") ``` -------------------------------- ### Run All Method Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/StressTest.md Demonstrates how to execute all stress tests (baseline, block bootstrap, and degraded scenarios) and retrieve a comprehensive report. ```python st = StressTest(results["pnl_r"], n_sims=10_000, risk_pct=0.01) report = st.run_all(block_size=10) # 基準 MC print(f"基準 DD 95%: {report['baseline']['dd_95']:.1%}") # ブロック・ブートストラップ print(f"ブロック DD 95%: {report['block_bootstrap']['dd_95']:.1%}") # 劣化シナリオ for scenario_name, metrics in report['degraded'].items(): print(f"{scenario_name}: DD 95% = {metrics['dd_95']:.1%}") ``` -------------------------------- ### gate2_screen() Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/GateKeeper.md Example of using the gate2_screen method for a coarse-grained screening of approximately 100 parameters. ```python # スクリーニング(~100パラメータ) screen_params = [ # ... 100 combos ] result = gk.gate2_screen(run_func, screen_params) if result.passed: print(f"✓ Gate 2 PASS: Best PF = {result.best_metric['pf']:.2f}, RF = {result.best_metric.get('rf', 0):.2f}") else: print(f"✗ Gate 2 FAIL: {result.message}") ``` -------------------------------- ### gate1_quick() Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/GateKeeper.md Example of using the gate1_quick method for a quick screening of approximately 20 parameters across the entire dataset. ```python # 軽速度テスト(~20パラメータ、全データ) def run_func(params): """パラメータ dict → {'pf': ..., 'total_r': ..., 'n_trades': ..., 'max_dd_r': ...} or None""" # シミュレーション実装 # results = simulate_trades(...) # return { # 'pf': results.profit_factor, # 'total_r': np.sum(results['pnl_r']), # 'n_trades': len(results), # 'max_dd_r': results.max_drawdown_r, # } quick_params = [ {"rsi_period": 7}, {"rsi_period": 10}, {"rsi_period": 14}, # ... 20 combos ] result = gk.gate1_quick(run_func, quick_params) if result.passed: print(f"✓ Gate 1 PASS: Best PF = {result.best_metric['pf']:.2f}") else: print(f"✗ Gate 1 FAIL: {result.message}") ``` -------------------------------- ### Full Usage Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/MonteCarloDD.md Demonstrates a complete workflow from fetching data and simulating trades to performing Monte Carlo analysis and checking prop firm conditions. ```python from backtest_engine import ( simulate_trades, fetch_aggvault, atr, MonteCarloDD, LONG ) import numpy as np # Data and signal simulation ts, o, h, l, c, _ = fetch_aggvault("EURUSD", "1h", "2024-01-01", "2025-01-01") atr_vals = atr(h, l, c, 14) signal_bars = np.where(atr_vals > 0.0010)[0] directions = np.ones(len(signal_bars), dtype=np.int8) # LONG sl_distances = atr_vals[signal_bars] * 1.5 tp_distances = atr_vals[signal_bars] * 3.0 results = simulate_trades( h, l, c, signal_bars.astype(np.int32), directions, sl_distances, tp_distances, max_hold=100, ) # MC execution with 1% risk setting mc = MonteCarloDD(results["pnl_r"], n_sims=10_000, risk_pct=0.01, seed=42) # Drawdown distribution print(f"DD 50%: {mc.dd_percentile(50):.1%}") print(f"DD 95%: {mc.dd_percentile(95):.1%}") print(f"DD 99%: {mc.dd_percentile(99):.1%}") # Kelly criterion kelly = mc.kelly_fraction() print(f"Kelly criterion: {kelly * 100:.1f}%") print(f"Recommended risk (25% Kelly): {kelly * 0.25 * 100:.1f}%") # Prop firm check (Fundora) check = mc.prop_firm_check(max_dd_limit=0.04, total_dd_limit=0.08, confidence=95.0) print(f"\nProp firm verification:") print(f" Max DD OK: {check['max_dd_ok']} (limit 4%)") print(f" Total DD OK: {check['total_dd_ok']} (limit 8%)") print(f" Overall: {'PASS' if check['pass'] else 'FAIL'}") # Optimal risk search optimal = mc.optimal_risk_pct(max_dd=0.20, target_pct=95.0) print(f"\nOptimal risk (DD95% ≤ 20%): {optimal * 100:.2f}%") ``` -------------------------------- ### Example Usage: Constants and Types Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/types.md A comprehensive example demonstrating the usage of defined constants and types for defining trades and analyzing simulation results. ```python from backtest_engine import ( LONG, SHORT, EXIT_SL, EXIT_TP, EXIT_TIME, EXIT_BE, EXIT_CUSTOM, EXIT_TRAIL, EXIT_NO_FILL, TRADE_RESULT_DTYPE, simulate_trades, ) import numpy as np # トレード定義 signal_bars = np.array([100, 250, 400], dtype=np.int32) directions = np.array([LONG, SHORT, LONG], dtype=np.int8) # シミュレーション results = simulate_trades( high, low, close, signal_bars, directions, sl_distances, tp_distances, max_hold=100, ) # 結果分析 print(f"トレード数: {len(results)}") print(f"形式: {results.dtype}") # 出場理由別集計 exit_counts = {} for exit_type in [EXIT_SL, EXIT_TP, EXIT_TIME, EXIT_BE, EXIT_CUSTOM, EXIT_TRAIL, EXIT_NO_FILL]: count = np.sum(results["exit_type"] == exit_type) if count > 0: exit_counts[exit_type] = count print("出場理由別:") for exit_type, count in exit_counts.items(): names = { 0: "SL", 1: "TP", 2: "TIME", 3: "BE", 4: "CUSTOM", 5: "TRAIL", 6: "NO_FILL" } print(f" {names[exit_type]}: {count}") # MFE/MAE 分析 print(f"平均 MFE: {np.mean(results['mfe_r']):.3f}R") print(f"平均 MAE: {np.mean(results['mae_r']):.3f}R") # ホールド期間の統計 print(f"平均保有: {np.mean(results['hold_bars']):.0f} バー") print(f"最長保有: {np.max(results['hold_bars'])} バー") ``` -------------------------------- ### Block Bootstrap Method Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/StressTest.md Demonstrates how to use the block_bootstrap method to perform Monte Carlo simulations with block resampling, preserving auto-correlation of losses. ```python st = StressTest(results["pnl_r"], n_sims=1000, risk_pct=0.01, seed=42) bb = st.block_bootstrap(block_size=10) print(f"DD 95%: {bb['dd_95']:.1%}") print(f"DD 99%: {bb['dd_99']:.1%}") ``` -------------------------------- ### run() Method Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/MonteCarloDD.md Executes the Monte Carlo simulation and returns an array of maximum drawdowns for each simulation. ```python mc = MonteCarloDD(results["pnl_r"], n_sims=10_000, risk_pct=0.01, seed=42) max_dds = mc.run() # max_dds: float64 array, length=10_000, each element is a DD value in [0, 1] ``` -------------------------------- ### Degrade Method Examples Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/StressTest.md Shows examples of using the degrade method to simulate various adverse scenarios by modifying win rate, profit factor, or adding costs. ```python # シナリオ1: 勝率 -5% pnl_degraded_wr = st.degrade(win_rate_delta=-0.05) # シナリオ2: 利益が20%小さくなる pnl_degraded_rr = st.degrade(rr_scale=0.80) # シナリオ3: 追加コスト +0.1R pnl_degraded_cost = st.degrade(cost_add_r=0.10) # 複合シナリオ pnl_degraded_all = st.degrade( win_rate_delta=-0.03, rr_scale=0.90, cost_add_r=0.05, ) # 劣化後のP&Lで MC 実行 mc = MonteCarloDD(pnl_degraded_all, n_sims=10_000, risk_pct=0.01) mc.run() print(f"劣化シナリオ DD 95%: {mc.dd_percentile(95):.1%}") ``` -------------------------------- ### optimal_risk_pct() Method Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/MonteCarloDD.md Finds the optimal risk percentage using binary search such that the drawdown at a target percentile does not exceed a maximum limit. ```python optimal_risk = mc.optimal_risk_pct(max_dd=0.20, target_pct=95.0) print(f"Recommended risk: {optimal_risk * 100:.2f}%") ``` -------------------------------- ### kelly_fraction() Method Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/MonteCarloDD.md Calculates the Kelly criterion, which represents the optimal bet size to maximize compound growth. ```python kelly = mc.kelly_fraction() print(f"Kelly criterion: {kelly:.3f} → {kelly * 100:.1f}%") ``` -------------------------------- ### Field Access Example for TradeResults Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/types.md Demonstrates how to access fields within the `TradeResults` structure. ```python results = simulate_trades(...) pnl = results["pnl_r"] # 全トレードのP&L winners = results[results["pnl_r"] > 0] exits = results["exit_type"] # 特定の出場理由でフィルタ from backtest_engine import EXIT_SL, EXIT_TP sl_exits = results[results["exit_type"] == EXIT_SL] tp_exits = results[results["exit_type"] == EXIT_TP] ``` -------------------------------- ### gate0_validate() Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/GateKeeper.md Example of how to use the gate0_validate method for data validation and BugGuard checks. ```python from backtest_engine import GateKeeper, BrokerCost cost = BrokerCost.tradeview_ilc() gk = GateKeeper( strategy_name="RSI Reversal v3", n_bars=7022, bar_minutes=60, resolution_minutes=1, spreads_used={"EURUSD": 0.00008}, source_path="strategy.py", expected_costs=cost.cost_prices(), ) try: result = gk.gate0_validate() print(f"✓ Gate 0 PASS: {result.message}") except RuntimeError as e: print(f"✗ Gate 0 FAIL: {e}") ``` -------------------------------- ### fetch_aggvault() 使用例 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md 環境変数から AggVault API キーを自動取得するか、直接指定して fetch_aggvault() を使用する例。 ```python from backtest_engine import fetch_aggvault # 環境変数から自動取得 ts, o, h, l, c, v = fetch_aggvault("EURUSD", "1h", "2024-01-01", "2025-01-01") # または直接指定(環境変数よりも優先) ts, o, h, l, c, v = fetch_aggvault( "EURUSD", "1h", "2024-01-01", "2025-01-01", api_key="tk_your_key_here" ) ``` -------------------------------- ### gate3_validate() Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/GateKeeper.md Example of using the gate3_validate method for overfitting detection using Walk-Forward Analysis (WFA) and Cross-Sectional Cross-Validation (CSCV). ```python from backtest_engine import WalkForward, CSCV # WFA 実行 wf = WalkForward(n_bars=len(close), is_ratio=0.7, n_splits=5) wfa_result = wf.run(param_grid, evaluate_fn) # CSCV 実行(オプション) cscv = CSCV(n_splits=10) cscv_result = cscv.run(param_grid, evaluate_fn, n_bars=len(close)) # Gate 3 result = gk.gate3_validate(wfa_result, cscv_result) if result.passed: print(f"✓ Gate 3 PASS: OOS win rate = {result.best_metric['oos_positive_frac']:.1%}, PBO = {result.best_metric.get('pbo', 1):.1%}") else: print(f"✗ Gate 3 FAIL: {result.message}") ``` -------------------------------- ### AGGVAULT_KEY 設定方法 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md 環境変数 AGGVAULT_KEY を設定するコマンドラインとPythonスクリプトの例。 ```bash # Unix/Linux/macOS export AGGVAULT_KEY=tk_your_key_here # Windows (PowerShell) $env:AGGVAULT_KEY="tk_your_key_here" # Windows (CMD) set AGGVAULT_KEY=tk_your_key_here # Python スクリプト内 import os os.environ["AGGVAULT_KEY"] = "tk_your_key_here" ``` -------------------------------- ### BrokerCost カスタム設定例 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md カスタムスプレッド、コミッション、ピップサイズ、ピップ値を持つ BrokerCost オブジェクトの作成例。 ```python cost_custom = BrokerCost( spreads={ "EURUSD": 0.00008, "GBPUSD": 0.0001, "CUSTOM": 0.00006, }, commission_per_lot=4.0, # $4 RT pip_sizes={ "EURUSD": 0.0001, "GBPUSD": 0.0001, "CUSTOM": 0.0001, }, pip_values={ "EURUSD": 10.0, "GBPUSD": 10.0, "CUSTOM": 10.0, }, ) ``` -------------------------------- ### API キー設定例 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/data_utilities.md 環境変数または関数引数を使用して AggVault API キーを設定する方法。 ```bash export AGGVAULT_KEY=tk_your_key_here ``` ```python fetch_aggvault("EURUSD", "1h", "2024-01-01", "2025-01-01", api_key="tk_...") ``` -------------------------------- ### ruin_probability() Method Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/MonteCarloDD.md Calculates the probability of exceeding a specified drawdown threshold. ```python prob = mc.ruin_probability(0.20) # Probability of DD exceeding 20% print(f"Ruin risk: {prob:.1%}") ``` -------------------------------- ### Simulation with Broker Costs (NET) Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/simulate_trades.md Shows how to include broker costs in the simulation by configuring BrokerCost and applying entry costs to the simulate_trades function. ```python from backtest_engine import BrokerCost # ブローカーコスト設定 cost = BrokerCost.tradeview_ilc() # コストをR単位で計算 instruments = ["EURUSD"] * len(signal_bars) entry_costs = cost.per_trade_cost(instruments, sl_distances) # NET結果(コスト適用後) results = simulate_trades( h, l, c, signal_bars, directions, sl_distances, tp_distances, max_hold=100, open_prices=o, # 次バーオープン entry_costs=entry_costs, # コスト適用 ) print(f"PF (NET): {results.profit_factor:.2f}") print(f"Cost label: {results.cost_label}") ``` -------------------------------- ### dd_percentile() Method Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/MonteCarloDD.md Calculates the drawdown at a specified percentile of the drawdown distribution. ```python dd_95 = mc.dd_percentile(95.0) # 95th percentile DD dd_99 = mc.dd_percentile(99.0) # 99th percentile DD ``` -------------------------------- ### fetch_aggvault 使用例 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/data_utilities.md EURUSD 1時間足データを取得し、ATR を計算して取引をシミュレートする例。 ```python from backtest_engine import fetch_aggvault, simulate_trades, atr, LONG import numpy as np # EURUSD 1時間足、1年分を取得 ts, o, h, l, c, v = fetch_aggvault( symbol="EURUSD", timeframe="1h", start="2024-01-01", end="2025-01-01", ) print(f"取得データ: {len(c)} バー") print(f"期間: {ts[0]} ~ {ts[-1]}") # ATR計算 atr_vals = atr(h, l, c, 14) # シミュレーション signal_bars = np.array([100, 250, 400], dtype=np.int32) directions = np.ones(3, dtype=np.int8) * LONG sl_distances = atr_vals[signal_bars] * 1.5 tp_distances = atr_vals[signal_bars] * 3.0 results = simulate_trades( h, l, c, signal_bars, directions, sl_distances, tp_distances, max_hold=100, ) print(f"PF: {results.profit_factor:.2f}") ``` -------------------------------- ### Customizable Thresholds (Class Variables) Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/GateKeeper.md Examples of how to customize the thresholds for each gate using class variables. ```python gk = GateKeeper(...) # Gate 1 閾値 gk.GATE1_MIN_PF = 1.05 # PF >= 1.05 gk.GATE1_MIN_TRADES = 30 # 最低トレード数 # Gate 2 閾値 gk.GATE2_MIN_PF = 1.10 gk.GATE2_MIN_RF = 1.5 # Recovery Factor gk.GATE2_MIN_TRADES = 50 # Gate 3 閾値 gk.GATE3_MAX_PBO = 0.40 # PBO <= 40% gk.GATE3_MIN_WFA_WINRATE = 0.55 # OOS 勝率 >= 55% # Gate 4 閾値 gk.GATE4_MIN_MC_PASS = 0.70 # MC通過率 >= 70% ``` -------------------------------- ### fetch_aggvault シグネチャ Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/data_utilities.md AggVault API から OHLC データを取得するための関数シグネチャ。 ```python def fetch_aggvault( symbol: str, timeframe: str, start: str, end: str, api_key: Optional[str] = None, base_url: str = "https://tick.hugen.tokyo", ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray] ``` -------------------------------- ### Add Custom Section Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/report.md Example of adding a custom section to the report with custom HTML content. ```python from backtest_engine import Section custom_section = Section( title="カスタム分析", html="""

月別成績(詳細)

2024年1月: PF=1.2, n=12
2024年2月: PF=0.8, n=8
...

"") cfg = ReportConfig( # ... 基本設定 sections=[custom_section], ) generate_report(cfg, "detailed_report.html") ``` -------------------------------- ### load_ohlcv 使用例 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/data_utilities.md CSV ファイルから OHLC データをロードする簡単な例。 ```python from backtest_engine import load_ohlcv ts, o, h, l, c, v = load_ohlcv("data/eurusd_1h.csv") print(f"ロード: {len(c)} バー") ``` -------------------------------- ### Basic Simulation (GROSS, No Costs) Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/simulate_trades.md Demonstrates a basic simulation using fetched data, ATR-based stop-loss and take-profit levels, and generating trades without considering broker costs. ```python from backtest_engine import fetch_aggvault, simulate_trades, atr, LONG # データ取得 ts, o, h, l, c, v = fetch_aggvault("EURUSD", "1h", "2024-01-01", "2025-01-01") # ATRベースのSL/TP atr_vals = atr(h, l, c, 14) # シグナル生成 signal_bars = np.array([100, 250, 400], dtype=np.int32) directions = np.array([LONG, LONG, LONG], dtype=np.int8) sl_distances = atr_vals[signal_bars] * 1.5 tp_distances = atr_vals[signal_bars] * 3.0 # シミュレーション実行(GROSS) results = simulate_trades( h, l, c, signal_bars, directions, sl_distances, tp_distances, max_hold=100, ) print(f"Profit Factor: {results.profit_factor:.2f}") print(f"Win Rate: {results.win_rate:.1%}") ``` -------------------------------- ### load_ohlcv シグネチャ Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/data_utilities.md CSV ファイルから OHLC データを読み込むための関数シグネチャ。 ```python def load_ohlcv(filepath: str) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray] ``` -------------------------------- ### prop_firm_check() Method Example Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/MonteCarloDD.md Validates against prop firm drawdown limits, checking maximum drawdown and total drawdown at specified confidence levels. ```python from backtest_engine import MonteCarloDD, simulate_trades, fetch_aggvault, atr, LONG import numpy as np results = simulate_trades(...) # Assume results are obtained mc = MonteCarloDD(results["pnl_r"], n_sims=10_000, risk_pct=0.01, seed=42) check = mc.prop_firm_check( max_dd_limit=0.04, # 4% DD limit total_dd_limit=0.08, # 8% total DD limit confidence=95.0, # Verify at 95th percentile ) if check["pass"]: print("✓ Passed prop firm conditions") else: print("✗ Conditions not met") if not check["max_dd_ok"]: print(f" Max DD: {check['dd_confidence']:.2%} > {max_dd_limit:.2%}") if not check["total_dd_ok"]: print(f" Total DD: {check['dd_99']:.2%} > {total_dd_limit:.2%}") ``` -------------------------------- ### ローリング vs アンカー型 — ローリング型(固定サイズウィンドウがスライド)— デフォルト Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md ローリング型(固定サイズウィンドウがスライド)— デフォルト ```python # ローリング型(固定サイズウィンドウがスライド)— デフォルト wf = WalkForward(n_bars=len(close), is_ratio=0.7, n_splits=5, anchored=False) ``` -------------------------------- ### BacktestQualityWarning 抑制方法 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md BacktestQualityWarning を抑制するための Python の warnings モジュールを使用した例。 ```python import warnings from backtest_engine import BacktestQualityWarning, simulate_trades # 全て抑制 warnings.filterwarnings("ignore", category=BacktestQualityWarning) # または呼び出しごとに results = simulate_trades( ..., preflight=False, # 品質チェック自体を実行しない ) # または特定の条件のみ表示 warnings.filterwarnings("error", category=BacktestQualityWarning) try: results = simulate_trades(...) except BacktestQualityWarning: print("品質警告あり") ``` -------------------------------- ### IS/OOS 分割比 — 60% IS / 40% OOS(より攻撃的) Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md 60% IS / 40% OOS(より攻撃的) ```python # 60% IS / 40% OOS(より攻撃的) wf = WalkForward(n_bars=len(close), is_ratio=0.6, n_splits=5) ``` -------------------------------- ### Retrace Entry and Break-Even Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/simulate_trades.md Illustrates a simulation with retrace entry logic and break-even trigger, allowing for entries after a retracement and moving to break-even upon reaching a certain profit target percentage. ```python results = simulate_trades( h, l, c, signal_bars, directions, sl_distances, tp_distances, max_hold=100, open_prices=o, entry_costs=entry_costs, retrace_pct=0.5, # TP距離の50%だけリトレース後にエントリー retrace_timeout=20, # 最大20バー待機 be_trigger_pct=0.5, # TP到達の50%でBEに移動 ) ``` -------------------------------- ### "trailing" — Trailing Stop Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/simulate_trades.md Example of using simulate_trades with the "trailing" exit mode, specifying activation and distance in R multiples. ```python results = simulate_trades( high, low, close, signal_bars, directions, sl_distances, tp_distances, max_hold=100, exit_mode="trailing", trail_activation_r=1.5, # 1.5R利益時に発動 trail_distance_r=0.5, # 0.5Rの距離で追随 ) ``` -------------------------------- ### ローリング vs アンカー型 — アンカー型(IS常に開始から、OOS拡大) Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md アンカー型(IS常に開始から、OOS拡大) ```python # アンカー型(IS常に開始から、OOS拡大) wf = WalkForward(n_bars=len(close), is_ratio=0.7, n_splits=5, anchored=True) ``` -------------------------------- ### "custom" — Custom Exit Signal Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/simulate_trades.md Example of using simulate_trades with the "custom" exit mode, providing a custom exit signal array. ```python exit_sigs = np.zeros(len(close), dtype=bool) exit_sigs[my_exit_indices] = True results = simulate_trades( high, low, close, signal_bars, directions, sl_distances, tp_distances, max_hold=100, exit_mode="custom", exit_signals=exit_sigs, ) ``` -------------------------------- ### 基本的なレポート Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md 基本的なレポート ```python from backtest_engine import generate_report, ReportConfig, SummaryCell, GateRow cfg = ReportConfig( title="RSI Reversal — EURUSD", subtitle="RSI(14) 30/70 | 1H | 2024–2025 | NET", verdict="PASS", equity_curve=np.cumsum(results["pnl_r"]), equity_timestamps=ts[results["entry_bar"]], summary=[ SummaryCell("取引数", str(len(results)), ""), SummaryCell("PF", f"{results.profit_factor:.2f}", ""), ], strategy_html="Entry: RSI < 30 or > 70
Exit: TP or SL", trades=results, trade_timestamps=ts, ) generate_report(cfg, "report.html") ``` -------------------------------- ### "sar_trailing" — Parabolic SAR-based Trailing Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/simulate_trades.md Example of using simulate_trades with the "sar_trailing" exit mode, utilizing pre-calculated Parabolic SAR values. ```python sar, trend, sar_stop = parabolic_sar(high, low) results = simulate_trades( high, low, close, signal_bars, directions, sl_distances, tp_distances, max_hold=100, exit_mode="sar_trailing", sar_values=sar_stop, ) ``` -------------------------------- ### "rr" — Fixed Risk-Reward Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/simulate_trades.md Example of using simulate_trades with the "rr" exit mode, including break-even trigger and next-bar open price execution. ```python results = simulate_trades( high, low, close, signal_bars, directions, sl_distances, tp_distances, max_hold=100, exit_mode="rr", be_trigger_pct=0.5, # TP到達の50%時点でBEに移動 open_prices=open_, # 次バーオープンで約定 ) ``` -------------------------------- ### WFA / CSCV 結果をレポートに含める Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md WFA / CSCV 結果をレポートに含める ```python from backtest_engine import generate_report, ReportConfig, WfaRow, CscvResult cfg = ReportConfig( # ... 基本設定 wfa=wfa_result, # WalkForward 結果を追加 cscv=cscv_result, # CSCV 結果を追加 ) generate_report(cfg, "report.html") ``` -------------------------------- ### fetch_aggvault エラーハンドリング Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/api-reference/data_utilities.md fetch_aggvault 関数で発生する可能性のある ValueError と RuntimeError の処理例。 ```python from backtest_engine import fetch_aggvault try: ts, o, h, l, c, v = fetch_aggvault( "EURUSD", "1h", "2024-01-01", "2025-01-01", ) except ValueError as e: print(f"入力エラー: {e}") # API キー不足、日付形式不正、無効なタイムフレーム except RuntimeError as e: print(f"API エラー: {e}") # 401: API キー無効 # 403: アクセス権限不足 # 404: シンボル/日付範囲でデータ不在 # 429: レート制限(最大10リクエスト/分) ``` -------------------------------- ### 資産クラス別推奨値 — 株式(Stock)— より保守的 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md 資産クラス別推奨値 — 株式(Stock)— より保守的 ```python gk.GATE1_MIN_PF = 1.10 gk.GATE2_MIN_PF = 1.20 gk.GATE2_MIN_RF = 2.0 gk.GATE3_MAX_PBO = 0.30 gk.GATE4_MIN_MC_PASS = 0.80 ``` -------------------------------- ### Gate 3 カスタム閾値 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md Gate 3 カスタム閾値 ```python gk.GATE3_MAX_PBO = 0.30 # PBO <= 30%(厳しく) gk.GATE3_MIN_WFA_WINRATE = 0.60 # OOS win rate >= 60% ``` -------------------------------- ### StressTest ブロック・ブートストラップ設定例 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md StressTest クラスでブロック・ブートストラップのブロックサイズを設定する例。 ```python st = StressTest(pnl_r) # ブロックサイズ = 10(デフォルト) bb = st.block_bootstrap(block_size=10) # ブロックサイズ = 5(損失クラスタ短い戦略向け) bb = st.block_bootstrap(block_size=5) # ブロックサイズ = 20(損失クラスタ長い戦略向け) bb = st.block_bootstrap(block_size=20) ``` -------------------------------- ### IS/OOS 分割比 — 80% IS / 20% OOS(より慎重) Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md 80% IS / 20% OOS(より慎重) ```python # 80% IS / 20% OOS(より慎重) wf = WalkForward(n_bars=len(close), is_ratio=0.8, n_splits=5) ``` -------------------------------- ### Gate 2 カスタム閾値 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md Gate 2 カスタム閾値 ```python gk.GATE2_MIN_PF = 1.15 gk.GATE2_MIN_RF = 2.0 # Recovery Factor >= 2.0 gk.GATE2_MIN_TRADES = 100 ``` -------------------------------- ### CSCV 分割数 — 8分割(高速、C(8,4)=70組み合わせ) Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md 8分割(高速、C(8,4)=70組み合わせ) ```python # 8分割(高速、C(8,4)=70組み合わせ) cscv = CSCV(n_splits=8) ``` -------------------------------- ### CSCV 分割数 — 10分割(デフォルト、C(10,5)=252組み合わせ) Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md 10分割(デフォルト、C(10,5)=252組み合わせ) ```python # 10分割(デフォルト、C(10,5)=252組み合わせ) cscv = CSCV(n_splits=10) ``` -------------------------------- ### 資産クラス別推奨値 — 外国為替(FX)— デフォルト Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md 資産クラス別推奨値 — 外国為替(FX)— デフォルト ```python gk.GATE1_MIN_PF = 1.05 gk.GATE2_MIN_PF = 1.10 gk.GATE2_MIN_RF = 1.5 gk.GATE3_MAX_PBO = 0.40 gk.GATE4_MIN_MC_PASS = 0.70 ``` -------------------------------- ### 資産クラス別推奨値 — 暗号資産(Crypto)— より攻撃的 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md 資産クラス別推奨値 — 暗号資産(Crypto)— より攻撃的 ```python gk.GATE1_MIN_PF = 1.02 gk.GATE2_MIN_PF = 1.05 gk.GATE2_MIN_RF = 1.2 gk.GATE3_MAX_PBO = 0.50 gk.GATE4_MIN_MC_PASS = 0.60 ``` -------------------------------- ### BrokerCost プリセット設定例 Source: https://github.com/bartonguestier1725-collab/backtest-engine/blob/main/_autodocs/configuration.md BrokerCost クラスのプリセット(Tradeview ILC, Fundora)を使用した設定例。 ```python from backtest_engine import BrokerCost # Tradeview ILC — ECN、$5 RT手数料 cost_tv = BrokerCost.tradeview_ilc() # Fundora — プロップ企業、手数料なし cost_fundora = BrokerCost.fundora() ```