-
Notifications
You must be signed in to change notification settings - Fork 0
/
instrument.py
233 lines (197 loc) · 7.15 KB
/
instrument.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
import asyncio
import operator
import concurrent.futures as confu
from collections import OrderedDict
from datetime import date, datetime
def to_datetime(obj, formats=['%Y%m%d', '%Y-%m-%d', '%Y/%m/%d']):
if type(obj) is datetime:
return obj
elif type(obj) is date:
return datetime(obj.year, obj.month, obj.day)
elif type(obj) is str:
for f in formats:
try:
return datetime.strptime(obj, f)
except ValueError:
continue
raise ValueError(
f'String {obj} matches none of the formats in {formats}.'
)
raise ValueError(
f'Unknown type {type(obj)}'
)
class FloorDict(OrderedDict):
def __get__(self, key):
try:
return super().__get__(self, key)
except KeyError:
try:
return super().__get__(
self, max(k for k in self if k < key)
)
except ValueError:
raise KeyError(
'Key not found and value outside key range'
)
def price_from_mkt_cap_and_shares(mkt_cap, shares_outstanding):
return mkt_cap / shares_outstanding
def adj_price(price, cumulative_price_adjust):
return price / cumulative_price_adjust
def mkt_cap_from_price_and_shares(price, shares_outstanding):
return price * shares_outstanding
def shares_from_mkt_cap_and_price(mkt_cap, price):
return mkt_cap / price
def calc_market_vals(price, mkt_cap, shares_outstanding):
"""Requires (any) two inputs to be non-None"""
try:
if price is None:
_price = mkt_cap / shares_outstanding
if mkt_cap is None:
_mkt_cap = price * shares_outstanding
if shares_outstanding is None:
_shares_outstanding = mkt_cap / price
except TypeError as e:
raise TypeError(
'calc_market_vals requires at least two inputs to be non-None'
) from e
return _price, _mkt_cap, _shares_outstanding
class Status:
def __init__(self, time, volume=None, price=None,
mkt_cap=None, shares_outstanding=None,
price_adjust=None, shares_adjust=None):
self.time = to_datetime(time)
self.volume = volume
self.price, self.mkt_cap, self.shares_outstanding = calc_market_vals(
price, mkt_cap, shares_outstanding
)
if price_adjust is None:
self.adj_price = price
else:
self.adj_price = price / price_adjust
if shares_adjust is None:
self.adj_shares = shares_outstanding
else:
self.adj_shares = shares_outstanding * shares_adjust
self.price_adjust = price_adjust
self.shares_adjust = shares_adjust
def __getitem__(self, key):
return self.attrs[key]
def __repr__(self):
return f'{type(self).__name__}({self.time})'
class Instrument:
def __init__(self, statuses, name=None, sic_code=None):
self.statuses = statuses.sort(
key=operator.attrgetter('time')
)
self.name = name
def __getitem__(self, key):
return self.statuses[key]
class Index(Instrument):
def __init__(self, instruments):
self.instruments = instruments
@classmethod
def from_crsp_df_async(cls, df):
"""Create market from CRSP file read into a pandas DataFrame.
Required columns (as defined by Center for Research in Security Prices):
PERMNO: Permanent identifier for instrument
date: date
SICCD: Standard Industrial Classification code
VOL: Trading volume
PRC: price
SHROUT: Shares outstanding
CFACPR: Cumulative factor to adjust price
CFACSHR: Cumulative factor to adjust shares
"""
df = df.rename(
mapper={
'PERMNO': 'name',
'SICCD': 'sic_code',
'VOL': 'volume',
'PRC': 'price',
'SHROUT': 'shares_outstanding',
'CFACPR': 'cumulative_price_adjust',
'CFACSHR': 'cumulative_shares_adjust',
},
axis='columns',
)
async def create_instrument(name, i):
statdict = i.to_dict(orient='index')
statuses = [
Status(k, v) for k, v in statdict.items()
]
return Instrument(
statuses,
name=name
)
instruments = []
async def all_instruments(df):
for name, i in df.set_index('date').groupby('PERMNO'):
instruments.append(create_instrument(name, i))
await asyncio.gather(*instruments)
asyncio.run(all_instruments(df))
return cls(instruments)
@classmethod
def from_crsp_df_sync(cls, df):
"""Create market from CRSP file read into a pandas DataFrame.
Required columns (as defined by Center for Research in Security Prices):
PERMNO: Permanent identifier for instrument
date: date
SICCD: Standard Industrial Classification code
VOL: Trading volume
PRC: price
SHROUT: Shares outstanding
CFACPR: Cumulative factor to adjust price
CFACSHR: Cumulative factor to adjust shares
"""
instruments = []
for name, i in df.set_index('date').groupby('PERMNO'):
d = i.to_dict(orient='index')
statdict = {
k: d[k] for k in [
'date',
'PRC',
'VOL',
'SHROUT',
'CFACPR',
'CFACSHR',
]
}
statuses = [
Status(k, v) for k, v in statdict.items()
]
instruments.append(Instrument(
statuses,
name=name
)
)
return cls(instruments)
@classmethod
def from_crsp_df_threaded(cls, df):
"""Create market from CRSP file read into a pandas DataFrame.
Required columns (as defined by Center for Research in Security Prices):
PERMNO: Permanent identifier for instrument
date: date
SICCD: Standard Industrial Classification code
VOL: Trading volume
PRC: price
SHROUT: Shares outstanding
CFACPR: Cumulative factor to adjust price
CFACSHR: Cumulative factor to adjust shares
"""
def create_instrument(name, i):
statdict = i.to_dict(orient='index')
statuses = [
Status(k, v) for k, v in statdict.items()
]
return Instrument(
statuses,
name=name
)
with confu.ThreadPoolExecutor() as executor:
instruments = [
i for i in executor.map(
lambda x: create_instrument(*x),
df.set_index('date').groupby('PERMNO')
)
]
return cls(instruments)