-
Notifications
You must be signed in to change notification settings - Fork 39
/
fx-data-generate.py
executable file
·387 lines (357 loc) · 11.5 KB
/
fx-data-generate.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Script to generate backtest data in CSV format.
# Example usage:
# ./gen_bt_data.py -s 10 -p random -v 100 2018.01.01 2018.01.30 2.0 4.0 | gnuplot -p -e "set datafile separator ','; plot '-' using 3 w l"
import argparse
import sys
import datetime
import csv
import random
from math import ceil, exp, pi, sin
def error(message, exit=True):
print("[ERROR]", message)
if exit:
sys.exit(1)
def volumesFromTimestamp(timestamp, spread):
longTimestamp = timestamp.timestamp()
spread *= 1e5
d = int(str(int(longTimestamp / 60))[-3:]) + 1
bidVolume = int((longTimestamp / d) % (1e3 - spread))
return (bidVolume, bidVolume + spread)
def linearModel(startDate, endDate, startPrice, endPrice, deltaTime, spread):
timestamp = startDate
bidPrice = startPrice
askPrice = bidPrice + spread
bidVolume = 1
askVolume = bidVolume + spread
deltaPrice = (
deltaTime
/ (endDate + datetime.timedelta(days=1) - startDate - deltaTime)
* (endPrice - startPrice)
)
ticks = []
while timestamp < (endDate + datetime.timedelta(days=1)):
ticks += [
{
"timestamp": timestamp,
"bidPrice": bidPrice,
"askPrice": askPrice,
"bidVolume": bidVolume,
"askVolume": askVolume,
}
]
timestamp += deltaTime
bidPrice += deltaPrice
askPrice += deltaPrice
(bidVolume, askVolume) = volumesFromTimestamp(timestamp, spread)
return ticks
def zigzagModel(
startDate, endDate, startPrice, endPrice, deltaTime, spread, volatility
):
timestamp = startDate
bidPrice = startPrice
askPrice = bidPrice + spread
bidVolume = 1
askVolume = bidVolume + spread
deltaPrice = endPrice - startPrice
count = ceil((endDate + datetime.timedelta(days=1) - startDate) / deltaTime)
lift = deltaPrice / count
forward = 500
backward = int(volatility * 50)
ticks = []
# Calculate zigzag body
for i in range(0, count - backward):
ticks += [
{
"timestamp": timestamp,
"bidPrice": bidPrice,
"askPrice": askPrice,
"bidVolume": bidVolume,
"askVolume": askVolume,
}
]
i += 1
timestamp += deltaTime
if i % (forward + backward) < forward:
bidPrice += (forward + 2 * backward) / forward * lift
else:
bidPrice -= lift
askPrice = bidPrice + spread
(bidVolume, askVolume) = volumesFromTimestamp(timestamp, spread)
# Calculate tail as a linear line
lift = (endPrice - bidPrice) / (backward - 1)
for i in range(count - backward, count):
ticks += [
{
"timestamp": timestamp,
"bidPrice": bidPrice,
"askPrice": askPrice,
"bidVolume": bidVolume,
"askVolume": askVolume,
}
]
i += 1
timestamp += deltaTime
bidPrice += lift
askPrice = bidPrice + spread
(bidVolume, askVolume) = volumesFromTimestamp(timestamp, spread)
return ticks
def waveModel(startDate, endDate, startPrice, endPrice, deltaTime, spread, volatility):
timestamp = startDate
bidPrice = startPrice
askPrice = bidPrice + spread
bidVolume = 1
askVolume = bidVolume + spread
deltaPrice = endPrice - startPrice
count = ceil((endDate + datetime.timedelta(days=1) - startDate) / deltaTime)
d = count / 2 # Denominator for curve shaping
ticks = []
for i in range(0, count):
ticks += [
{
"timestamp": timestamp,
"bidPrice": bidPrice,
"askPrice": askPrice,
"bidVolume": bidVolume,
"askVolume": askVolume,
}
]
i += 1
timestamp += deltaTime
# Select appropriate formula depending on starting and ending prices
if abs(deltaPrice) > 0:
bidPrice = abs(
startPrice
+ i / (count - 1) * deltaPrice
+ volatility * sin(i / (count - 1) * 3 * pi)
)
else:
bidPrice = abs(startPrice + (volatility * sin(i / (count - 1) * 3 * pi)))
askPrice = bidPrice + spread
(bidVolume, askVolume) = volumesFromTimestamp(timestamp, spread)
return ticks
def curveModel(startDate, endDate, startPrice, endPrice, deltaTime, spread, volatility):
timestamp = startDate
bidPrice = startPrice
askPrice = bidPrice + spread
bidVolume = 1
askVolume = bidVolume + spread
deltaPrice = endPrice - startPrice
count = ceil((endDate + datetime.timedelta(days=1) - startDate) / deltaTime)
d = count / volatility # A kind of volatility interpretation via curve shaping
ticks = []
for i in range(0, count):
ticks += [
{
"timestamp": timestamp,
"bidPrice": bidPrice,
"askPrice": askPrice,
"bidVolume": bidVolume,
"askVolume": askVolume,
}
]
i += 1
timestamp += deltaTime
bidPrice = (
startPrice
+ (1 - (exp(i / d) - exp((count - 1) / d)) / (1 - exp((count - 1) / d)))
* deltaPrice
)
askPrice = bidPrice + spread
(bidVolume, askVolume) = volumesFromTimestamp(timestamp, spread)
return ticks
def randomModel(
startDate, endDate, startPrice, endPrice, deltaTime, spread, volatility
):
timestamp = startDate
bidPrice = startPrice
askPrice = bidPrice + spread
bidVolume = 1
askVolume = bidVolume + spread
deltaPrice = (
deltaTime
/ (endDate + datetime.timedelta(days=1) - startDate - deltaTime)
* (endPrice - startPrice)
)
count = ceil((endDate + datetime.timedelta(days=1) - startDate) / deltaTime)
ticks = []
for i in range(0, count):
ticks += [
{
"timestamp": timestamp,
"bidPrice": bidPrice,
"askPrice": askPrice,
"bidVolume": bidVolume,
"askVolume": askVolume,
}
]
timestamp += deltaTime
bidPrice += deltaPrice + deltaPrice * (random.random() - 0.5) * volatility
askPrice = bidPrice + spread
(bidVolume, askVolume) = volumesFromTimestamp(timestamp, spread)
ticks[-1]["bidPrice"] = endPrice
ticks[-1]["askPrice"] = endPrice + spread
return ticks
def toCsv(rows, digits, output):
csvWriter = csv.writer(
output, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL
)
for row in rows:
csvWriter.writerow(
[
row["timestamp"].strftime("%Y.%m.%d %H:%M:%S.%f")[:-3],
("{:.%df}" % (digits)).format(max(row["bidPrice"], 10 ** -digits)),
("{:.%df}" % (digits)).format(max(row["askPrice"], 10 ** -digits)),
("{:.%df}" % (digits)).format(row["bidVolume"]),
("{:.%df}" % (digits)).format(row["askVolume"]),
]
)
if __name__ == "__main__":
argumentParser = argparse.ArgumentParser()
argumentParser.add_argument(
"startDate", help="Starting date of generated data in YYYY.MM.DD format."
)
argumentParser.add_argument(
"endDate", help="Ending date of generated data in YYYY.MM.DD format."
)
argumentParser.add_argument(
"startPrice",
type=float,
help="Starting bid price of generated data, must be a float value.",
)
argumentParser.add_argument(
"endPrice",
type=float,
help="Ending bid price of generated data, must be a float value.",
)
argumentParser.add_argument(
"-D",
"--digits",
type=int,
action="store",
dest="digits",
help="Decimal digits of prices.",
default=5,
)
argumentParser.add_argument(
"-s",
"--spread",
type=int,
action="store",
dest="spread",
help="Spread between prices in points.",
default=10,
)
argumentParser.add_argument(
"-d",
"--density",
type=int,
action="store",
dest="density",
help="Data points per minute in generated data.",
default=1,
)
argumentParser.add_argument(
"-p",
"--pattern",
action="store",
dest="pattern",
choices=["none", "wave", "curve", "zigzag", "random"],
help="Modelling pattern, all of them are deterministic except of 'random'.",
default="none",
)
argumentParser.add_argument(
"-v",
"--volatility",
type=float,
action="store",
dest="volatility",
help="Volatility gain for models, higher values leads to higher volatility in price values.",
default=1.0,
)
argumentParser.add_argument(
"-o",
"--outputFile",
action="store",
dest="outputFile",
help="Write generated data to file instead of standard output.",
)
arguments = argumentParser.parse_args()
# Check date values
try:
startDate = datetime.datetime.strptime(arguments.startDate, "%Y.%m.%d")
endDate = datetime.datetime.strptime(arguments.endDate, "%Y.%m.%d")
except ValueError as e:
error("Bad date format!")
if endDate < startDate:
error("Ending date precedes starting date!")
if arguments.digits <= 0:
error("Digits must be larger than zero!")
if arguments.startPrice <= 0 or arguments.endPrice <= 0:
error("Price must be larger than zero!")
if arguments.spread < 0:
error("Spread must be larger or equal to zero!")
spread = arguments.spread / 1e5
if arguments.density <= 0:
error("Density must be larger than zero!")
if arguments.volatility <= 0:
error("Volatility must be larger than zero!")
# Select and run appropriate model
deltaTime = datetime.timedelta(seconds=60 / arguments.density)
rows = None
if arguments.pattern == "none":
rows = linearModel(
startDate,
endDate,
arguments.startPrice,
arguments.endPrice,
deltaTime,
spread,
)
elif arguments.pattern == "zigzag":
rows = zigzagModel(
startDate,
endDate,
arguments.startPrice,
arguments.endPrice,
deltaTime,
spread,
arguments.volatility,
)
elif arguments.pattern == "wave":
rows = waveModel(
startDate,
endDate,
arguments.startPrice,
arguments.endPrice,
deltaTime,
spread,
arguments.volatility,
)
elif arguments.pattern == "curve":
rows = curveModel(
startDate,
endDate,
arguments.startPrice,
arguments.endPrice,
deltaTime,
spread,
arguments.volatility,
)
elif arguments.pattern == "random":
rows = randomModel(
startDate,
endDate,
arguments.startPrice,
arguments.endPrice,
deltaTime,
spread,
arguments.volatility,
)
# output array stdout/file
if arguments.outputFile:
with open(arguments.outputFile, "w") as outputFile:
toCsv(rows, arguments.digits, outputFile)
else:
toCsv(rows, arguments.digits, sys.stdout)