-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbacktest_optimized.php
More file actions
288 lines (256 loc) · 11.4 KB
/
backtest_optimized.php
File metadata and controls
288 lines (256 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
<?php
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
use Illuminate\Support\Facades\DB;
// 現在の最適化設定
$lookbackPeriod = 20;
$breakoutThreshold = 0.15; // 最適化済み
$initialTrailingStopPercent = 0.5; // 最適化済み
$trailingOffsetPercent = 0.5;
$stopLossPercent = 1.0;
echo "========================================\n";
echo "バックテスト実行 - 最適化設定\n";
echo "========================================\n";
echo "ブレイクアウト閾値: {$breakoutThreshold}%\n";
echo "初期トレーリングS: {$initialTrailingStopPercent}%\n";
echo "トレーリングオフセット: {$trailingOffsetPercent}%\n";
echo "固定損切り: {$stopLossPercent}%\n";
echo "lookback_period: {$lookbackPeriod}本\n";
echo "========================================\n\n";
// 価格履歴データを取得
$prices = DB::table('price_history')
->where('symbol', 'XRP/JPY')
->orderBy('recorded_at', 'asc')
->get();
if ($prices->count() < $lookbackPeriod + 50) {
echo "エラー: 価格データが不足しています(必要: " . ($lookbackPeriod + 50) . "本、利用可能: {$prices->count()}本)\n";
exit(1);
}
echo "価格データ数: {$prices->count()}本\n";
echo "期間: {$prices->first()->recorded_at} ~ {$prices->last()->recorded_at}\n\n";
// バックテスト用の仮想ポジション
$positions = [];
$closedTrades = [];
$tradeId = 1;
// 各時点でのシミュレーション
for ($i = $lookbackPeriod; $i < $prices->count(); $i++) {
$currentPrice = (float)$prices[$i]->price;
$currentTime = $prices[$i]->recorded_at;
// 過去N本の価格
$historicalPrices = [];
for ($j = $i - $lookbackPeriod; $j < $i; $j++) {
$historicalPrices[] = (float)$prices[$j]->price;
}
$highestHigh = max($historicalPrices);
$lowestLow = min($historicalPrices);
// ブレイクアウト閾値
$buyThreshold = $highestHigh * (1 + $breakoutThreshold / 100);
$sellThreshold = $lowestLow * (1 - $breakoutThreshold / 100);
// 既存ポジションの損切り・トレーリングストップチェック
foreach ($positions as $key => $pos) {
$shouldClose = false;
$closeReason = '';
if ($pos['side'] === 'long') {
// ロングの固定損切り
$stopLossPrice = $pos['entry_price'] * (1 - $stopLossPercent / 100);
if ($currentPrice <= $stopLossPrice) {
$shouldClose = true;
$closeReason = 'stop_loss';
}
// トレーリングストップ
elseif ($currentPrice <= $pos['trailing_stop']) {
$shouldClose = true;
$closeReason = 'trailing_stop';
}
// トレーリングストップの更新
else {
$newTrailingStop = $currentPrice * (1 - $trailingOffsetPercent / 100);
if ($newTrailingStop > $pos['trailing_stop']) {
$positions[$key]['trailing_stop'] = $newTrailingStop;
$positions[$key]['highest_price'] = $currentPrice;
}
}
} else { // short
// ショートの固定損切り
$stopLossPrice = $pos['entry_price'] * (1 + $stopLossPercent / 100);
if ($currentPrice >= $stopLossPrice) {
$shouldClose = true;
$closeReason = 'stop_loss';
}
// トレーリングストップ
elseif ($currentPrice >= $pos['trailing_stop']) {
$shouldClose = true;
$closeReason = 'trailing_stop';
}
// トレーリングストップの更新
else {
$newTrailingStop = $currentPrice * (1 + $trailingOffsetPercent / 100);
if ($newTrailingStop < $pos['trailing_stop']) {
$positions[$key]['trailing_stop'] = $newTrailingStop;
$positions[$key]['lowest_price'] = $currentPrice;
}
}
}
if ($shouldClose) {
$profitLoss = $pos['side'] === 'long'
? ($currentPrice - $pos['entry_price']) * $pos['quantity']
: ($pos['entry_price'] - $currentPrice) * $pos['quantity'];
$closedTrades[] = [
'id' => $pos['id'],
'side' => $pos['side'],
'entry_price' => $pos['entry_price'],
'exit_price' => $currentPrice,
'entry_time' => $pos['entry_time'],
'exit_time' => $currentTime,
'profit_loss' => $profitLoss,
'reason' => $closeReason,
];
unset($positions[$key]);
}
}
// 新規エントリーシグナル
$longCount = count(array_filter($positions, fn($p) => $p['side'] === 'long'));
$shortCount = count(array_filter($positions, fn($p) => $p['side'] === 'short'));
// 高値ブレイクアウト(買いシグナル)
if ($currentPrice > $buyThreshold) {
if ($shortCount > 0) {
// ショートポジションがある場合は全決済
foreach ($positions as $key => $pos) {
if ($pos['side'] === 'short') {
$profitLoss = ($pos['entry_price'] - $currentPrice) * $pos['quantity'];
$closedTrades[] = [
'id' => $pos['id'],
'side' => $pos['side'],
'entry_price' => $pos['entry_price'],
'exit_price' => $currentPrice,
'entry_time' => $pos['entry_time'],
'exit_time' => $currentTime,
'profit_loss' => $profitLoss,
'reason' => 'reversal_signal',
];
unset($positions[$key]);
}
}
// ロング新規エントリー
$positions[] = [
'id' => $tradeId++,
'side' => 'long',
'entry_price' => $currentPrice,
'entry_time' => $currentTime,
'quantity' => 0.01,
'trailing_stop' => $currentPrice * (1 - $initialTrailingStopPercent / 100),
'highest_price' => $currentPrice,
];
} elseif ($longCount < 3) {
// ロング追加エントリー
$positions[] = [
'id' => $tradeId++,
'side' => 'long',
'entry_price' => $currentPrice,
'entry_time' => $currentTime,
'quantity' => 0.01,
'trailing_stop' => $currentPrice * (1 - $initialTrailingStopPercent / 100),
'highest_price' => $currentPrice,
];
}
}
// 安値ブレイクダウン(売りシグナル)
if ($currentPrice < $sellThreshold) {
if ($longCount > 0) {
// ロングポジションがある場合は全決済
foreach ($positions as $key => $pos) {
if ($pos['side'] === 'long') {
$profitLoss = ($currentPrice - $pos['entry_price']) * $pos['quantity'];
$closedTrades[] = [
'id' => $pos['id'],
'side' => $pos['side'],
'entry_price' => $pos['entry_price'],
'exit_price' => $currentPrice,
'entry_time' => $pos['entry_time'],
'exit_time' => $currentTime,
'profit_loss' => $profitLoss,
'reason' => 'reversal_signal',
];
unset($positions[$key]);
}
}
// ショート新規エントリー
$positions[] = [
'id' => $tradeId++,
'side' => 'short',
'entry_price' => $currentPrice,
'entry_time' => $currentTime,
'quantity' => 0.01,
'trailing_stop' => $currentPrice * (1 + $initialTrailingStopPercent / 100),
'lowest_price' => $currentPrice,
];
} elseif ($shortCount < 3) {
// ショート追加エントリー
$positions[] = [
'id' => $tradeId++,
'side' => 'short',
'entry_price' => $currentPrice,
'entry_time' => $currentTime,
'quantity' => 0.01,
'trailing_stop' => $currentPrice * (1 + $initialTrailingStopPercent / 100),
'lowest_price' => $currentPrice,
];
}
}
}
// 結果集計
echo "\n========================================\n";
echo "バックテスト結果\n";
echo "========================================\n\n";
$totalTrades = count($closedTrades);
$winningTrades = array_filter($closedTrades, fn($t) => $t['profit_loss'] > 0);
$losingTrades = array_filter($closedTrades, fn($t) => $t['profit_loss'] <= 0);
$winCount = count($winningTrades);
$lossCount = count($losingTrades);
$winRate = $totalTrades > 0 ? ($winCount / $totalTrades) * 100 : 0;
$totalProfit = array_sum(array_column($closedTrades, 'profit_loss'));
$avgProfit = $totalTrades > 0 ? $totalProfit / $totalTrades : 0;
$avgWin = $winCount > 0 ? array_sum(array_column($winningTrades, 'profit_loss')) / $winCount : 0;
$avgLoss = $lossCount > 0 ? array_sum(array_column($losingTrades, 'profit_loss')) / $lossCount : 0;
echo "総トレード数: {$totalTrades}件\n";
echo "勝ちトレード: {$winCount}件\n";
echo "負けトレード: {$lossCount}件\n";
echo "勝率: " . number_format($winRate, 2) . "%\n\n";
echo "総損益: " . number_format($totalProfit, 4) . "円\n";
echo "平均損益: " . number_format($avgProfit, 4) . "円\n";
echo "平均利益: " . number_format($avgWin, 4) . "円\n";
echo "平均損失: " . number_format($avgLoss, 4) . "円\n";
echo "プロフィットファクター: " . ($avgLoss != 0 ? number_format(abs($avgWin / $avgLoss), 2) : 'N/A') . "\n\n";
// 決済理由別集計
$reasonStats = [];
foreach ($closedTrades as $trade) {
$reason = $trade['reason'];
if (!isset($reasonStats[$reason])) {
$reasonStats[$reason] = ['count' => 0, 'profit' => 0];
}
$reasonStats[$reason]['count']++;
$reasonStats[$reason]['profit'] += $trade['profit_loss'];
}
echo "--- 決済理由別統計 ---\n";
foreach ($reasonStats as $reason => $stats) {
$reasonName = [
'stop_loss' => '固定損切り',
'trailing_stop' => 'トレーリングS',
'reversal_signal' => '逆方向シグナル',
][$reason] ?? $reason;
echo "{$reasonName}: {$stats['count']}件 (損益: " . number_format($stats['profit'], 4) . "円)\n";
}
echo "\n--- 最新10件のトレード ---\n";
$recentTrades = array_slice($closedTrades, -10);
foreach (array_reverse($recentTrades) as $trade) {
$pl = $trade['profit_loss'];
$plStr = ($pl > 0 ? '+' : '') . number_format($pl, 4);
$reasonName = [
'stop_loss' => '損切',
'trailing_stop' => 'トレS',
'reversal_signal' => '反転',
][$trade['reason']] ?? $trade['reason'];
echo "#{$trade['id']} {$trade['side']} {$trade['entry_price']}円 → {$trade['exit_price']}円 = {$plStr}円 ({$reasonName})\n";
}
echo "\n========================================\n";