-
Notifications
You must be signed in to change notification settings - Fork 33
/
utils.py
246 lines (173 loc) · 6.2 KB
/
utils.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
"""
Python UK trading tax calculator
Copyright (C) 2015 Robert Carver
You may copy, modify and redistribute this file as allowed in the license agreement
but you must retain this header
See README.txt
"""
"""
Useful utilities
"""
import pandas as pd
import numpy as np
import datetime
def star_line(line_length=140):
return "".join(["*"]*line_length)+"\n"
def type_and_sense_check_arguments(classobject, kwargs, checkrequired=True):
"""
Check that we have the right arguments being passed, of the right type
If checkrequired is True then we make sure we have compulsory arguemnts
"""
type_check_dict=classobject._type_check()
possible_args_list=classobject._possible_args()
for argname in kwargs:
if argname not in possible_args_list:
raise Exception("Cant construct or modify objectclass object with a %s" % argname)
if not type(kwargs[argname]) is type_check_dict[argname]:
raise Exception("Bad type for %s" % argname)
if checkrequired:
required_missing=[argname not in kwargs for argname in classobject._required_columns()]
if any(required_missing):
raise Exception("Compulsory argument missing")
return kwargs
def list_of_dict_class_to_pandas_df(classobject, indexname=None):
"""
Takes any classobject which is a list containing objects with some attributes; turns into pd dataframe
Optional indexname
"""
all_keys=[x._possible_args() for x in classobject]
all_keys=list(set([j for i in all_keys for j in i]))
ans={}
for key in all_keys:
ans[key]=[]
for x in classobject:
if key in dir(x):
ans[key].append(getattr(x, key))
else:
ans[key].append(None)
if indexname is None:
ans=pd.DataFrame(ans)
else:
ans=pd.DataFrame(ans, index=ans[indexname])
return ans
def uniquets(df3):
"""
Makes x unique
"""
df3=df3.groupby(level=0).first()
return df3
def repr_class(x):
ans=", ".join(["%s:%s" % (name, str(getattr(x, name))) for name in x.argsused])
return ans
def check_equal(lst):
## Are all elements in a list equal
return lst[1:] == lst[:-1]
def check_identical_attribute(lst, element_name):
## Are all the elements in a list of objects with element_name equal
listofelements=[getattr(x, element_name) for x in lst]
return check_equal(listofelements)
def signs_match(x,y):
## Are the signs of x and y identical?
newsign=np.sign(x)
oldsign=np.sign(y)
return newsign==oldsign
def signs_match_list(xlist):
if len(xlist)<2:
return True
return all(signs_match(xlist[idx], xlist[idx-1]) for idx in range(len(xlist))[1:])
def any_duplicates(xlist):
if len(xlist)<2:
return False
xnewlist=sorted(xlist)
return any(xnewlist[idx]== xnewlist[idx-1] for idx in range(len(xnewlist))[1:])
def tax_year(year=None):
"""
Returns a tuple of datetime objects defining the start and end of a tax year (6 April to 5 April)
(optional) year int is the calendar year when the year ended
"""
if year is None:
## use current year
year=which_tax_year(datetime.datetime.now())
next_tax_year_starts=datetime.datetime(year=year-1, month=4, day=6)
next_tax_year_ends=datetime.datetime(year=year, month=4, day=5)
return (next_tax_year_starts, next_tax_year_ends)
def which_tax_year(date_time):
"""
Returns the tax year a date is in
"""
thisapril6=datetime.datetime(year=date_time.year, month=4, day=6)
if date_time>=thisapril6:
year=date_time.year+1
else:
year=date_time.year
return year
def next_letter_code(letter):
## We take the last letter
last_letter=letter[-1]
if last_letter=="z":
## Add an extra letter
return letter+"a"
next_letter=chr(ord(last_letter)+1)
return letter[:-1]+next_letter
def pretty(x, commas=True):
"""
Return a string of x formatted nicely
"""
if x==0.0:
return "0"
absx=abs(x)
if int(x)==x:
if commas:
return "{:,.0f}".format(x)
else:
return "%d" % int(x)
if absx>100000:
if commas:
return "{:,.0f}".format(x)
else:
return "%.0f" % x
if absx>=1000:
if commas:
return "{:,.2f}".format(x)
else:
return "%.2f" % x
if absx>=100:
return "%.3f" % x
if absx>=10:
return "%.4f" % x
if absx>=1:
return "%.5f" % x
if absx>=0.1:
return "%.6f" % x
if absx>=0.01:
return "%.7f" % x
if absx>=0.001:
return "%.8f" % x
if absx>=0.0001:
return "%.9f" % x
return "%.10f" % x
def profit_analyser(profits):
## Do some rudimentary analysis of profits
biglist=[]
for code in profits.keys():
biglist=biglist+profits[code]
codes=list(set(list(profits.keys())))
profits_by_code=[sum(profits[code]) for code in codes]
profits_by_code=pd.DataFrame(dict(code=codes, profit=profits_by_code))
stdev_profits_by_code=[float(np.nanstd(profits[code])) for code in codes]
stdev_profits_by_code = pd.DataFrame(dict(code=codes, stdev_profit = stdev_profits_by_code))
avg_profits_by_code=[float(np.nanmean(profits[code])) for code in codes]
avg_profits_by_code = pd.DataFrame(dict(code=codes, avg_profit = avg_profits_by_code))
profits=[x for x in biglist if x>0]
losses=[x for x in biglist if x<0]
stdev = float(np.nanstd(biglist))
print("%d Trades Profits %d Losses %s" % (len(biglist), len(profits),len(losses)))
print( "Average %f Average profit %f Average loss %f" % (np.mean(biglist), np.mean(profits), np.mean(losses)))
print( "Standard deviation %f" % stdev)
profits_by_code=profits_by_code.sort_values("profit")
print( "Total profits by code")
print( profits_by_code)
print( "Avg profits by code")
print( avg_profits_by_code)
print( "Std profits by code")
print( stdev_profits_by_code)