-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBacktestingCommand.php
More file actions
354 lines (298 loc) · 14.8 KB
/
BacktestingCommand.php
File metadata and controls
354 lines (298 loc) · 14.8 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<?php
namespace Stochastix\Command;
use Psr\EventDispatcher\EventDispatcherInterface;
use Stochastix\Domain\Backtesting\Dto\BacktestConfiguration;
use Stochastix\Domain\Backtesting\Event\BacktestPhaseEvent;
use Stochastix\Domain\Backtesting\Repository\BacktestResultRepositoryInterface;
use Stochastix\Domain\Backtesting\Service\Backtester;
use Stochastix\Domain\Backtesting\Service\BacktestResultSaver;
use Stochastix\Domain\Backtesting\Service\ConfigurationResolver;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\TableSeparator;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Stopwatch\Stopwatch;
#[AsCommand(
name: 'stochastix:backtesting',
description: 'Runs a backtest based on a strategy and configuration overrides.',
aliases: ['stx:backtest']
)]
class BacktestingCommand extends Command
{
private const int DISPLAY_SCALE_CURRENCY = 2;
private const int DISPLAY_SCALE_PERCENT = 2;
private const int DISPLAY_SCALE_PRICE = 5;
private const int DISPLAY_SCALE_QTY = 6;
public function __construct(
private readonly Backtester $backtester,
private readonly ConfigurationResolver $configResolver,
private readonly BacktestResultRepositoryInterface $resultRepository,
private readonly BacktestResultSaver $resultSaver,
private readonly EventDispatcherInterface $eventDispatcher,
) {
parent::__construct();
}
protected function configure(): void
{
$this
->setHelp('Runs a backtest. Specify a strategy alias and optionally override any configuration (from #[Input] or stochastix.yaml defaults) using options.')
->addArgument('strategy-alias', InputArgument::REQUIRED, 'The alias of the strategy to run (defined in #[AsStrategy]).')
->addOption('symbol', 's', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Override symbols.')
->addOption('timeframe', 't', InputOption::VALUE_REQUIRED, 'Override timeframe.')
->addOption('start-date', 'S', InputOption::VALUE_REQUIRED, 'Override start date (YYYY-MM-DD).')
->addOption('end-date', 'E', InputOption::VALUE_REQUIRED, 'Override end date (YYYY-MM-DD).')
->addOption('input', 'i', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Override a strategy input (e.g., -i ema:10).')
->addOption('config', 'c', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Override a global config (e.g., -c initial_capital:50000).')
->addOption('load-config', 'l', InputOption::VALUE_REQUIRED, 'Load config from JSON file.')
->addOption('save-config', null, InputOption::VALUE_REQUIRED, 'Save config to JSON file and exit.')
->addOption('annual-risk-free-rate', null, InputOption::VALUE_REQUIRED, 'Annual risk-free rate for Sharpe Ratio calculation (e.g., 0.02 for 2%).', 0.02);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$strategyAlias = $input->getArgument('strategy-alias');
$stopwatch = new Stopwatch(true);
$runId = null;
$listener = function (BacktestPhaseEvent $event) use ($stopwatch, &$runId) {
if ($event->runId !== $runId) {
return;
}
$phaseName = $event->phase;
if ($event->eventType === 'start' && !$stopwatch->isStarted($phaseName)) {
$stopwatch->start($phaseName);
} elseif ($event->eventType === 'stop' && $stopwatch->isStarted($phaseName)) {
$stopwatch->stop($phaseName);
}
};
$this->eventDispatcher->addListener(BacktestPhaseEvent::class, $listener);
try {
$io->title(sprintf('🚀 Stochastix Backtester Initializing: %s 🚀', $strategyAlias));
$stopwatch->start('configuration');
$io->text('Resolving configuration...');
$config = $this->configResolver->resolve($input);
$io->text('Configuration resolved.');
$io->newLine();
$stopwatch->stop('configuration');
if ($savePath = $input->getOption('save-config')) {
$this->saveConfigToJson($config, $savePath);
$io->success("Configuration saved to {$savePath}. Exiting as requested.");
$this->displayExecutionTime($io, $stopwatch);
return Command::SUCCESS;
}
$io->section('Final Backtest Configuration');
$definitions = [
['Strategy Alias' => $config->strategyAlias],
['Strategy Class' => $config->strategyClass],
['Symbols' => implode(', ', $config->symbols)],
['Timeframe' => $config->timeframe->value],
['Start Date' => $config->startDate ? $config->startDate->format('Y-m-d') : 'Full History (Start)'],
['End Date' => $config->endDate ? $config->endDate->format('Y-m-d') : 'Full History (End)'],
['Initial Capital' => $this->formatNumber($config->initialCapital, self::DISPLAY_SCALE_CURRENCY)],
['Stake Amount' => $config->stakeAmountConfig !== null ? (is_numeric($config->stakeAmountConfig) && $config->stakeAmountConfig > 0 && $config->stakeAmountConfig <= 1 ? sprintf('%.2f%%', (float) $config->stakeAmountConfig * 100) : $config->stakeAmountConfig) : 'N/A'],
['Exchange' => $config->dataSourceExchangeId],
];
if (!empty($config->strategyInputs)) {
$definitions[] = new TableSeparator();
$definitions[] = ['<info>Strategy Inputs</info>' => ''];
foreach ($config->strategyInputs as $key => $value) {
$displayValue = is_scalar($value) ? (string) $value : json_encode($value);
$definitions[] = [' ' . $key => $displayValue];
}
}
$io->definitionList(...$definitions);
$io->section('Starting Backtest Run...');
$runId = $this->resultRepository->generateRunId($config->strategyAlias);
$io->note("Generated Run ID: {$runId}");
$results = $this->backtester->run($config, $runId);
$stopwatch->start('saving');
$this->resultSaver->save($runId, $results);
$stopwatch->stop('saving');
$io->section('Backtest Performance Summary');
$this->displaySummaryStats($io, $results);
$this->displayTradesLog($io, $results['closedTrades']);
$this->displayOpenPositionsLog($io, $results['openPositions'] ?? []); // NEW
$io->newLine();
$this->displayExecutionTime($io, $stopwatch);
$io->newLine();
$io->success(sprintf('Backtest for "%s" finished successfully.', $strategyAlias));
return Command::SUCCESS;
} catch (\Exception $e) {
$this->displayExecutionTime($io, $stopwatch, true);
$io->error([
'💥 An error occurred:',
$e->getMessage(),
]);
if ($output->isVerbose()) {
$io->newLine();
$io->writeln('<comment>Exception Trace:</comment>');
$io->writeln($e->getTraceAsString());
}
return Command::FAILURE;
} finally {
$this->eventDispatcher->removeListener(BacktestPhaseEvent::class, $listener);
}
}
private function displayExecutionTime(SymfonyStyle $io, Stopwatch $stopwatch, bool $errorOccurred = false): void
{
$rows = [];
$totalDuration = 0;
$peakMemory = 0;
$phases = ['configuration', 'initialization', 'loop', 'statistics', 'saving'];
foreach ($phases as $phase) {
if ($stopwatch->isStarted($phase)) {
$stopwatch->stop($phase);
}
try {
$event = $stopwatch->getEvent($phase);
$duration = $event->getDuration();
$memory = $event->getMemory();
$totalDuration += $duration;
$peakMemory = max($peakMemory, $memory);
$rows[] = [ucfirst($phase), sprintf('%.2f ms', $duration), sprintf('%.2f MB', $memory / (1024 ** 2))];
} catch (\LogicException) {
// Event was not started/stopped, so we can't display it
continue;
}
}
$io->section('Execution Profile');
$io->table(['Phase', 'Duration', 'Memory'], $rows);
$messagePrefix = $errorOccurred ? '📊 Backtest ran for' : '📊 Backtest finished in';
$io->writeln(sprintf(
'%s: <info>%.2f ms</info> / Peak Memory usage: <info>%.2f MB</info>',
$messagePrefix,
$totalDuration,
$peakMemory / (1024 ** 2)
));
}
private function displaySummaryStats(SymfonyStyle $io, array $results): void
{
$stats = $results['statistics']['summaryMetrics'];
$definitions = [
['Initial Capital' => $this->formatNumber($stats['startingBalance'], self::DISPLAY_SCALE_CURRENCY)],
['Final Capital' => $this->formatNumber($stats['finalBalance'], self::DISPLAY_SCALE_CURRENCY)],
['Total Net Profit' => $this->formatNumber($stats['absProfit'], self::DISPLAY_SCALE_CURRENCY)],
['Total Net Profit %' => $this->formatNumber($stats['totalProfitPercentage'], self::DISPLAY_SCALE_PERCENT) . '%'],
new TableSeparator(),
['Total Trades' => $stats['totalTrades']],
['Profit Factor' => $this->formatNumber($stats['profitFactor'], 2)],
new TableSeparator(),
['Sharpe Ratio' => $this->formatNumber($stats['sharpe'], 3)],
['Max Drawdown' => $this->formatNumber($stats['maxAccountUnderwaterPercentage'], self::DISPLAY_SCALE_PERCENT) . '%'],
];
$io->definitionList(...$definitions);
}
private function displayTradesLog(SymfonyStyle $io, array $closedTrades): void
{
if (empty($closedTrades)) {
$io->note('No closed trades to display.');
return;
}
$io->section('Closed Trades Log');
$headers = ['#', 'Symbol', 'Dir', 'Enter Tag', 'Exit Tag', 'Entry Time', 'Exit Time', 'Qty', 'P&L'];
$rows = [];
foreach ($closedTrades as $trade) {
$rows[] = [
$trade['tradeNumber'],
$trade['symbol'],
ucfirst($trade['direction']),
implode(', ', $trade['enterTags'] ?? []),
implode(', ', $trade['exitTags'] ?? []),
$trade['entryTime'],
$trade['exitTime'],
$this->formatNumber($trade['quantity'], self::DISPLAY_SCALE_QTY),
$this->formatNumber($trade['pnl'], self::DISPLAY_SCALE_CURRENCY),
];
}
$io->table($headers, $rows);
}
private function displayOpenPositionsLog(SymfonyStyle $io, array $openPositions): void
{
if (empty($openPositions)) {
return;
}
$io->section('Open Positions at End of Backtest');
$headers = ['Symbol', 'Dir', 'Entry Time', 'Qty', 'Entry Price', 'Current Price', 'Unrealized P&L'];
$rows = [];
foreach ($openPositions as $position) {
$rows[] = [
$position['symbol'],
ucfirst($position['direction']),
$position['entryTime'],
$this->formatNumber($position['quantity'], self::DISPLAY_SCALE_QTY),
$this->formatNumber($position['entryPrice'], self::DISPLAY_SCALE_PRICE),
$this->formatNumber($position['currentPrice'], self::DISPLAY_SCALE_PRICE),
$this->formatNumber($position['unrealizedPnl'], self::DISPLAY_SCALE_CURRENCY),
];
}
$io->table($headers, $rows);
}
private function formatNumber($number, int $scale): string
{
if (!is_numeric($number)) {
return (string) $number;
}
return number_format((float) $number, $scale, '.', '');
}
private function saveConfigToJson(BacktestConfiguration $config, string $filePath): void
{
$dataToSave = [
'core' => [
'strategy_alias' => $config->strategyAlias,
'symbols' => $config->symbols,
'timeframe' => $config->timeframe->value,
'start_date' => $config->startDate?->format('Y-m-d'),
'end_date' => $config->endDate?->format('Y-m-d'),
'initial_capital' => $config->initialCapital,
'stake_currency' => $config->stakeCurrency,
'stake_amount' => $config->stakeAmountConfig,
'commission' => $config->commissionConfig,
'data_source' => [
'type' => $config->dataSourceType,
'exchange_id' => $config->dataSourceExchangeId,
'options' => $config->dataSourceOptions,
],
],
'inputs' => $config->strategyInputs,
];
$json = json_encode($dataToSave, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
file_put_contents($filePath, $json);
}
private function formatDurationFromDays(float $totalDays): string
{
if ($totalDays < 0) {
return 'N/A (invalid duration)';
}
$totalSeconds = (int) round($totalDays * 24 * 60 * 60);
if ($totalSeconds < 60) { // Less than a minute
return $totalSeconds . ' second' . ($totalSeconds === 1 ? '' : 's');
}
$days = floor($totalDays);
$remainingHoursTotal = ($totalDays - $days) * 24;
$hours = floor($remainingHoursTotal);
$remainingMinutesTotal = ($remainingHoursTotal - $hours) * 60;
$minutes = floor($remainingMinutesTotal);
$parts = [];
if ($days > 0) {
$parts[] = sprintf('%d day%s', $days, $days > 1 ? 's' : '');
}
if ($hours > 0) {
$parts[] = sprintf('%d hour%s', $hours, $hours > 1 ? 's' : '');
}
if ($minutes > 0) {
$parts[] = sprintf('%d minute%s', $minutes, $minutes > 1 ? 's' : '');
}
if (empty($parts)) {
// This case should ideally be covered by the $totalSeconds < 60 check,
// but as a fallback if totalDays was extremely small but not negative.
if ($totalSeconds > 0) {
return $totalSeconds . ' second' . ($totalSeconds === 1 ? '' : 's');
}
return '0 minutes'; // Or "Less than a minute" if preferred
}
return implode(' ', $parts);
}
}