This repository has been archived by the owner on Feb 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
darwin.js
executable file
·527 lines (434 loc) · 20.1 KB
/
darwin.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
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
#!/usr/bin/env node
/* Zenbot 4 Genetic Backtester
* Clifford Roche <clifford.roche@gmail.com>
* 07/01/2017
*
* Example: ./darwin.js --selector="bitfinex.ETH-USD" --days="10" --currency_capital="5000" --use_strategies="all | macd,trend_ema,etc" --population="101" --population_data="simulations/generation_data_NUMBERS"
* Params:
* --use_strategies=<stragegy_name>,<stragegy_name>,<stragegy_name> Min one strategy, can include more than one
* --population_data=<filename> filename used for continueing backtesting from previous run
* --generateLaunch=<true>|<false> will generate .sh and .bat file using the best generation discovered
* --ignoreLaunchFitness=<true>|<false> if used with --generateLaunch it will always write a new launch file regardless if latest fitness is greater
* --floatScanWindow Time window used for analyzing data be adjusted every generation
* --population=<int> populate per strategy
* --maxCores=<int> maximum processes to execute at a time default is # of cpu cores in system
* --selector=<exchange.marketPair>
* --asset_capital=<float> amount coin to start sim with
* --currency_capital=<float> amount of capital/base currency to start sim with
* --days=<int> amount of days to use when backfilling
* --noStatSave=<true>|<false> true:no statistics are saved to the simulation folder
* --silent=<true>|<false> true:can improve performance
* --runGenerations=<int> if used run this number of generations, will be shown 1 less due to generations starts at 0
* --minTrades=<int> Minimum wins before generation is considured fit to evolve
* --fitnessCalcType=<wl / profit / classic / profitwl> Default: Classic. wl will score the highes for wins and losses, profit doesn't care about wins and losses only the higest end balance, classic uses original claculation / profitwl tries to get the highest profit using the lowest win/loss ratio
*
*
* any parameters for sim and or strategy can be passed in and will override the genetic test generated parameter
* i.e. if --period_length=1m is passed all test will be performed using --period_length=1m instead of trying to find that parameter
*
*/
let parallel = require('run-parallel-limit')
let json2csv = require('json2csv')
let fs = require('fs')
let GeneticAlgorithmCtor = require('geneticalgorithm')
let moment = require('moment')
let path = require('path')
// eslint-disable-next-line no-unused-vars
let colors = require('colors')
let Phenotypes = require('../../lib/phenotype')
let Backtester = require('../../lib/backtester')
let argv = require('yargs').argv
let z = require('zero-fill')
let n = require('numbro')
let VERSION = 'Zenbot 4 Genetic Backtester v0.2.3'
let PARALLEL_LIMIT = (process.env.PARALLEL_LIMIT && +process.env.PARALLEL_LIMIT) || require('os').cpus().length
let iterationCount = 0
let selectedStrategies
let pools = {}
let simArgs
let populationSize = 0
let generationCount = 1
let runGenerations = undefined
let generationProcessing = false
let population_data = ''
let noStatSave = false
//let floatScanWindow = false
let ignoreLaunchFitness = false
let minimumTrades = 0
let fitnessCalcType = 'classic'
let readSimDataFile = (iteration) => {
let jsonFileName = `simulations/${population_data}/gen_${generationCount}/sim_${iteration}.json`
if (fs.existsSync(jsonFileName)) {
let simData = JSON.parse(fs.readFileSync(jsonFileName, { encoding: 'utf8' }))
return simData
}
else {
return null
}
}
let writeSimDataFile = (iteration, data) => {
let jsonFileName = `simulations/${population_data}/gen_${generationCount}/sim_${iteration}.json`
Backtester.writeFileAndFolder(jsonFileName, data)
}
function allStrategyNames() {
let pathName = path.resolve(__dirname, '..', '..', 'extensions', 'strategies')
return fs.readdirSync(pathName).filter(function (file) {
return fs.statSync(pathName + '/' + file).isDirectory()
})
}
function isUsefulKey(key) {
if (key == 'filename' || key == 'show_options' || key == 'sim') return false
return true
}
function generateCommandParams(input) {
if (!isUndefined(input) && !isUndefined(input.params)) {
input = input.params.replace('module.exports =', '')
}
input = JSON.parse(input)
var result = ''
var keys = Object.keys(input)
for (let i = 0; i < keys.length; i++) {
var key = keys[i]
if (isUsefulKey(key)) {
// selector should be at start before keys
if (key == 'selector') {
result = input[key] + result
}
else result += ' --' + key + '=' + input[key]
}
}
return result
}
function saveGenerationData(csvFileName, jsonFileName, dataCSV, dataJSON) {
try {
fs.writeFileSync(csvFileName, dataCSV)
console.log('> Finished writing generation csv to ' + csvFileName)
}
catch (err) {
throw err
}
try {
fs.writeFileSync(jsonFileName, dataJSON)
console.log('> Finished writing generation json to ' + jsonFileName)
}
catch (err) {
throw err
}
}
// Find the first incomplete generation of this session, where incomplete means no "results" files
while (fs.existsSync(`simulations/${population_data}/gen_${generationCount}`)) {
generationCount++
}
generationCount--
if (generationCount > 0 && !fs.existsSync(`simulations/${population_data}/gen_${generationCount}/results.csv`)) {
generationCount--
}
function saveLaunchFiles(saveLauchFile, configuration) {
if (!saveLauchFile) return
//let lConfiguration = configuration.replace(' sim ', ' trade ')
let lFilenameNix = new String().concat('./gen.', configuration.selector.toLowerCase(), '.sh')
let lFinenamewin32 = new String().concat('./gen.', configuration.selector.toLowerCase(), '.bat')
delete configuration.generateLaunch
delete configuration.backtester_generation
let bestOverallCommand = generateCommandParams(configuration)
let lastFitnessLevel = -9999.0
// get prior fitness level nix
if (fs.existsSync(lFilenameNix)) {
let lFileCont = fs.readFileSync(lFilenameNix, { encoding: 'utf8', flag: 'r' })
let lines = lFileCont.split('\n')
if (lines.length > 2)
if (lines[1].includes('fitness=')) {
let th = lines[1].split('=')
lastFitnessLevel = th[1]
}
}
// get prior firness level win32
if (fs.existsSync(lFinenamewin32)) {
let lFileCont = fs.readFileSync(lFinenamewin32, { encoding: 'utf8', flag: 'r' })
let lines = lFileCont.split('\n')
if (lines.length > 1)
if (lines[1].includes('fitness=')) {
let th = lines[1].split('=')
lastFitnessLevel = th[1]
}
}
//write Nix Version
let lNixContents = '#!/bin/bash\n'.concat('#fitness=', configuration.fitness, '\n',
'env node zenbot.js trade ',
bestOverallCommand, ' $@\n')
let lWin32Contents = '@echo off\n'.concat('rem fitness=', configuration.fitness, '\n',
'node zenbot.js trade ',
bestOverallCommand, ' %*\n')
if (((Number(configuration.fitness) > Number(lastFitnessLevel)) || (ignoreLaunchFitness)) && Number(configuration.fitness) > 0.0) {
fs.writeFileSync(lFilenameNix, lNixContents)
fs.writeFileSync(lFinenamewin32, lWin32Contents)
// using the string instead of octet as eslint compaines about an invalid number if the number starts with 0
fs.chmodSync(lFilenameNix, '777')
fs.chmodSync(lFinenamewin32, '777')
}
}
let cycleCount = -1
function isUndefined(variable) {
return typeof variable === typeof undefined
}
function simulateGeneration(generateLaunchFile) {
generationProcessing = true
// Find the first incomplete generation of this session, where incomplete means no "results" files
while (fs.existsSync(`simulations/${population_data}/gen_${generationCount}`)) {
generationCount++
}
generationCount--
if (generationCount > 0 && !fs.existsSync(`simulations/${population_data}/gen_${generationCount}/results.csv`)) {
generationCount--
}
if (noStatSave) {
cycleCount++
generationCount = cycleCount
}
let ofGenerations = (!isUndefined(runGenerations)) ? `of ${runGenerations}` : ''
console.log(`\n\n=== Simulating generation ${++generationCount} ${ofGenerations} ===\n`)
Backtester.resetMonitor()
Backtester.ensureBackfill()
iterationCount = 0
let tasks = selectedStrategies.map(v => pools[v]['pool'].population().map(phenotype => {
return cb => {
phenotype.backtester_generation = iterationCount
phenotype.exchangeMarketPair = argv.selector
Backtester.trackPhenotype(phenotype)
var command
let simData = readSimDataFile(iterationCount)
if (simData) {
if (simData.result) {
// Found a complete and cached sim, don't run anything, just forward the results of it
phenotype['sim'] = simData.result
iterationCount++
return cb(null, simData.result)
}
else {
command = {
iteration: iterationCount,
commandString: simData.commandString,
queryStart: moment(simData.queryStart),
queryEnd: moment(simData.queryEnd)
}
}
}
if (!command) {
// Default flow, build the command to run, and cache it so there's no need to duplicate work when resuming
command = Backtester.buildCommand(v, phenotype, `simulations/${population_data}/gen_${generationCount}/sim_${iterationCount}_result.html`)
command.iteration = iterationCount
writeSimDataFile(iterationCount, JSON.stringify(command))
}
iterationCount++
phenotype.minTrades = minimumTrades
phenotype.fitnessCalcType = fitnessCalcType
Backtester.runCommand(v, phenotype, command, cb)
}
})).reduce((a, b) => a.concat(b))
Backtester.startMonitor()
parallel(tasks, PARALLEL_LIMIT, (err, results) => {
Backtester.stopMonitor(`Generation ${generationCount}`)
results = results.filter(function (r) {
return !!r
})
results.sort((a, b) => (Number(a.fitness) < Number(b.fitness)) ? 1 : ((Number(b.fitness) < Number(a.fitness)) ? -1 : 0))
let fieldsGeneral = ['selector.normalized', 'fitness', 'vsBuyHold', 'wlRatio', 'frequency', 'strategy', 'order_type', 'endBalance', 'buyHold', 'wins', 'losses', 'period_length', 'min_periods', 'days', 'params']
let fieldNamesGeneral = ['Selector', 'Fitness', 'VS Buy Hold (%)', 'Win/Loss Ratio', '# Trades/Day', 'Strategy', 'Order Type', 'Ending Balance ($)', 'Buy Hold ($)', '# Wins', '# Losses', 'Period', 'Min Periods', '# Days', 'Full Parameters']
let dataCSV = json2csv({
data: results,
fields: fieldsGeneral,
fieldNames: fieldNamesGeneral
})
let csvFileName = `simulations/${population_data}/gen_${generationCount}/results.csv`
let poolData = {}
selectedStrategies.forEach(function (v) {
poolData[v] = pools[v]['pool'].population()
})
let jsonFileName = `simulations/${population_data}/gen_${generationCount}/results.json`
let dataJSON = JSON.stringify(poolData, null, 2)
if (!noStatSave)
saveGenerationData(csvFileName, jsonFileName, dataCSV, dataJSON)
//Display best of the generation
console.log('\n\nGeneration\'s Best Results')
let bestOverallResult = []
let prefix = './zenbot.sh sim '
selectedStrategies.forEach((v) => {
let best = pools[v]['pool'].best()
let bestCommand
if (best.sim) {
console.log(`(${best.sim.strategy}) Sim Fitness ${best.sim.fitness}, VS Buy and Hold: ${z(5, (n(best.sim.vsBuyHold).format('0.0') + '%'), ' ').yellow} BuyAndHold Balance: ${z(5, (n(best.sim.buyHold).format('0.000000')), ' ').yellow} End Balance: ${z(5, (n(best.sim.endBalance).format('0.000000')), ' ').yellow}, Wins/Losses ${best.sim.wins}/${best.sim.losses}, ROI ${z(5, (n(best.sim.roi).format('0.000000')), ' ').yellow}.`)
bestCommand = generateCommandParams(best.sim)
bestOverallResult.push(best.sim)
} else {
console.log(`(${results[0].strategy}) Result Fitness ${results[0].fitness}, VS Buy and Hold: ${z(5, (n(results[0].vsBuyHold).format('0.0') + '%'), ' ').yellow} BuyAndHold Balance: ${z(5, (n(results[0].buyHold).format('0.000000')), ' ').yellow} End Balance: ${z(5, (n(results[0].endBalance).format('0.000000')), ' ').yellow}, Wins/Losses ${results[0].wins}/${results[0].losses}, ROI ${z(5, (n(results.roi).format('0.000000')), ' ').yellow}.`)
bestCommand = generateCommandParams(results[0])
bestOverallResult.push(results[0])
}
// prepare command snippet from top result for this strat
if (bestCommand != '') {
bestCommand = prefix + bestCommand
bestCommand = bestCommand + ' --asset_capital=' + argv.asset_capital + ' --currency_capital=' + argv.currency_capital
console.log(bestCommand + '\n')
}
})
bestOverallResult.sort((a, b) =>
(isUndefined(a.fitness)) ? 1 :
(isUndefined(b.fitness)) ? 0 :
(a.fitness < b.fitness) ? 1 :
(b.fitness < a.fitness) ? -1 : 0)
// let bestOverallCommand = generateCommandParams(bestOverallResult[0])
// bestOverallCommand = prefix + bestOverallCommand
// bestOverallCommand = bestOverallCommand + ' --asset_capital=' + argv.asset_capital + ' --currency_capital=' + argv.currency_capital
saveLaunchFiles(generateLaunchFile, bestOverallResult[0])
if (selectedStrategies.length > 1) {
console.log(`(${bestOverallResult[0].strategy}) Best Overall Fitness ${bestOverallResult[0].fitness}, VS Buy and Hold: ${z(5, (n(bestOverallResult[0].vsBuyHold).format('0.00') + '%'), ' ').yellow} BuyAndHold Balance: ${z(5, (n(bestOverallResult[0].buyHold).format('0.000000')), ' ').yellow} End Balance: ${z(5, (n(bestOverallResult[0].endBalance).format('0.000000')), ' ').yellow}, Wins/Losses ${bestOverallResult[0].wins}/${bestOverallResult[0].losses}, ROI ${z(5, (n(bestOverallResult[0].roi).format('0.000000')), ' ').yellow}.`)
}
selectedStrategies.forEach((v) => {
pools[v]['pool'] = pools[v]['pool'].evolve()
})
if (!isUndefined(runGenerations) && runGenerations <= generationCount) {
process.exit()
}
generationProcessing = false
})
}
console.log(`\n--==${VERSION}==--`)
console.log(new Date().toUTCString() + '\n')
simArgs = Object.assign({}, argv)
if (!simArgs.selector) {
simArgs.selector = 'bitfinex.ETH-USD'
}
if (!simArgs.filename) {
simArgs.filename = 'none'
}
if (simArgs.help || !(simArgs.use_strategies)) {
console.log('--use_strategies=<stragegy_name>,<stragegy_name>,<stragegy_name> Min one strategy, can include more than one')
console.log('--population_data=<filename> filename used for continueing backtesting from previous run')
console.log('--generateLaunch=<true>|<false> will generate .sh and .bat file using the best generation discovered')
console.log('--population=<int> populate per strategy')
console.log('--maxCores=<int> maximum processes to execute at a time default is # of cpu cores in system')
console.log('--selector=<exchange.marketPair> ')
console.log('--asset_capital=<float> amount coin to start sim with ')
console.log('--currency_capital=<float> amount of capital/base currency to start sim with')
console.log('--days=<int> amount of days to use when backfilling')
console.log('--noStatSave=<true>|<false>')
console.log('--runGenerations=<int> if used run this number of generations, will be shown 1 less due to generations starts at 0')
console.log('--minTrades=<int> Minimum wins before generation is considured fit to evolve')
console.log('--fitnessCalcType=<wl / profit / classic / profitwl> Default: Classic.')
console.log(' wl will score the highes for wins and losses, profit does not care about wins and losses only the higest end balance,')
console.log(' classic uses original claculation / profitwl tries to get the highest profit using the lowest win/loss ratio')
process.exit(0)
}
delete simArgs.use_strategies
delete simArgs.population_data
delete simArgs.population
delete simArgs['$0'] // This comes in to argv all by itself
delete simArgs['_'] // This comes in to argv all by itself
if (simArgs.maxCores) {
if (simArgs.maxCores < 1) PARALLEL_LIMIT = 1
else PARALLEL_LIMIT = simArgs.maxCores
}
fitnessCalcType = 'classic'
if (simArgs.fitnessCalcType) {
if (simArgs.fitnessCalcType == 'classic') fitnessCalcType = 'classic'
if (simArgs.fitnessCalcType == 'wl') fitnessCalcType = 'wl'
if (simArgs.fitnessCalcType == 'profit') fitnessCalcType = 'profit'
if (simArgs.fitnessCalcType == 'profitwl') fitnessCalcType = 'profitwl'
}
if (!isUndefined(simArgs.runGenerations)) {
if (simArgs.runGenerations) {
runGenerations = simArgs.runGenerations - 1
}
}
let generateLaunchFile = (simArgs.generateLaunch) ? true : false
noStatSave = (simArgs.noStatSave) ? true : false
let strategyName = (argv.use_strategies) ? argv.use_strategies : 'all'
populationSize = (argv.population) ? argv.population : 100
minimumTrades = (argv.minTrades) ? argv.minTrades : 0
//floatScanWindow = (argv.floatScanWindow) ? argv.floatScanWindow : false
ignoreLaunchFitness = (argv.ignoreLaunchFitness) ? argv.ignoreLaunchFitness : false
population_data = argv.population_data || `backtest.${simArgs.selector.toLowerCase()}.${moment().format('YYYYMMDDHHmmss')}`
console.log(`Backtesting strategy ${strategyName} ...\n`)
console.log(`Creating population of ${populationSize} ...\n`)
selectedStrategies = (strategyName === 'all') ? allStrategyNames() : strategyName.split(',')
Backtester.deLint()
for (var i = 0; i < selectedStrategies.length; i++) {
let v = selectedStrategies[i]
let strategyPool = pools[v] = {}
let strategyData = require(path.resolve(__dirname, `../../extensions/strategies/${v}/strategy`))
let strategyPhenotypes = strategyData.phenotypes
if (strategyPhenotypes) {
let evolve = true
let population = []
for (var i2 = population.length; i2 < populationSize; ++i2) {
var lPheno = Phenotypes.create(strategyPhenotypes)
population.push(lPheno)
evolve = false
}
strategyPool['config'] = {
mutationFunction: function (phenotype) {
return Phenotypes.mutation(phenotype, strategyPhenotypes)
},
crossoverFunction: function (phenotypeA, phenotypeB) {
return Phenotypes.crossover(phenotypeA, phenotypeB, strategyPhenotypes)
},
fitnessFunction: Phenotypes.fitness,
doesABeatBFunction: Phenotypes.competition,
population: population,
populationSize: populationSize
}
strategyPool['pool'] = GeneticAlgorithmCtor(strategyPool.config)
if (evolve) {
strategyPool['pool'].evolve()
}
}
else {
if (strategyName === 'all') {
// skip it, probably just something like forex_analytics
selectedStrategies.splice(i, 1)
i--
}
else {
console.log(`No phenotypes definition found for strategy ${v}`)
process.exit(1)
}
}
}
// BEGIN - exitHandler
var exitHandler = function (options, exitErr) {
if (generationCount && options.cleanup && (isUndefined(runGenerations) || runGenerations !== generationCount)) {
console.log('Resume this backtest later with:')
var darwin_args = process.argv.slice(2, process.argv.length)
var hasPopData = false
var popDataArg = `--population_data=${population_data}`
darwin_args.forEach(function (arg) {
if (arg === popDataArg) {
hasPopData = true
}
})
if (!hasPopData) {
darwin_args.push(popDataArg)
}
console.log(`./scripts/genetic_backtester/darwin.js ${darwin_args.join(' ')}`)
}
if (exitErr) console.log(exitErr.stack || exitErr)
if (options.exit) process.exit()
}
process.on('exit', exitHandler.bind(null, { cleanup: true }))
//catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, { exit: true }))
// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', exitHandler.bind(null, { exit: true }))
process.on('SIGUSR2', exitHandler.bind(null, { exit: true }))
//catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, { exit: true }))
// END - exitHandler
Backtester.init({
simArgs: simArgs,
simTotalCount: populationSize * selectedStrategies.length,
parallelLimit: PARALLEL_LIMIT,
writeFile: writeSimDataFile
})
setInterval(() => {
if (generationProcessing == false) simulateGeneration(generateLaunchFile)
}, 1000)