-
Notifications
You must be signed in to change notification settings - Fork 680
/
Copy pathtiingo.py
402 lines (361 loc) · 12.7 KB
/
tiingo.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
393
394
395
396
397
398
399
400
401
402
import os
import pandas as pd
from pandas_datareader.base import _BaseReader
TIINGO_API_URL_BASE = "https://api.tiingo.com"
def get_tiingo_symbols():
"""
Get the set of stock symbols supported by Tiingo
Returns
-------
symbols : DataFrame
DataFrame with symbols (ticker), exchange, asset type, currency and
start and end dates
Notes
-----
Reads https://apimedia.tiingo.com/docs/tiingo/daily/supported_tickers.zip
"""
url = "https://apimedia.tiingo.com/docs/tiingo/daily/supported_tickers.zip"
return pd.read_csv(url)
class TiingoIEXHistoricalReader(_BaseReader):
"""
Historical data from Tiingo on equities, ETFs and mutual funds,
with re-sampling capability. This query is limited to the last
1,000 bars based in the endDate. So the startDate is moved if
it goes past the limit.
Parameters
----------
symbols : {str, List[str]}
String symbol or list of symbols
start : {string, int, date, datetime, Timestamp}
Starting date. Parses many different kind of date
representations (e.g., 'JAN-01-2010', '1/1/10', 'Jan, 1, 1980').
Defaults to 20 years before current date.
end : {string, int, date, datetime, Timestamp}
Ending date
retry_count : int, default 3
Number of times to retry query request.
pause : float, default 0.1
Time, in seconds, of the pause between retries.
session : Session, default None
requests.sessions.Session instance to be used
freq : {str, None}
Re-sample frequency. Format is #min/hour; e.g. "15min" or "4hour".
If no value is provided, defaults to 5min. The minimum value is "1min".
Units in minutes (min) and hours (hour) are accepted.
response_format : str, default 'json'
Specifies format of response data returned by the underlying
Tiingo REST API. Acceptable values are 'json' and 'csv'.
Use of 'csv' results in smaller message payload, less bandwidth,
and may delay the time when client hits API's bandwidth limit.
api_key : str, optional
Tiingo API key . If not provided the environmental variable
TIINGO_API_KEY is read. The API key is *required*.
"""
def __init__(
self,
symbols,
start=None,
end=None,
retry_count=3,
pause=0.1,
timeout=30,
session=None,
freq=None,
response_format="json",
api_key=None,
):
super().__init__(
symbols, start, end, retry_count, pause, timeout, session, freq
)
if isinstance(self.symbols, str):
self.symbols = [self.symbols]
self._symbol = ""
if api_key is None:
api_key = os.getenv("TIINGO_API_KEY")
if not api_key or not isinstance(api_key, str):
raise ValueError(
"The tiingo API key must be provided either "
"through the api_key variable or through the "
"environmental variable TIINGO_API_KEY."
)
self.api_key = api_key
if response_format not in ["json", "csv"]:
raise ValueError("Acceptable values are 'json' and 'csv'")
self.response_format = response_format
self._concat_axis = 0
@property
def url(self):
"""API URL"""
_url = TIINGO_API_URL_BASE + "/iex/{ticker}/prices"
return _url.format(ticker=self._symbol)
@property
def params(self):
"""Parameters to use in API calls"""
return {
"startDate": self.start.strftime("%Y-%m-%d"),
"endDate": self.end.strftime("%Y-%m-%d"),
"resampleFreq": self.freq,
"format": self.response_format,
}
def _get_crumb(self, *args):
pass
def _read_one_data(self, url, params):
""" read one data from specified URL """
content_type = (
"application/json" if self.response_format == "json" else "text/csv"
)
headers = {
"Content-Type": content_type,
"Authorization": "Token " + self.api_key,
}
out = None
if self.response_format == "json":
out = self._get_response(url, params=params, headers=headers).json()
elif self.response_format == "csv":
out = self._read_url_as_StringIO(url, params=params, headers=headers)
return self._read_lines(out)
def _read_lines(self, out):
df = pd.DataFrame(out) if self.response_format == "json" else pd.read_csv(out)
df["symbol"] = self._symbol
df["date"] = pd.to_datetime(df["date"])
df = df.set_index(["symbol", "date"])
return df
def read(self):
"""Read data from connector"""
dfs = []
for symbol in self.symbols:
self._symbol = symbol
try:
dfs.append(self._read_one_data(self.url, self.params))
finally:
self.close()
return pd.concat(dfs, self._concat_axis)
class TiingoDailyReader(_BaseReader):
"""
Historical daily data from Tiingo on equities, ETFs and mutual funds
Parameters
----------
symbols : {str, List[str]}
String symbol or list of symbols
start : {string, int, date, datetime, Timestamp}
Starting date, timestamp. Parses many different kind of date
representations (e.g., 'JAN-01-2010', '1/1/10', 'Jan, 1, 1980').
Default starting date is 5 years before current date.
end : {string, int, date, datetime, Timestamp}
Ending date, timestamp. Same format as starting date.
retry_count : int, default 3
Number of times to retry query request.
pause : float, default 0.1
Time, in seconds, of the pause between retries.
session : Session, default None
requests.sessions.Session instance to be used
freq : {str, None}
Not used.
response_format : str, default 'json'
Specifies format of response data returned by the underlying
Tiingo REST API. Acceptable values are 'json' and 'csv'.
Use of 'csv' results in smaller message payload, less bandwidth,
and may delay the time when client hits API's bandwidth limit.
api_key : str, optional
Tiingo API key . If not provided the environmental variable
TIINGO_API_KEY is read. The API key is *required*.
"""
def __init__(
self,
symbols,
start=None,
end=None,
retry_count=3,
pause=0.1,
timeout=30,
session=None,
freq=None,
response_format="json",
api_key=None,
):
super(TiingoDailyReader, self).__init__(
symbols, start, end, retry_count, pause, timeout, session, freq
)
if isinstance(self.symbols, str):
self.symbols = [self.symbols]
self._symbol = ""
if api_key is None:
api_key = os.getenv("TIINGO_API_KEY")
if not api_key or not isinstance(api_key, str):
raise ValueError(
"The tiingo API key must be provided either "
"through the api_key variable or through the "
"environmental variable TIINGO_API_KEY."
)
self.api_key = api_key
if response_format not in ["json", "csv"]:
raise ValueError("Acceptable values are 'json' and 'csv'")
self.response_format = response_format
self._concat_axis = 0
@property
def url(self):
"""API URL"""
_url = TIINGO_API_URL_BASE + "/tiingo/daily/{ticker}/prices"
return _url.format(ticker=self._symbol)
@property
def params(self):
"""Parameters to use in API calls"""
return {
"startDate": self.start.strftime("%Y-%m-%d"),
"endDate": self.end.strftime("%Y-%m-%d"),
"format": self.response_format,
}
def _get_crumb(self, *args):
pass
def _read_one_data(self, url, params):
""" read one data from specified URL """
content_type = (
"application/json" if self.response_format == "json" else "text/csv"
)
headers = {
"Content-Type": content_type,
"Authorization": "Token " + self.api_key,
}
out = None
if self.response_format == "json":
out = self._get_response(url, params=params, headers=headers).json()
elif self.response_format == "csv":
out = self._read_url_as_StringIO(url, params=params, headers=headers)
return self._read_lines(out)
def _read_lines(self, out):
df = pd.DataFrame(out) if self.response_format == "json" else pd.read_csv(out)
df["symbol"] = self._symbol
df["date"] = pd.to_datetime(df["date"])
df = df.set_index(["symbol", "date"])
return df
def read(self):
"""Read data from connector"""
dfs = []
for symbol in self.symbols:
self._symbol = symbol
try:
dfs.append(self._read_one_data(self.url, self.params))
finally:
self.close()
return pd.concat(dfs, self._concat_axis)
class TiingoMetaDataReader(TiingoDailyReader):
"""
Read metadata about symbols from Tiingo
Parameters
----------
symbols : {str, List[str]}
String symbol or list of symbols
start : {string, int, date, datetime, Timestamp}
Not used.
end : {string, int, date, datetime, Timestamp}
Not used.
retry_count : int, default 3
Number of times to retry query request.
pause : float, default 0.1
Time, in seconds, of the pause between retries.
session : Session, default None
requests.sessions.Session instance to be used
freq : {str, None}
Not used.
api_key : str, optional
Tiingo API key . If not provided the environmental variable
TIINGO_API_KEY is read. The API key is *required*.
"""
def __init__(
self,
symbols,
start=None,
end=None,
retry_count=3,
pause=0.1,
timeout=30,
session=None,
freq=None,
api_key=None,
):
super(TiingoMetaDataReader, self).__init__(
symbols,
start,
end,
retry_count,
pause,
timeout,
session,
freq,
response_format="json",
api_key=api_key,
)
self._concat_axis = 1
@property
def url(self):
"""API URL"""
_url = TIINGO_API_URL_BASE + "/tiingo/daily/{ticker}"
return _url.format(ticker=self._symbol)
@property
def params(self):
return None
def _read_lines(self, out):
s = pd.Series(out)
s.name = self._symbol
return s
class TiingoQuoteReader(TiingoDailyReader):
"""
Read quotes (latest prices) from Tiingo
Parameters
----------
symbols : {str, List[str]}
String symbol or list of symbols
start : {string, int, date, datetime, Timestamp}
Not used.
end : {string, int, date, datetime, Timestamp}
Not used.
retry_count : int, default 3
Number of times to retry query request.
pause : float, default 0.1
Time, in seconds, of the pause between retries.
session : Session, default None
requests.sessions.Session instance to be used
freq : {str, None}
Not used.
response_format : str, default 'json'
Specifies format of response data returned by the underlying
Tiingo REST API. Acceptable values are 'json' and 'csv'.
Use of 'csv' results in smaller message payload, less bandwidth,
and may delay the time when client hits API's bandwidth limit.
api_key : str, optional
Tiingo API key . If not provided the environmental variable
TIINGO_API_KEY is read. The API key is *required*.
Notes
-----
This is a special case of the daily reader which automatically selected
the latest data available for each symbol.
"""
def __init__(
self,
symbols,
start=None,
end=None,
retry_count=3,
pause=0.1,
timeout=30,
session=None,
freq=None,
response_format="json",
api_key=None,
):
super(TiingoQuoteReader, self).__init__(
symbols,
start,
end,
retry_count,
pause,
timeout,
session,
freq,
response_format,
api_key,
)
@property
def params(self):
"""Parameters to use in API calls"""
return {"format": self.response_format}