-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathgulpfile.js
409 lines (332 loc) · 14.3 KB
/
gulpfile.js
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
var gulp = require('gulp');
var gutil = require('gulp-util');
var argv = require('yargs').argv;
var path = require('path');
var _ = require('lodash');
var async = require('async');
var slice = require('sliced');
var garbageCollectionTimeout = null;
function scheduleGarbageCollection() {
if (!global.gc) {
return;
}
garbageCollectionTimeout = setTimeout(function() {
// Allow the timeout to be garbage collected.
garbageCollectionTimeout = null;
// Collect garbage.
global.gc();
// Re-schedule garbage collection.
scheduleGarbageCollection();
}, 1 * 60 * 1000);
}
// Replace slice() with a more efficient version.
Array.prototype.slice = function(begin, end) {
return slice(this, begin, end);
};
scheduleGarbageCollection();
gulp.task('backtest', function(done) {
function showUsageInfo() {
console.log('Example usage:\n');
console.log('gulp backtest --symbol AUDJPY --parser metatrader --data ./data/metatrader/three-year/AUDJPY.csv --optimizer Reversals --investment 1000 --profitability 0.7 --database forex-backtesting\n');
}
function handleInputError(message) {
gutil.log(gutil.colors.red(message));
showUsageInfo();
process.exit(1);
}
var db = require('./db');
var dataParsers = require('./src/dataParsers');
var optimizers = require('./src/optimizers');
var optimizerFn;
var dataParser;
var investment = 0.0;
var profitability = 0.0;
// Find the symbol based on the command line argument.
if (!argv.symbol) {
handleInputError('No symbol provided');
}
// Find the raw data parser based on command line argument.
dataParser = dataParsers[argv.parser]
if (!dataParser) {
handleInputError('Invalid data parser');
}
// Find the strategy based on the command line argument.
optimizerFn = optimizers[argv.optimizer]
if (!optimizerFn) {
handleInputError('Invalid strategy optimizer');
}
investment = parseFloat(argv.investment)
if (!investment) {
handleInputError('Invalid investment');
}
profitability = parseFloat(argv.profitability)
if (!profitability) {
handleInputError('No profitability provided');
}
if (!argv.database) {
handleInputError('No database provided');
}
// Set up database connection.
db.initialize(argv.database);
try {
// Parse the raw data file.
dataParser.parse(argv.data).then(function(parsedData) {
// Prepare the strategy.
var optimizer = new optimizerFn(argv.symbol);
// Backtest the strategy against the parsed data.
optimizer.optimize(parsedData, investment, profitability, function() {
db.disconnect();
done();
});
});
}
catch (error) {
console.error(error.message || error);
process.exit(1);
}
});
gulp.task('forwardtest', function(done) {
function showUsageInfo() {
console.log('Example usage:\n');
console.log('gulp forwardtest --symbol AUDJPY --parser ctoption --data ./data/ctoption/AUDJPY.csv --investment 1000 --profitability 0.7 --database forex-backtesting\n');
}
function handleInputError(message) {
gutil.log(gutil.colors.red(message));
showUsageInfo();
process.exit(1);
}
var db = require('./db');
var dataParsers = require('./src/dataParsers');
var Backtest = require('./src/models/Backtest');
var Forwardtest = require('./src/models/Forwardtest');
var optimizerFn = require('./src/optimizers/Reversals');
var strategyFn = require('./src/strategies/combined/Reversals');
var dataParser;
var investment = 0.0;
var profitability = 0.0;
var backtestConstraints = {
symbol: argv.symbol,
//strategyName: argv.strategy,
minimumProfitLoss: {'$gte': -20000},
maximumConsecutiveLosses: {'$lte': 10},
winRate: {'$gte': 0.62},
tradeCount: {'$gte': 1000},
};
// Find the symbol based on the command line argument.
if (!argv.symbol) {
handleInputError('No symbol provided');
}
// Find the raw data parser based on command line argument.
dataParser = dataParsers[argv.parser]
if (!dataParser) {
handleInputError('Invalid data parser');
}
investment = parseFloat(argv.investment)
if (!investment) {
handleInputError('Invalid investment');
}
profitability = parseFloat(argv.profitability)
if (!profitability) {
handleInputError('No profitability provided');
}
// Find the data file based on the command line argument.
if (!argv.data) {
handleInputError('No data file provided');
}
if (!argv.database) {
handleInputError('No database provided');
}
// Set up database connection.
db.initialize(argv.database);
try {
dataParser.parse(argv.data).then(function(parsedData) {
var studyDefinitions = optimizerFn.studyDefinitions;
var studies = [];
var cumulativeData = [];
var previousDataPoint = null;
var dataCount = parsedData.length;
process.stdout.write('Preparing study data...');
// Prepare studies.
studyDefinitions.forEach(function(studyDefinition) {
// Instantiate the study, and add it to the list of studies for this strategy.
studies.push(new studyDefinition.study(studyDefinition.inputs, studyDefinition.outputMap));
});
// Parepare study data.
parsedData.forEach(function(dataPoint, index) {
// If there is a significant gap, start over.
if (previousDataPoint && (dataPoint.timestamp - previousDataPoint.timestamp) > 600000) {
cumulativeData = [];
}
// Add the data point to the cumulative data.
cumulativeData.push(dataPoint);
// Iterate over each study...
studies.forEach(function(study) {
var studyProperty = '';
var studyTickValues = {};
var studyOutputs = study.getOutputMappings();
// Update the data for the study.
study.setData(cumulativeData);
studyTickValues = study.tick();
// Augment the last data point with the data the study generates.
for (studyProperty in studyOutputs) {
if (studyTickValues && typeof studyTickValues[studyOutputs[studyProperty]] === 'number') {
dataPoint[studyOutputs[studyProperty]] = studyTickValues[studyOutputs[studyProperty]];
}
else {
dataPoint[studyOutputs[studyProperty]] = '';
}
}
// Ensure memory is freed.
studyTickValues = null;
});
previousDataPoint = dataPoint;
process.stdout.cursorTo(23);
process.stdout.write(index + ' of ' + dataCount + ' completed');
});
process.stdout.cursorTo(23);
process.stdout.write(dataCount + ' of ' + dataCount + ' completed\n');
Backtest.find(backtestConstraints, function(error, backtests) {
var backtestCount = backtests.length;
var backtestTasks = [];
// Iterate through the remaining backtests.
process.stdout.write('Forward testing...\n');
backtests.forEach(function(backtest, index) {
backtestTasks.push(function(taskCallback) {
// Set up a new strategy instance.
var strategy = new strategyFn(argv.symbol, [backtest.configuration]);
strategy.setProfitLoss(10000);
// Backtest (forward test).
var results = strategy.backtest(parsedData, investment, profitability);
// Save results.
Forwardtest.create(_.extend(results, {
symbol: argv.symbol,
strategyUuid: backtest.strategyUuid,
configuration: backtest.configuration
}), function() {
process.stdout.cursorTo(18);
process.stdout.write(index + ' of ' + backtestCount + ' completed');
// Forward test the next backtest.
taskCallback();
});
});
});
async.series(backtestTasks, function(error) {
process.stdout.cursorTo(18);
process.stdout.write(backtestCount + ' of ' + backtestCount + ' completed\n');
db.disconnect();
done();
});
});
});
}
catch (error) {
cosole.error(error.message || error);
process.exit(1);
}
});
// gulp.task('combine', function(done) {
// function showUsageInfo() {
// console.log('Example usage:\n');
// console.log('gulp combine --symbol AUDJPY --strategy Reversals --investment 1000 --profitability 0.7 --database forex-backtesting\n');
// }
// function handleInputError(message) {
// gutil.log(gutil.colors.red(message));
// showUsageInfo();
// process.exit(1);
// }
// var db = require('./db');
// var Forwardtest = require('./src/models/Forwardtest');
// var Position = require('./src/models/Position');
// var Combination = require('./src/models/Combination');
// var positionTester = require('./src/positionTester');
// var profitability = 0.0;
// var forwardtestConstraints = {
// symbol: argv.symbol,
// //strategyName: argv.strategy,
// minimumProfitLoss: {'$gte': 0},
// maximumConsecutiveLosses: {'$lte': 5},
// winRate: {'$gte': 0.62},
// tradeCount: {'$gte': 75},
// };
// // Find the symbol based on the command line argument.
// if (!argv.symbol) {
// handleInputError('No symbol provided');
// }
// // Find the strategy based on the command line argument.
// if (!argv.strategy) {
// handleInputError('Invalid strategy');
// }
// investment = parseFloat(argv.investment)
// if (!investment) {
// handleInputError('Invalid investment');
// }
// profitability = parseFloat(argv.profitability)
// if (!profitability) {
// handleInputError('No profitability provided');
// }
// if (!argv.database) {
// handleInputError('No database provided');
// }
// // Set up database connection.
// db.initialize(argv.database);
// // Find all forward tests for the symbol.
// Forwardtest.find(forwardtestConstraints, function(error, forwardtests) {
// // Sort forward tests descending by profitLoss.
// forwardtests = _.sortBy(forwardtests, 'winRate').reverse();
// // Use the highest profit/loss figure as the benchmark.
// var benchmarkProfitLoss = 0;
// var optimalConfigurations = [];
// var optimalPositions = [];
// var percentage = 0.0;
// var forwardtestCount = forwardtests.length;
// var tasks = [];
// // Iterate through the remaining forward tests.
// process.stdout.write('Combining configurations...');
// forwardtests.forEach(function(forwardtest, index) {
// tasks.push(function(taskCallback) {
// process.stdout.cursorTo(27);
// process.stdout.write(index + ' of ' + forwardtestCount + ' completed (' + optimalConfigurations.length + ' / $' + benchmarkProfitLoss + ')');
// // Find all positions for each forward test.
// Position.find({strategyUuid: forwardtest.strategyUuid}, function(error, positions) {
// // Test with the optimal positions combined with the current positions.
// var testPositions = optimalPositions.concat(positions);
// // Get the unique set of trades.
// var testPositions = _.uniq(testPositions, function(position) {
// return position.timestamp;
// });
// // Sort positions by timestamp.
// testPositions = _.sortBy(testPositions, 'timestamp');
// // Determine if all the trades combined results in an improvement.
// var testResults = positionTester.test(testPositions);
// // See if the test resulted in an improvement.
// if (testResults.profitLoss >= benchmarkProfitLoss + 1000 && testResults.winRate >= 0.62 && testResults.tradeCount >= 3000 && testResults.maximumConsecutiveLosses <= 20 && testResults.minimumProfitLoss >= -20000) {
// // Use the positions in future tests.
// optimalPositions = testPositions;
// // Include the forward test configuration in the list of optimal configurations.
// optimalConfigurations.push(forwardtest.configuration);
// // Update the benchmark.
// benchmarkProfitLoss = testResults.profitLoss;
// }
// taskCallback(error);
// });
// });
// });
// // Execute the tasks, in order.
// async.series(tasks, function(error) {
// var optimalResults = positionTester.test(optimalPositions);
// // Save the results.
// Combination.create({
// symbol: argv.symbol,
// strategyName: argv.strategy,
// results: optimalResults,
// configurations: optimalConfigurations,
// positions: optimalPositions
// }, function() {
// process.stdout.cursorTo(27);
// process.stdout.write(forwardtestCount + ' of ' + forwardtestCount + ' completed\n');
// done();
// process.exit();
// });
// });
// });
// });