-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbacktesting_engine.cpp
More file actions
588 lines (503 loc) · 16.5 KB
/
Copy pathbacktesting_engine.cpp
File metadata and controls
588 lines (503 loc) · 16.5 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
#include <iostream>
#include <vector>
#include <queue>
#include <memory>
#include <string>
#include <unordered_map>
#include <chrono>
#include <functional>
// Forward declarations
class Event;
class MarketEvent;
class SignalEvent;
class OrderEvent;
class FillEvent;
class Strategy;
class Portfolio;
class ExecutionHandler;
class DataHandler;
// Event Types Enum
enum class EventType
{
MARKET,
SIGNAL,
ORDER,
FILL
};
// Order Types
enum class OrderType
{
MARKET,
LIMIT,
STOP
};
// Order Direction
enum class OrderDirection
{
BUY,
SELL
};
// Base Event Class
class Event
{
public:
Event(EventType type) : type_(type) {}
virtual ~Event() = default;
EventType getType() const { return type_; }
virtual std::string toString() const = 0;
protected:
EventType type_;
};
// Market Event - represents new market data
class MarketEvent : public Event
{
public:
MarketEvent(const std::string &symbol, double price, int64_t timestamp, int volume = 0)
: Event(EventType::MARKET), symbol_(symbol), price_(price),
timestamp_(timestamp), volume_(volume) {}
std::string getSymbol() const { return symbol_; }
double getPrice() const { return price_; }
int64_t getTimestamp() const { return timestamp_; }
int getVolume() const { return volume_; }
std::string toString() const override
{
return "MarketEvent: " + symbol_ + " @ " + std::to_string(price_) +
" Vol: " + std::to_string(volume_);
}
private:
std::string symbol_;
double price_;
int64_t timestamp_;
int volume_;
};
// Signal Event - generated by strategy
class SignalEvent : public Event
{
public:
SignalEvent(const std::string &symbol, OrderDirection direction,
double strength = 1.0, const std::string &strategy_id = "")
: Event(EventType::SIGNAL), symbol_(symbol), direction_(direction),
strength_(strength), strategy_id_(strategy_id) {}
std::string getSymbol() const { return symbol_; }
OrderDirection getDirection() const { return direction_; }
double getStrength() const { return strength_; }
std::string getStrategyId() const { return strategy_id_; }
std::string toString() const override
{
std::string dir = (direction_ == OrderDirection::BUY) ? "BUY" : "SELL";
return "SignalEvent: " + dir + " " + symbol_ + " Strength: " +
std::to_string(strength_);
}
private:
std::string symbol_;
OrderDirection direction_;
double strength_;
std::string strategy_id_;
};
// Order Event - generated by portfolio
class OrderEvent : public Event
{
public:
OrderEvent(const std::string &symbol, OrderType order_type,
int quantity, OrderDirection direction, double price = 0.0)
: Event(EventType::ORDER), symbol_(symbol), order_type_(order_type),
quantity_(quantity), direction_(direction), price_(price) {}
std::string getSymbol() const { return symbol_; }
OrderType getOrderType() const { return order_type_; }
int getQuantity() const { return quantity_; }
OrderDirection getDirection() const { return direction_; }
double getPrice() const { return price_; }
std::string toString() const override
{
std::string dir = (direction_ == OrderDirection::BUY) ? "BUY" : "SELL";
std::string type = (order_type_ == OrderType::MARKET) ? "MARKET" : "LIMIT";
return "OrderEvent: " + type + " " + dir + " " + std::to_string(quantity_) +
" " + symbol_ + " @ " + std::to_string(price_);
}
private:
std::string symbol_;
OrderType order_type_;
int quantity_;
OrderDirection direction_;
double price_;
};
// Fill Event - represents executed order
class FillEvent : public Event
{
public:
FillEvent(const std::string &symbol, int quantity, OrderDirection direction,
double fill_price, double commission = 0.0, int64_t timestamp = 0)
: Event(EventType::FILL), symbol_(symbol), quantity_(quantity),
direction_(direction), fill_price_(fill_price), commission_(commission),
timestamp_(timestamp) {}
std::string getSymbol() const { return symbol_; }
int getQuantity() const { return quantity_; }
OrderDirection getDirection() const { return direction_; }
double getFillPrice() const { return fill_price_; }
double getCommission() const { return commission_; }
int64_t getTimestamp() const { return timestamp_; }
std::string toString() const override
{
std::string dir = (direction_ == OrderDirection::BUY) ? "BUY" : "SELL";
return "FillEvent: " + dir + " " + std::to_string(quantity_) +
" " + symbol_ + " @ " + std::to_string(fill_price_);
}
private:
std::string symbol_;
int quantity_;
OrderDirection direction_;
double fill_price_;
double commission_;
int64_t timestamp_;
};
// Position class to track holdings
class Position
{
public:
Position(const std::string &symbol) : symbol_(symbol), quantity_(0), avg_price_(0.0) {}
void updatePosition(int quantity, double price)
{
if (quantity_ == 0)
{
quantity_ = quantity;
avg_price_ = price;
}
else
{
double total_cost = (quantity_ * avg_price_) + (quantity * price);
quantity_ += quantity;
if (quantity_ != 0)
{
avg_price_ = total_cost / quantity_;
}
}
}
std::string getSymbol() const { return symbol_; }
int getQuantity() const { return quantity_; }
double getAvgPrice() const { return avg_price_; }
double getMarketValue(double current_price) const
{
return quantity_ * current_price;
}
private:
std::string symbol_;
int quantity_;
double avg_price_;
};
// Abstract Strategy Base Class
class Strategy
{
public:
virtual ~Strategy() = default;
virtual void calculateSignals(const MarketEvent &market_event) = 0;
virtual std::string getName() const = 0;
protected:
std::function<void(std::shared_ptr<SignalEvent>)> signal_callback_;
public:
void setSignalCallback(std::function<void(std::shared_ptr<SignalEvent>)> callback)
{
signal_callback_ = callback;
}
};
// Example: Simple Moving Average Strategy
class SMAStrategy : public Strategy
{
public:
SMAStrategy(int window_size = 20) : window_size_(window_size) {}
void calculateSignals(const MarketEvent &market_event) override
{
std::string symbol = market_event.getSymbol();
double price = market_event.getPrice();
// Add price to history
price_history_[symbol].push_back(price);
auto &history = price_history_[symbol];
// Keep only the last window_size prices
if (history.size() > window_size_)
{
history.erase(history.begin());
}
// Generate signal if we have enough data
if (history.size() == window_size_)
{
double sma = 0.0;
for (double p : history)
{
sma += p;
}
sma /= window_size_;
// Simple signal: buy if price > SMA, sell if price < SMA
if (price > sma * 1.02)
{ // 2% buffer
auto signal = std::make_shared<SignalEvent>(symbol, OrderDirection::BUY, 1.0, "SMA");
if (signal_callback_)
signal_callback_(signal);
}
else if (price < sma * 0.98)
{ // 2% buffer
auto signal = std::make_shared<SignalEvent>(symbol, OrderDirection::SELL, 1.0, "SMA");
if (signal_callback_)
signal_callback_(signal);
}
}
}
std::string getName() const override { return "SMA_" + std::to_string(window_size_); }
private:
int window_size_;
std::unordered_map<std::string, std::vector<double>> price_history_;
};
// Portfolio Management
class Portfolio
{
public:
Portfolio(double initial_capital = 100000.0)
: initial_capital_(initial_capital), current_capital_(initial_capital) {}
void updateSignal(const SignalEvent &signal)
{
// Simple position sizing: use 10% of capital per trade
double position_size = current_capital_ * 0.1;
int quantity = static_cast<int>(position_size / getCurrentPrice(signal.getSymbol()));
if (quantity > 0)
{
auto order = std::make_shared<OrderEvent>(
signal.getSymbol(), OrderType::MARKET, quantity,
signal.getDirection());
if (order_callback_)
{
order_callback_(order);
}
}
}
void updateFill(const FillEvent &fill)
{
std::string symbol = fill.getSymbol();
// Update position
if (positions_.find(symbol) == positions_.end())
{
positions_[symbol] = std::make_unique<Position>(symbol);
}
int quantity = fill.getQuantity();
if (fill.getDirection() == OrderDirection::SELL)
{
quantity = -quantity;
}
positions_[symbol]->updatePosition(quantity, fill.getFillPrice());
// Update capital
double cost = fill.getQuantity() * fill.getFillPrice() + fill.getCommission();
if (fill.getDirection() == OrderDirection::BUY)
{
current_capital_ -= cost;
}
else
{
current_capital_ += cost;
}
std::cout << "Fill processed: " << fill.toString()
<< " | Capital: $" << current_capital_ << std::endl;
}
double getCurrentPrice(const std::string &symbol) const
{
auto it = current_prices_.find(symbol);
return (it != current_prices_.end()) ? it->second : 100.0; // Default price
}
void updatePrice(const std::string &symbol, double price)
{
current_prices_[symbol] = price;
}
double getTotalValue() const
{
double total = current_capital_;
for (const auto &pos : positions_)
{
if (pos.second->getQuantity() != 0)
{
double current_price = getCurrentPrice(pos.first);
total += pos.second->getMarketValue(current_price);
}
}
return total;
}
void setOrderCallback(std::function<void(std::shared_ptr<OrderEvent>)> callback)
{
order_callback_ = callback;
}
private:
double initial_capital_;
double current_capital_;
std::unordered_map<std::string, std::unique_ptr<Position>> positions_;
std::unordered_map<std::string, double> current_prices_;
std::function<void(std::shared_ptr<OrderEvent>)> order_callback_;
};
// Execution Handler - simulates order execution
class ExecutionHandler
{
public:
void executeOrder(const OrderEvent &order)
{
// Simulate market order execution with some slippage
double fill_price = getCurrentPrice(order.getSymbol());
double slippage = 0.001; // 0.1% slippage
if (order.getDirection() == OrderDirection::BUY)
{
fill_price *= (1.0 + slippage);
}
else
{
fill_price *= (1.0 - slippage);
}
double commission = calculateCommission(order);
auto fill = std::make_shared<FillEvent>(
order.getSymbol(), order.getQuantity(), order.getDirection(),
fill_price, commission);
if (fill_callback_)
{
fill_callback_(fill);
}
}
void updatePrice(const std::string &symbol, double price)
{
current_prices_[symbol] = price;
}
void setFillCallback(std::function<void(std::shared_ptr<FillEvent>)> callback)
{
fill_callback_ = callback;
}
private:
std::unordered_map<std::string, double> current_prices_;
std::function<void(std::shared_ptr<FillEvent>)> fill_callback_;
double getCurrentPrice(const std::string &symbol) const
{
auto it = current_prices_.find(symbol);
return (it != current_prices_.end()) ? it->second : 100.0;
}
double calculateCommission(const OrderEvent &order) const
{
// Simple commission: $1 per trade + 0.1% of trade value
double trade_value = order.getQuantity() * getCurrentPrice(order.getSymbol());
return 1.0 + (trade_value * 0.001);
}
};
// Main Backtesting Engine
class BacktestingEngine
{
public:
BacktestingEngine() : portfolio_(std::make_unique<Portfolio>()),
execution_handler_(std::make_unique<ExecutionHandler>())
{
setupCallbacks();
}
void addStrategy(std::unique_ptr<Strategy> strategy)
{
strategy->setSignalCallback([this](std::shared_ptr<SignalEvent> signal)
{ event_queue_.push(signal); });
strategies_.push_back(std::move(strategy));
}
void addMarketData(const std::string &symbol, double price, int64_t timestamp, int volume = 0)
{
auto market_event = std::make_shared<MarketEvent>(symbol, price, timestamp, volume);
event_queue_.push(market_event);
}
void run()
{
std::cout << "Starting backtest...\n"
<< std::endl;
while (!event_queue_.empty())
{
auto event = event_queue_.front();
event_queue_.pop();
processEvent(event);
}
std::cout << "\nBacktest completed!" << std::endl;
std::cout << "Final Portfolio Value: $" << portfolio_->getTotalValue() << std::endl;
}
private:
std::queue<std::shared_ptr<Event>> event_queue_;
std::vector<std::unique_ptr<Strategy>> strategies_;
std::unique_ptr<Portfolio> portfolio_;
std::unique_ptr<ExecutionHandler> execution_handler_;
void setupCallbacks()
{
portfolio_->setOrderCallback([this](std::shared_ptr<OrderEvent> order)
{ event_queue_.push(order); });
execution_handler_->setFillCallback([this](std::shared_ptr<FillEvent> fill)
{ event_queue_.push(fill); });
}
void processEvent(std::shared_ptr<Event> event)
{
switch (event->getType())
{
case EventType::MARKET:
{
auto market_event = std::static_pointer_cast<MarketEvent>(event);
handleMarketEvent(*market_event);
break;
}
case EventType::SIGNAL:
{
auto signal_event = std::static_pointer_cast<SignalEvent>(event);
handleSignalEvent(*signal_event);
break;
}
case EventType::ORDER:
{
auto order_event = std::static_pointer_cast<OrderEvent>(event);
handleOrderEvent(*order_event);
break;
}
case EventType::FILL:
{
auto fill_event = std::static_pointer_cast<FillEvent>(event);
handleFillEvent(*fill_event);
break;
}
}
}
void handleMarketEvent(const MarketEvent &event)
{
std::cout << event.toString() << std::endl;
// Update prices in portfolio and execution handler
portfolio_->updatePrice(event.getSymbol(), event.getPrice());
execution_handler_->updatePrice(event.getSymbol(), event.getPrice());
// Send to all strategies
for (auto &strategy : strategies_)
{
strategy->calculateSignals(event);
}
}
void handleSignalEvent(const SignalEvent &event)
{
std::cout << " -> " << event.toString() << std::endl;
portfolio_->updateSignal(event);
}
void handleOrderEvent(const OrderEvent &event)
{
std::cout << " -> " << event.toString() << std::endl;
execution_handler_->executeOrder(event);
}
void handleFillEvent(const FillEvent &event)
{
std::cout << " -> " << event.toString() << std::endl;
portfolio_->updateFill(event);
}
};
// Example usage
int main()
{
// Create backtesting engine
BacktestingEngine engine;
// Add SMA strategy
auto sma_strategy = std::make_unique<SMAStrategy>(10);
engine.addStrategy(std::move(sma_strategy));
// Simulate market data - simple price series
std::vector<double> prices = {
100, 101, 99, 102, 105, 103, 106, 108, 107, 110,
112, 109, 111, 115, 118, 116, 119, 121, 118, 122,
125, 123, 126, 129, 127, 130, 132, 129, 135, 138};
int64_t timestamp = 1640995200; // Starting timestamp
for (size_t i = 0; i < prices.size(); ++i)
{
engine.addMarketData("AAPL", prices[i], timestamp + i * 86400, 1000);
}
// Run backtest
engine.run();
return 0;
}