datamule 0.416__cp39-cp39-macosx_10_9_universal2.whl → 0.418__cp39-cp39-macosx_10_9_universal2.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of datamule might be problematic. Click here for more details.

datamule/__init__.py CHANGED
@@ -12,12 +12,21 @@ def __getattr__(name):
12
12
  elif name == 'Parser':
13
13
  from .parser.document_parsing.sec_parser import Parser
14
14
  return Parser
15
+ elif name == 'Monitor':
16
+ from .monitor import Monitor
17
+ return Monitor
18
+ elif name == 'PackageUpdater':
19
+ from .packageupdater import PackageUpdater
20
+ return PackageUpdater
15
21
  elif name == 'Submission':
16
22
  from .submission import Submission
17
23
  return Submission
18
24
  elif name == 'Portfolio':
19
25
  from .portfolio import Portfolio
20
26
  return Portfolio
27
+ elif name == 'Document':
28
+ from .document import Document
29
+ return Document
21
30
  elif name == "parse_sgml_submission":
22
31
  from .parser.sgml_parsing.sgml_parser_cy import parse_sgml_submission
23
32
  return parse_sgml_submission
@@ -0,0 +1,364 @@
1
+ import asyncio
2
+ import aiohttp
3
+ import os
4
+ from tqdm import tqdm
5
+ from datetime import datetime
6
+ from urllib.parse import urlencode
7
+ import aiofiles
8
+ import json
9
+ import time
10
+ from collections import deque
11
+
12
+ from ..helper import identifier_to_cik, load_package_csv, fix_filing_url, headers
13
+ from ..parser.sgml_parsing.sgml_parser_cy import parse_sgml_submission
14
+
15
+ class RetryException(Exception):
16
+ def __init__(self, url, retry_after=601):
17
+ self.url = url
18
+ self.retry_after = retry_after
19
+
20
+ class PreciseRateLimiter:
21
+ def __init__(self, rate, interval=1.0):
22
+ self.rate = rate # requests per interval
23
+ self.interval = interval # in seconds
24
+ self.token_time = self.interval / self.rate # time per token
25
+ self.last_time = time.time()
26
+ self.lock = asyncio.Lock()
27
+
28
+ async def acquire(self):
29
+ async with self.lock:
30
+ now = time.time()
31
+ wait_time = self.last_time + self.token_time - now
32
+ if wait_time > 0:
33
+ await asyncio.sleep(wait_time)
34
+ self.last_time = time.time()
35
+ return True
36
+
37
+ async def __aenter__(self):
38
+ await self.acquire()
39
+ return self
40
+
41
+ async def __aexit__(self, exc_type, exc, tb):
42
+ pass
43
+
44
+ class RateMonitor:
45
+ def __init__(self, window_size=1.0):
46
+ self.window_size = window_size
47
+ self.requests = deque()
48
+ self._lock = asyncio.Lock()
49
+
50
+ async def add_request(self, size_bytes):
51
+ async with self._lock:
52
+ now = time.time()
53
+ self.requests.append((now, size_bytes))
54
+ while self.requests and self.requests[0][0] < now - self.window_size:
55
+ self.requests.popleft()
56
+
57
+ def get_current_rates(self):
58
+ now = time.time()
59
+ while self.requests and self.requests[0][0] < now - self.window_size:
60
+ self.requests.popleft()
61
+
62
+ if not self.requests:
63
+ return 0, 0
64
+
65
+ request_count = len(self.requests)
66
+ byte_count = sum(size for _, size in self.requests)
67
+
68
+ requests_per_second = request_count / self.window_size
69
+ mb_per_second = (byte_count / 1024 / 1024) / self.window_size
70
+
71
+ return round(requests_per_second, 1), round(mb_per_second, 2)
72
+
73
+ class Downloader:
74
+ def __init__(self):
75
+ self.headers = headers
76
+ self.limiter = PreciseRateLimiter(5) # 10 requests per second
77
+ self.session = None
78
+ self.parse_filings = True
79
+ self.download_queue = asyncio.Queue()
80
+ self.rate_monitor = RateMonitor()
81
+ self.current_pbar = None
82
+ self.connection_semaphore = asyncio.Semaphore(5)
83
+
84
+ def update_progress_description(self):
85
+ if self.current_pbar:
86
+ reqs_per_sec, mb_per_sec = self.rate_monitor.get_current_rates()
87
+ self.current_pbar.set_description(
88
+ f"Progress [Rate: {reqs_per_sec}/s | {mb_per_sec} MB/s]"
89
+ )
90
+
91
+ async def __aenter__(self):
92
+ await self._init_session()
93
+ return self
94
+
95
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
96
+ await self._close()
97
+
98
+ async def _init_session(self):
99
+ if not self.session:
100
+ self.session = aiohttp.ClientSession(headers=self.headers)
101
+
102
+ async def _close(self):
103
+ if self.session:
104
+ await self.session.close()
105
+ self.session = None
106
+
107
+ async def _fetch_json(self, url):
108
+ """Fetch JSON with rate monitoring."""
109
+ async with self.limiter:
110
+ try:
111
+ url = fix_filing_url(url)
112
+ async with self.session.get(url) as response:
113
+ if response.status == 429:
114
+ raise RetryException(url)
115
+ response.raise_for_status()
116
+ content = await response.read()
117
+ await self.rate_monitor.add_request(len(content))
118
+ self.update_progress_description()
119
+ return await response.json()
120
+ except aiohttp.ClientResponseError as e:
121
+ if e.status == 429:
122
+ raise RetryException(url)
123
+ raise
124
+
125
+ async def _get_filing_urls_from_efts(self, base_url):
126
+ """Fetch filing URLs from EFTS in batches."""
127
+ start = 0
128
+ page_size = 100
129
+ urls = []
130
+
131
+ data = await self._fetch_json(f"{base_url}&from=0&size=1")
132
+ if not data or 'hits' not in data:
133
+ return []
134
+
135
+ total_hits = data['hits']['total']['value']
136
+ if not total_hits:
137
+ return []
138
+
139
+ pbar = tqdm(total=total_hits, desc="Fetching URLs [Rate: 0/s | 0 MB/s]")
140
+ self.current_pbar = pbar
141
+
142
+ while start < total_hits:
143
+ try:
144
+ tasks = [
145
+ self._fetch_json(f"{base_url}&from={start + i * page_size}&size={page_size}")
146
+ for i in range(10)
147
+ ]
148
+
149
+ results = await asyncio.gather(*tasks)
150
+
151
+ for data in results:
152
+ if data and 'hits' in data:
153
+ hits = data['hits']['hits']
154
+ if hits:
155
+ batch_urls = [
156
+ f"https://www.sec.gov/Archives/edgar/data/{hit['_source']['ciks'][0]}/{hit['_id'].split(':')[0]}.txt"
157
+ for hit in hits
158
+ ]
159
+ urls.extend(batch_urls)
160
+ pbar.update(len(hits))
161
+ self.update_progress_description()
162
+
163
+ start += 10 * page_size
164
+
165
+ except RetryException as e:
166
+ print(f"\nRate limited. Sleeping for {e.retry_after} seconds...")
167
+ await asyncio.sleep(e.retry_after)
168
+ continue
169
+ except Exception as e:
170
+ print(f"\nError fetching URLs batch at {start}: {str(e)}")
171
+ break
172
+
173
+ pbar.close()
174
+ self.current_pbar = None
175
+ return urls
176
+
177
+ async def _download_file(self, url, filepath):
178
+ """Download single file with precise rate limiting."""
179
+ async with self.connection_semaphore:
180
+ async with self.limiter:
181
+ try:
182
+ url = fix_filing_url(url)
183
+ async with self.session.get(url) as response:
184
+ if response.status == 429:
185
+ raise RetryException(url)
186
+ response.raise_for_status()
187
+ content = await response.read()
188
+ await self.rate_monitor.add_request(len(content))
189
+ self.update_progress_description()
190
+
191
+ parsed_data = None
192
+ if self.parse_filings:
193
+ try:
194
+ os.makedirs(os.path.dirname(filepath), exist_ok=True)
195
+ async with aiofiles.open(filepath, 'wb') as f:
196
+ await f.write(content)
197
+
198
+ parsed_data = parse_sgml_submission(
199
+ content=content.decode(),
200
+ output_dir=os.path.dirname(filepath) + f'/{url.split("/")[-1].split(".")[0].replace("-", "")}'
201
+ )
202
+
203
+ try:
204
+ os.remove(filepath)
205
+ except Exception as e:
206
+ print(f"\nError deleting original file {filepath}: {str(e)}")
207
+
208
+ except Exception as e:
209
+ print(f"\nError parsing {url}: {str(e)}")
210
+ try:
211
+ os.remove(filepath)
212
+ parsed_dir = os.path.dirname(filepath) + f'/{url.split("/")[-1].split(".")[0].replace("-", "")}'
213
+ if os.path.exists(parsed_dir):
214
+ import shutil
215
+ shutil.rmtree(parsed_dir)
216
+ except Exception as e:
217
+ print(f"\nError cleaning up files for {url}: {str(e)}")
218
+ else:
219
+ os.makedirs(os.path.dirname(filepath), exist_ok=True)
220
+ async with aiofiles.open(filepath, 'wb') as f:
221
+ await f.write(content)
222
+
223
+ return filepath, parsed_data
224
+
225
+ except Exception as e:
226
+ print(f"\nError downloading {url}: {str(e)}")
227
+ return None
228
+
229
+ async def _download_worker(self, pbar):
230
+ """Worker to process download queue."""
231
+ while True:
232
+ try:
233
+ url, filepath = await self.download_queue.get()
234
+ result = await self._download_file(url, filepath)
235
+ if result:
236
+ pbar.update(1)
237
+ self.download_queue.task_done()
238
+ except asyncio.CancelledError:
239
+ break
240
+ except Exception as e:
241
+ print(f"\nWorker error processing {url}: {str(e)}")
242
+ self.download_queue.task_done()
243
+
244
+ async def _download_and_process(self, urls, output_dir):
245
+ """Queue-based download processing."""
246
+ results = []
247
+ parsed_results = []
248
+
249
+ pbar = tqdm(total=len(urls), desc="Downloading files [Rate: 0/s | 0 MB/s]")
250
+ self.current_pbar = pbar
251
+
252
+ for url in urls:
253
+ filename = url.split('/')[-1]
254
+ filepath = os.path.join(output_dir, filename)
255
+ await self.download_queue.put((url, filepath))
256
+
257
+ workers = [asyncio.create_task(self._download_worker(pbar))
258
+ for _ in range(5)] # Match number of workers to semaphore
259
+
260
+ await self.download_queue.join()
261
+
262
+ for worker in workers:
263
+ worker.cancel()
264
+
265
+ await asyncio.gather(*workers, return_exceptions=True)
266
+
267
+ pbar.close()
268
+ self.current_pbar = None
269
+ return results, parsed_results
270
+
271
+ def download_submissions(self, output_dir='filings', cik=None, ticker=None, submission_type=None, date=None, parse=True):
272
+ """Main method to download SEC filings."""
273
+ self.parse_filings = parse
274
+
275
+ async def _download():
276
+ async with self as downloader:
277
+ if ticker is not None:
278
+ cik_value = identifier_to_cik(ticker)
279
+ else:
280
+ cik_value = cik
281
+
282
+ params = {}
283
+ if cik_value:
284
+ if isinstance(cik_value, list):
285
+ params['ciks'] = ','.join(str(c).zfill(10) for c in cik_value)
286
+ else:
287
+ params['ciks'] = str(cik_value).zfill(10)
288
+
289
+ params['forms'] = ','.join(submission_type) if isinstance(submission_type, list) else submission_type if submission_type else "-0"
290
+
291
+ if isinstance(date, list):
292
+ dates = [(d, d) for d in date]
293
+ elif isinstance(date, tuple):
294
+ dates = [date]
295
+ else:
296
+ date_str = date if date else f"2001-01-01,{datetime.now().strftime('%Y-%m-%d')}"
297
+ start, end = date_str.split(',')
298
+ dates = [(start, end)]
299
+
300
+ all_filepaths = []
301
+ all_parsed_data = []
302
+
303
+ for start_date, end_date in dates:
304
+ params['startdt'] = start_date
305
+ params['enddt'] = end_date
306
+ base_url = "https://efts.sec.gov/LATEST/search-index"
307
+ efts_url = f"{base_url}?{urlencode(params, doseq=True)}"
308
+
309
+ urls = await self._get_filing_urls_from_efts(efts_url)
310
+ if urls:
311
+ filepaths, parsed_data = await self._download_and_process(urls, output_dir)
312
+ all_filepaths.extend(filepaths)
313
+ all_parsed_data.extend(parsed_data)
314
+
315
+ return all_filepaths, all_parsed_data
316
+
317
+ return asyncio.run(_download())
318
+
319
+ def download_company_concepts(self, output_dir='company_concepts', cik=None, ticker=None):
320
+ """Download company concept data."""
321
+ async def _download_concepts():
322
+ async with self as downloader:
323
+ if ticker is not None:
324
+ ciks = identifier_to_cik(ticker)
325
+ elif cik:
326
+ ciks = [cik] if not isinstance(cik, list) else cik
327
+ else:
328
+ company_tickers = load_package_csv('company_tickers')
329
+ ciks = [company['cik'] for company in company_tickers]
330
+
331
+ os.makedirs(output_dir, exist_ok=True)
332
+ urls = [f'https://data.sec.gov/api/xbrl/companyfacts/CIK{str(cik).zfill(10)}.json' for cik in ciks]
333
+
334
+ pbar = tqdm(total=len(urls), desc="Downloading concepts [Rate: 0/s | 0 MB/s]")
335
+ self.current_pbar = pbar
336
+
337
+ for url in urls:
338
+ filename = url.split('/')[-1]
339
+ filepath = os.path.join(output_dir, filename)
340
+ await self.download_queue.put((url, filepath))
341
+
342
+ workers = [asyncio.create_task(self._download_worker(pbar))
343
+ for _ in range(5)]
344
+
345
+ await self.download_queue.join()
346
+
347
+ for worker in workers:
348
+ worker.cancel()
349
+
350
+ await asyncio.gather(*workers, return_exceptions=True)
351
+
352
+ pbar.close()
353
+ self.current_pbar = None
354
+
355
+ results = []
356
+ for url in urls:
357
+ filename = url.split('/')[-1]
358
+ filepath = os.path.join(output_dir, filename)
359
+ if os.path.exists(filepath):
360
+ results.append(filepath)
361
+
362
+ return results
363
+
364
+ return asyncio.run(_download_concepts())