forked from pst-group/pysystemtrade
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenutils.py
More file actions
executable file
·390 lines (292 loc) · 8.59 KB
/
Copy pathgenutils.py
File metadata and controls
executable file
·390 lines (292 loc) · 8.59 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
"""
Utilities I can't put anywhere else...
"""
from typing import Union
import datetime
import functools
import math
import numpy as np
from collections import namedtuple
from math import copysign, gcd
from typing import Union, List
Changes = namedtuple("Changes", ["new", "existing", "removing"])
def new_removing_existing(original_list: list, new_list: list) -> Changes:
"""
>>> new_removing_existing([1,2],[3,4])
Changes(new=[3, 4], existing=[], removing=[1, 2])
>>> new_removing_existing([1,2,3],[3,4])
Changes(new=[4], existing=[3], removing=[1, 2])
>>> new_removing_existing([1,2,3],[1,2])
Changes(new=[], existing=[1, 2], removing=[3])
>>> new_removing_existing([1],[1,2])
Changes(new=[2], existing=[1], removing=[])
"""
existing = list_intersection(original_list, new_list)
new = list_difference(new_list, original_list)
removing = list_difference(original_list, new_list)
return Changes(new=new, existing=existing, removing=removing)
def list_intersection(x: list, y: list) -> list:
"""
>>> list_intersection([2,1], [1])
[1]
>>> list_intersection([2,1], [3])
[]
"""
return list(set(x).intersection(set(y)))
def list_difference(x: list, y: list) -> list:
"""
>>> list_difference([2,1], [1])
[2]
>>> list_difference([2,1], [3])
[1, 2]
>>> list_difference([3], [1, 2])
[3]
>>> list_difference([2,1], [1,2])
[]
"""
return list(set(x).difference(set(y)))
def list_union(x: list, y: list) -> list:
"""
>>> list_union([1,2], [1])
[1, 2]
>>> list_union([2,1], [3])
[1, 2, 3]
"""
return list(set(x).union(set(y)))
def get_unique_list(somelist: list) -> list:
return list(set(somelist))
def get_unique_list_slow(somelist):
uniquelist = []
for somevalue in somelist:
if somevalue not in uniquelist:
uniquelist.append(somevalue)
return uniquelist
def round_significant_figures(x: float, figures: int = 3) -> float:
"""
>>> round_significant_figures(0.0234, 2)
0.023
"""
if x == 0:
return 0.0
return round(x, figures - int(math.floor(math.log10(abs(x)))) - 1)
def flatten_list(some_list: list) -> list:
"""
>>> flatten_list([[1],[2,3]])
[1, 2, 3]
"""
flattened = [item for sublist in some_list for item in sublist]
return flattened
def str2Bool(x: str) -> bool:
if isinstance(x, bool):
return x
if x.lower() in ("t", "true"):
return True
if x.lower() in ("f", "false"):
return False
raise Exception("%s can't be resolved as a bool" % x)
def str_of_int(x: int) -> str:
"""
Returns the string of int of x, handling nan's or whatever
>>> str_of_int(34)
'34'
>>> str_of_int(34.0)
'34'
>>> import numpy as np
>>> str_of_int(np.nan)
''
"""
if isinstance(x, int):
return str(x)
try:
return str(int(x))
except BaseException:
return ""
def same_sign(x, y):
return sign(x) == sign(y)
def sign(x: Union[int, float]) -> float:
"""
>>> sign(3)
1.0
>>> sign(3.0)
1.0
>>> sign(-3)
-1.0
>>> sign(0)
1.0
"""
return copysign(1, x)
def return_another_value_if_nan(x, return_value=None):
"""
If x is np.nan return return_value
else return x
:param x: np.nan or other
:return: x or return_value
>>> return_another_value_if_nan(np.nan)
>>> return_another_value_if_nan(np.nan, -1)
-1
>>> return_another_value_if_nan("thing")
'thing'
>>> return_another_value_if_nan(42)
42
"""
try:
if np.isnan(x):
return return_value
else:
pass
# Not a nan will return x
except BaseException:
# Not something that can be compared to a nan
pass
# Either wrong type, or not a nan
return x
def are_dicts_equal(d1: dict, d2: dict) -> bool:
"""
>>> are_dicts_equal({1: 'a', 2: 'b'}, {2: 'b', 1: 'a'})
True
>>> are_dicts_equal({1: 'a', 2: 'b'}, {3: 'b', 1: 'a'})
False
>>> are_dicts_equal({1: 'a', 2: 'b'}, {2: 'c', 1: 'a'})
False
"""
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
intersect_keys = d1_keys.intersection(d2_keys)
if len(intersect_keys) != len(d1_keys):
return False
same_values = set(o for o in intersect_keys if d1[o] == d2[o])
if len(same_values) != len(d1_keys):
return False
return True
class quickTimer(object):
def __init__(self, seconds: Union[float, int] = 60):
self._time_started = datetime.datetime.now()
self._time_limit = seconds
@property
def unfinished(self) -> bool:
return not self.finished
@property
def finished(self) -> bool:
time_now = datetime.datetime.now()
elapsed = time_now - self.time_started
is_it_finished = elapsed.seconds > self.time_limit
return is_it_finished
@property
def time_started(self) -> datetime.datetime:
return self._time_started
@property
def time_limit(self) -> int:
return self._time_limit
# avoids encoding problems with mongo
EMPTY_STRING = ""
def if_empty_string_return_object(x, object):
if x == EMPTY_STRING:
return object
else:
return x
def if_object_matches_return_empty_string(x, object_to_match):
if x is object_to_match:
return EMPTY_STRING
else:
return x
"""
NAMED TUPLES AND OBJECTS
"""
def transfer_object_attributes(named_tuple_object, original_object):
kwargs = dict(
[
(field_name, getattr(original_object, field_name))
for field_name in named_tuple_object._fields
]
)
new_object = named_tuple_object(**kwargs)
return new_object
"""
COMMON FACTORS
"""
def highest_common_factor_for_list(list_of_ints: List[int]) -> int:
"""
>>> highest_common_factor_for_list([2,3,4])
1
>>> highest_common_factor_for_list([2,6,4])
2
"""
return functools.reduce(gcd, list_of_ints)
def divide_list_of_ints_by_highest_common_factor(list_of_ints: List[int]) -> list:
"""
>>> divide_list_of_ints_by_highest_common_factor([1,2])
[1, 2]
>>> divide_list_of_ints_by_highest_common_factor([2,4])
[1, 2]
>>> divide_list_of_ints_by_highest_common_factor([1,2,3])
[1, 2, 3]
>>> divide_list_of_ints_by_highest_common_factor([1])
[1]
"""
gcd_value = highest_common_factor_for_list(list_of_ints)
new_list = [int(float(x) / gcd_value) for x in list_of_ints]
return new_list
def list_of_ints_with_highest_common_factor_positive_first(
list_of_ints: List[int],
) -> list:
"""
Used to identify the unique version of a spread or fly contract
:param list_of_ints:
:return: list
>>> list_of_ints_with_highest_common_factor_positive_first([1])
[1]
>>> list_of_ints_with_highest_common_factor_positive_first([-1])
[1]
>>> list_of_ints_with_highest_common_factor_positive_first([1,-1])
[1, -1]
>>> list_of_ints_with_highest_common_factor_positive_first([-1,1])
[1, -1]
>>> list_of_ints_with_highest_common_factor_positive_first([-1,2])
[1, -2]
>>> list_of_ints_with_highest_common_factor_positive_first([-2,2])
[1, -1]
>>> list_of_ints_with_highest_common_factor_positive_first([2,-2])
[1, -1]
>>> list_of_ints_with_highest_common_factor_positive_first([2,-4,2])
[1, -2, 1]
>>> list_of_ints_with_highest_common_factor_positive_first([-2,4,-2])
[1, -2, 1]
"""
new_list = divide_list_of_ints_by_highest_common_factor(list_of_ints)
multiply_sign = sign(new_list[0])
new_list = [int(x * multiply_sign) for x in new_list]
return new_list
def np_convert(val):
"""
Converts the passed numpy value to a native python type
>>> val = np.int64(1)
>>> type(val)
<class 'numpy.int64'>
>>> type(np_convert(val))
<class 'int'>
"""
return val.item() if isinstance(val, np.generic) else val
def intersection_intervals(intervals: list) -> list:
"""
>>> intersection_intervals([[1,5], [2,3]])
[2, 3]
>>> intersection_intervals([[1,5], [2,6]])
[2, 5]
>>> intersection_intervals([[1,5], [1,5]])
[1, 5]
>>> intersection_intervals([[3,7], [2,6]])
[3, 6]
>>> intersection_intervals([[1,5], [7,9]])
[]
"""
start, end = intervals.pop()
while intervals:
start_temp, end_temp = intervals.pop()
start = max(start, start_temp)
end = min(end, end_temp)
if end < start:
return []
return [start, end]
if __name__ == "__main__":
import doctest
doctest.testmod()