-
Notifications
You must be signed in to change notification settings - Fork 827
/
instruments.py
392 lines (306 loc) · 11.7 KB
/
instruments.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
388
389
390
391
392
import numpy as np
from copy import copy
from syscore.constants import arg_not_supplied
from syscore.genutils import flatten_list
from dataclasses import dataclass
import pandas as pd
EMPTY_INSTRUMENT = ""
class futuresInstrument(object):
def __init__(self, instrument_code: str):
self._instrument_code = instrument_code
@property
def instrument_code(self):
return self._instrument_code
def empty(self):
return self.instrument_code == EMPTY_INSTRUMENT
@classmethod
def create_from_dict(futuresInstrument, input_dict):
# Might seem pointless, but (a) is used in original code, (b) gives a nice consistent feel
return futuresInstrument(input_dict["instrument_code"])
def as_dict(self):
# Might seem pointless, but (a) is used in original code, (b) gives a nice consistent feel
return dict(instrument_code=self.instrument_code)
def __eq__(self, other):
return self.instrument_code == other.instrument_code
@property
def key(self):
return self.instrument_code
def __repr__(self):
return str(self.instrument_code)
META_FIELD_LIST = [
"Description",
"Pointsize",
"Currency",
"AssetClass",
"PerBlock",
"Percentage",
"PerTrade",
"Region",
]
def _zero_if_nan(x):
if np.isnan(x):
return 0
else:
return x
NO_REGION = "NO_REGION"
def _string_if_nan(x, string=NO_REGION):
if np.isnan(x):
return string
else:
return x
class instrumentMetaData(object):
def __init__(
self,
Description: str = "",
Pointsize: float = 0.0,
Currency: str = "",
AssetClass: str = "",
PerBlock: float = 0.0,
Percentage: float = 0.0,
PerTrade: float = 0.0,
Region: str = "",
):
self.Description = Description
self.Currency = Currency
self.Pointsize = _zero_if_nan(Pointsize)
self.AssetClass = AssetClass
self.PerBlock = _zero_if_nan(PerBlock)
self.Percentage = _zero_if_nan(Percentage)
self.PerTrade = _zero_if_nan(PerTrade)
self.Region = Region
def as_dict(self) -> dict:
keys = META_FIELD_LIST
self_as_dict = dict([(key, getattr(self, key)) for key in keys])
return self_as_dict
@classmethod
def from_dict(instrumentMetaData, input_dict):
keys = list(input_dict.keys())
args_list = [input_dict[key] for key in keys]
return instrumentMetaData(*args_list)
def __eq__(self, other):
return self.as_dict() == other.as_dict()
def __repr__(self):
return str(self.as_dict())
@dataclass
class futuresInstrumentWithMetaData:
instrument: futuresInstrument
meta_data: instrumentMetaData
@property
def instrument_code(self) -> str:
return self.instrument.instrument_code
@property
def key(self) -> str:
return self.instrument_code
def as_dict(self) -> dict:
meta_data_dict = self.meta_data.as_dict()
meta_data_dict["instrument_code"] = self.instrument_code
return meta_data_dict
@classmethod
def from_dict(futuresInstrumentWithMetaData, input_dict):
instrument_code = input_dict.pop("instrument_code")
instrument = futuresInstrument(instrument_code)
meta_data = instrumentMetaData.from_dict(input_dict)
return futuresInstrumentWithMetaData(instrument, meta_data)
@classmethod
def create_empty(futuresInstrumentWithMetaData):
instrument = futuresInstrument(EMPTY_INSTRUMENT)
meta_data = instrumentMetaData()
instrument_with_metadata = futuresInstrumentWithMetaData(instrument, meta_data)
return instrument_with_metadata
def empty(self):
return self.instrument.empty()
def __eq__(self, other):
instrument_matches = self.instrument == other.instrument
meta_data_matches = self.meta_data == other.meta_data
return instrument_matches and meta_data_matches
class listOfFuturesInstrumentWithMetaData(list):
def as_df(self):
instrument_codes = [
instrument_object.instrument_code for instrument_object in self
]
meta_data_keys = [
instrument_object.meta_data.as_dict().keys() for instrument_object in self
]
meta_data_keys_flattened = flatten_list(meta_data_keys)
meta_data_keys_unique = list(set(meta_data_keys_flattened))
meta_data_as_lists = dict(
[
(
metadata_name,
[
getattr(instrument_object.meta_data, metadata_name)
for instrument_object in self
],
)
for metadata_name in meta_data_keys_unique
]
)
meta_data_as_dataframe = pd.DataFrame(
meta_data_as_lists, index=instrument_codes
)
return meta_data_as_dataframe
class assetClassesAndInstruments(dict):
def __repr__(self):
return str(self.as_pd())
def get_instrument_list(self) -> list:
return list(self.keys())
@classmethod
def from_pd_series(self, pd_series: pd.Series):
instruments = list(pd_series.index)
asset_classes = list(pd_series.values)
as_dict = dict(
[
(instrument_code, asset_class)
for instrument_code, asset_class in zip(instruments, asset_classes)
]
)
return assetClassesAndInstruments(as_dict)
def all_asset_classes(self) -> list:
asset_classes = list(self.values())
unique_asset_classes = list(set(asset_classes))
unique_asset_classes.sort()
return unique_asset_classes
def as_pd(self) -> pd.Series:
instruments = [key for key in self.keys()]
asset_classes = [value for value in self.values()]
return pd.Series(asset_classes, index=instruments)
def all_instruments_in_asset_class(
self, asset_class: str, must_be_in=arg_not_supplied
) -> list:
asset_class_instrument_list = [
instrument
for instrument, item_asset_class in self.items()
if item_asset_class == asset_class
]
if must_be_in is arg_not_supplied:
return asset_class_instrument_list
## we need to filter
filtered_asset_class_instrument_list = [
instrument
for instrument in asset_class_instrument_list
if instrument in must_be_in
]
return filtered_asset_class_instrument_list
class instrumentCosts(object):
def __init__(
self,
price_slippage: float = 0.0,
value_of_block_commission: float = 0.0,
percentage_cost: float = 0.0,
value_of_pertrade_commission: float = 0.0,
):
self._price_slippage = price_slippage
self._value_of_block_commission = value_of_block_commission
self._percentage_cost = percentage_cost
self._value_of_pertrade_commission = value_of_pertrade_commission
@classmethod
def from_meta_data_and_spread_cost(
instrumentCosts, meta_data: instrumentMetaData, spread_cost: float
):
return instrumentCosts(
price_slippage=spread_cost,
value_of_block_commission=meta_data.PerBlock,
percentage_cost=meta_data.Percentage,
value_of_pertrade_commission=meta_data.PerTrade,
)
def __repr__(self):
return (
"instrumentCosts slippage %f block_commission %f percentage cost %f per trade commission %f "
% (
self.price_slippage,
self.value_of_block_commission,
self.percentage_cost,
self.value_of_pertrade_commission,
)
)
def commission_only(self):
new_costs = instrumentCosts(
price_slippage=0.0,
value_of_block_commission=self.value_of_block_commission,
percentage_cost=self.percentage_cost,
value_of_pertrade_commission=self.value_of_pertrade_commission,
)
return new_costs
def spread_only(self):
new_costs = instrumentCosts(
price_slippage=self.price_slippage,
value_of_block_commission=0,
percentage_cost=0,
value_of_pertrade_commission=0,
)
return new_costs
@property
def price_slippage(self):
return self._price_slippage
@property
def value_of_block_commission(self):
return self._value_of_block_commission
@property
def percentage_cost(self):
return self._percentage_cost
@property
def value_of_pertrade_commission(self):
return self._value_of_pertrade_commission
def calculate_sr_cost(
self,
block_price_multiplier: float,
price: float,
ann_stdev_price_units: float,
blocks_traded: float = 1.0,
) -> float:
cost_instrument_currency = self.calculate_cost_instrument_currency(
blocks_traded=blocks_traded,
block_price_multiplier=block_price_multiplier,
price=price,
)
ann_stdev_instrument_currency = ann_stdev_price_units * block_price_multiplier
return cost_instrument_currency / ann_stdev_instrument_currency
def calculate_cost_percentage_terms(
self, blocks_traded: float, block_price_multiplier: float, price: float
) -> float:
cost_in_currency_terms = self.calculate_cost_instrument_currency(
blocks_traded, block_price_multiplier=block_price_multiplier, price=price
)
value_per_block = price * block_price_multiplier
total_value = blocks_traded * value_per_block
cost_in_percentage_terms = cost_in_currency_terms / total_value
return cost_in_percentage_terms
def calculate_cost_instrument_currency(
self,
blocks_traded: float,
block_price_multiplier: float,
price: float,
include_slippage: bool = True,
) -> float:
value_per_block = price * block_price_multiplier
if include_slippage:
slippage = self.calculate_slippage_instrument_currency(
blocks_traded, block_price_multiplier=block_price_multiplier
)
else:
slippage = 0
commission = self.calculate_total_commission(
blocks_traded, value_per_block=value_per_block
)
return slippage + commission
def calculate_total_commission(self, blocks_traded: float, value_per_block: float):
### YOU WILL NEED TO CHANGE THIS IF YOUR BROKER HAS A MORE COMPLEX STRUCTURE
per_trade_commission = self.calculate_per_trade_commission()
per_block_commission = self.calculate_cost_per_block_commission(blocks_traded)
percentage_commission = self.calculate_percentage_commission(
blocks_traded, value_per_block
)
return max([per_block_commission, per_trade_commission, percentage_commission])
def calculate_slippage_instrument_currency(
self, blocks_traded: float, block_price_multiplier: float
) -> float:
return abs(blocks_traded) * self.price_slippage * block_price_multiplier
def calculate_per_trade_commission(self):
return self.value_of_pertrade_commission
def calculate_cost_per_block_commission(self, blocks_traded):
return abs(blocks_traded) * self.value_of_block_commission
def calculate_percentage_commission(self, blocks_traded, price_per_block):
trade_value = self.calculate_trade_value(blocks_traded, price_per_block)
return self.percentage_cost * trade_value
def calculate_trade_value(self, blocks_traded, value_per_block):
return abs(blocks_traded) * value_per_block