-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBacktesterTest.php
More file actions
219 lines (185 loc) · 9.54 KB
/
BacktesterTest.php
File metadata and controls
219 lines (185 loc) · 9.54 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
<?php
namespace Stochastix\Tests\Domain\Backtesting\Service;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
use PHPUnit\Framework\TestCase;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\NullLogger;
use Stochastix\Domain\Backtesting\Dto\BacktestConfiguration;
use Stochastix\Domain\Backtesting\Service\Backtester;
use Stochastix\Domain\Backtesting\Service\MultiTimeframeDataServiceInterface;
use Stochastix\Domain\Backtesting\Service\SeriesMetricServiceInterface;
use Stochastix\Domain\Backtesting\Service\StatisticsServiceInterface;
use Stochastix\Domain\Common\Enum\DirectionEnum;
use Stochastix\Domain\Common\Enum\TimeframeEnum;
use Stochastix\Domain\Common\Model\MultiTimeframeOhlcvSeries;
use Stochastix\Domain\Data\Service\BinaryStorageInterface;
use Stochastix\Domain\Order\Enum\OrderTypeEnum;
use Stochastix\Domain\Strategy\AbstractStrategy;
use Stochastix\Domain\Strategy\Attribute\AsStrategy;
use Stochastix\Domain\Strategy\Service\StrategyRegistryInterface;
use Stochastix\Domain\Strategy\StrategyInterface;
class BacktesterTest extends TestCase
{
private Backtester $backtester;
private StrategyRegistryInterface $strategyRegistryMock;
private BinaryStorageInterface $binaryStorageMock;
private StatisticsServiceInterface $statisticsServiceMock;
private SeriesMetricServiceInterface $seriesMetricServiceMock;
private MultiTimeframeDataServiceInterface $multiTimeframeDataServiceMock;
private EventDispatcherInterface $eventDispatcherMock;
private vfsStreamDirectory $vfsRoot;
protected function setUp(): void
{
parent::setUp();
$this->strategyRegistryMock = $this->createMock(StrategyRegistryInterface::class);
$this->binaryStorageMock = $this->createMock(BinaryStorageInterface::class);
$this->statisticsServiceMock = $this->createMock(StatisticsServiceInterface::class);
$this->seriesMetricServiceMock = $this->createMock(SeriesMetricServiceInterface::class);
$this->multiTimeframeDataServiceMock = $this->createMock(MultiTimeframeDataServiceInterface::class);
$this->eventDispatcherMock = $this->createMock(EventDispatcherInterface::class);
$this->vfsRoot = vfsStream::setup('data');
$this->backtester = new Backtester(
$this->strategyRegistryMock,
$this->binaryStorageMock,
$this->statisticsServiceMock,
$this->seriesMetricServiceMock,
$this->multiTimeframeDataServiceMock,
$this->eventDispatcherMock,
new NullLogger(),
$this->vfsRoot->url()
);
}
public function testRunExecutesFullLifecycleForSingleSymbol(): void
{
$commissionConfig = ['type' => 'percentage', 'rate' => '0.001'];
$config = new BacktestConfiguration(
'test_strat',
'Test\Strategy',
['BTC/USDT'],
TimeframeEnum::D1,
new \DateTimeImmutable('2023-01-01'),
new \DateTimeImmutable('2023-01-03'),
'10000',
'USDT',
null,
$commissionConfig,
'stchx_binary',
'vfs',
[],
[]
);
$mockStrategy = $this->createMock(StrategyInterface::class);
$mockMetadata = new AsStrategy(alias: 'test_strat', name: 'Test Strategy');
$mockMarketData = [
['timestamp' => 1, 'open' => 100, 'high' => 101, 'low' => 99, 'close' => 100, 'volume' => 1000],
['timestamp' => 2, 'open' => 100, 'high' => 102, 'low' => 100, 'close' => 101, 'volume' => 1200],
];
$this->strategyRegistryMock->expects($this->once())
->method('getStrategy')->with('test_strat')->willReturn($mockStrategy);
$this->strategyRegistryMock->expects($this->once())
->method('getStrategyMetadata')->with('test_strat')->willReturn($mockMetadata);
vfsStream::create(['vfs' => ['BTC_USDT' => ['1d.stchx' => 'dummy_data']]], $this->vfsRoot);
$this->binaryStorageMock->expects($this->exactly(2))
->method('readRecordsByTimestampRange')
->willReturnCallback(static fn (): \Generator => yield from $mockMarketData);
$mockStrategy->expects($this->once())->method('configure');
$mockStrategy->expects($this->once())->method('initialize');
$mockStrategy->expects($this->exactly(2))->method('onBar');
$this->statisticsServiceMock->expects($this->once())->method('calculate')->willReturn(['summaryMetrics' => ['finalBalance' => '10000']]);
$this->seriesMetricServiceMock->expects($this->once())->method('calculate')->willReturn(['equity' => ['value' => [10000, 10000]]]);
$results = $this->backtester->run($config, 'test_run');
$this->assertIsArray($results);
$this->assertArrayHasKey('status', $results);
$this->assertEquals('10000', $results['finalCapital']);
$this->assertArrayHasKey('statistics', $results);
$this->assertArrayHasKey('timeSeriesMetrics', $results);
$this->assertArrayHasKey('equity', $results['timeSeriesMetrics']);
$this->assertCount(2, $results['timestamps']);
}
public function testProgressCallbackIsInvokedCorrectly(): void
{
$commissionConfig = ['type' => 'percentage', 'rate' => '0.001'];
$config = new BacktestConfiguration(
'test_strat',
'Test\Strategy',
['BTC/USDT'],
TimeframeEnum::H1,
null,
null,
'10000',
'USDT',
null,
$commissionConfig,
'stchx_binary',
'vfs',
[],
[]
);
$mockMarketData = array_fill(0, 5, ['timestamp' => 1, 'open' => 1, 'high' => 1, 'low' => 1, 'close' => 1, 'volume' => 1]);
$mockMetadata = new AsStrategy(alias: 'test_strat', name: 'Test Strategy');
$this->strategyRegistryMock->method('getStrategy')->willReturn($this->createMock(StrategyInterface::class));
$this->strategyRegistryMock->method('getStrategyMetadata')->willReturn($mockMetadata);
$this->binaryStorageMock->method('readRecordsByTimestampRange')
->willReturnCallback(static fn (): \Generator => yield from $mockMarketData);
vfsStream::create(['vfs' => ['BTC_USDT' => ['1h.stchx' => 'dummy_data']]], $this->vfsRoot);
$this->statisticsServiceMock->method('calculate')->willReturn([]);
$this->seriesMetricServiceMock->method('calculate')->willReturn([]);
$callCount = 0;
$progressCallback = function (int $processed, int $total) use (&$callCount, $mockMarketData) {
++$callCount;
$this->assertEquals(count($mockMarketData), $total);
$this->assertEquals($callCount, $processed);
};
$this->backtester->run($config, 'test_run', $progressCallback);
$this->assertEquals(5, $callCount);
}
public function testRunHandlesUnclosedShortPositionCorrectly(): void
{
$initialCapital = '10000';
$commissionConfig = ['type' => 'percentage', 'rate' => '0.0']; // No commission for simple test
$config = new BacktestConfiguration(
'test_strat',
'Test\Strategy',
['BTC/USDT'],
TimeframeEnum::D1,
null,
null,
$initialCapital,
'USDT',
null,
$commissionConfig,
'stchx_binary',
'vfs',
[],
[]
);
// Mock the AbstractStrategy directly, not the interface, to get access to protected methods.
$mockStrategy = $this->createMock(AbstractStrategy::class);
$mockStrategy->method('onBar')
->willReturnCallback(function (MultiTimeframeOhlcvSeries $bars) use ($mockStrategy) {
// We use reflection to call the protected 'entry' method on the mocked object
$entryCallable = (new \ReflectionMethod(AbstractStrategy::class, 'entry'))->getClosure($mockStrategy);
$entryCallable(DirectionEnum::Short, OrderTypeEnum::Market, '0.5');
});
$this->strategyRegistryMock->method('getStrategy')->willReturn($mockStrategy);
$this->strategyRegistryMock->method('getStrategyMetadata')->willReturn(new AsStrategy('test_strat', 'Test'));
$mockMarketData = [
['timestamp' => 1, 'open' => 3000, 'high' => 3000, 'low' => 3000, 'close' => 3000, 'volume' => 1000],
['timestamp' => 2, 'open' => 3100, 'high' => 3100, 'low' => 3100, 'close' => 3100, 'volume' => 1000],
['timestamp' => 3, 'open' => 2900, 'high' => 2900, 'low' => 2900, 'close' => 2900, 'volume' => 1000],
];
vfsStream::create(['vfs' => ['BTC_USDT' => ['1d.stchx' => 'dummy_data']]], $this->vfsRoot);
$this->binaryStorageMock->method('readRecordsByTimestampRange')->willReturnCallback(static fn (): \Generator => yield from $mockMarketData);
$this->statisticsServiceMock->method('calculate')->willReturn([]);
$this->seriesMetricServiceMock->method('calculate')->willReturn([]);
$results = $this->backtester->run($config, 'test_run');
// Unrealized PNL = (Entry Price - Current Price) * Quantity = (3100 - 2900) * 0.5 = 100
$expectedUnrealizedPnl = '100';
// Final Capital = Initial Capital + Unrealized PNL = 10000 + 100 = 10100
$expectedFinalCapital = '10100';
$this->assertCount(1, $results['openPositions']);
$this->assertEquals($expectedUnrealizedPnl, $results['openPositions'][0]['unrealizedPnl']);
$this->assertEquals($expectedFinalCapital, $results['finalCapital']);
}
}