pschofield2 commited on
Commit
3684aa1
·
verified ·
1 Parent(s): 5a5a4d9

Delete fmp_assistant_functions.py

Browse files
Files changed (1) hide show
  1. fmp_assistant_functions.py +0 -554
fmp_assistant_functions.py DELETED
@@ -1,554 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """fmp_data_functions.ipynb
3
-
4
- Automatically generated by Colab.
5
-
6
- Original file is located at
7
- https://colab.research.google.com/drive/1KsEvO8hhA8ueVCejK_Lg3DSI6hd5SPvI
8
- """
9
-
10
- import requests
11
- import json
12
- from google.colab import userdata
13
- import pandas as pd
14
- from urllib.parse import urlencode
15
- import os
16
-
17
- # Define base URL and API key
18
- BASE_URL = "https://financialmodelingprep.com/api/v3"
19
- os.environ['FMP_API_KEY'] = userdata.get('FMP_API_KEY')
20
-
21
- def handle_response(response):
22
- if response.status_code == 200:
23
- return response.json()
24
- else:
25
- return {"error": f"Failed to fetch data. Status code: {response.status_code}"}
26
-
27
- def get_income_statement(ticker, period='annual', limit=5):
28
- """
29
- Fetches the income statement for a given company (ticker) over a specified period and with a limit on the number of records returned.
30
-
31
- Parameters:
32
- -----------
33
- ticker : str
34
- The stock symbol or CIK (Central Index Key) for the company (e.g., 'AAPL' for Apple or '0000320193' for its CIK).
35
-
36
- period : str, optional
37
- The reporting period for the income statement. Allowable values are:
38
- - 'annual' : Retrieves the annual income statement (default).
39
- - 'quarter' : Retrieves the quarterly income statement.
40
-
41
- limit : int, optional
42
- Limits the number of records returned. The default value is 5.
43
-
44
- Returns:
45
- --------
46
- dict or list of dict
47
- The income statement data, including fields like date, symbol, reported currency, filing date, etc.
48
-
49
- Example:
50
- --------
51
- get_income_statement('AAPL', period='annual', limit=5)
52
-
53
- Response format:
54
- ----------------
55
- [
56
- {
57
- "date": "2022-09-24",
58
- "symbol": "AAPL",
59
- "reportedCurrency": "USD",
60
- "cik": "0000320193",
61
- "fillingDate": "2022-10-28",
62
- "acceptedDate": "2022-10-27 18:01:14",
63
- ...
64
- },
65
- ...
66
- ]
67
- """
68
- params = {
69
- "period": period, # Accepts 'annual' or 'quarter'
70
- "limit": limit, # Limits the number of records returned
71
- "apikey": os.environ['FMP_API_KEY'] # API Key for authentication
72
- }
73
-
74
- # Construct the full URL with query parameters
75
- endpoint = f"{BASE_URL}/income-statement/{ticker}?{urlencode(params)}"
76
-
77
- response = requests.get(endpoint)
78
- return handle_response(response)
79
-
80
- def ticker_search(query, limit=10, exchange='NYSE'):
81
- """
82
- Searches for ticker symbols and exchanges for both equity securities and exchange-traded funds (ETFs)
83
- by searching with the company name or ticker symbol.
84
-
85
- Parameters:
86
- -----------
87
- query : str
88
- The name or ticker symbol to search for (e.g., 'AA' for Alcoa).
89
-
90
- limit : int, optional
91
- Limits the number of records returned. The default is 10.
92
-
93
- exchange : str, optional
94
- Specifies the exchange to filter results by. Allowable values include:
95
- - 'NYSE' : New York Stock Exchange (default).
96
- - 'NASDAQ' : NASDAQ Exchange.
97
- - Other exchange codes supported by the API.
98
-
99
- Returns:
100
- --------
101
- dict or list of dict
102
- The search results, including the symbol, name, currency, stock exchange, and exchange short name.
103
-
104
- Example:
105
- --------
106
- ticker_search('AA', limit=10, exchange='NASDAQ')
107
-
108
- Response format:
109
- ----------------
110
- [
111
- {
112
- "symbol": "PRAA",
113
- "name": "PRA Group, Inc.",
114
- "currency": "USD",
115
- "stockExchange": "NasdaqGS",
116
- "exchangeShortName": "NASDAQ"
117
- },
118
- {
119
- "symbol": "PAAS",
120
- "name": "Pan American Silver Corp.",
121
- "currency": "USD",
122
- "stockExchange": "NasdaqGS",
123
- "exchangeShortName": "NASDAQ"
124
- },
125
- ...
126
- ]
127
- """
128
- params = {
129
- "limit": limit,
130
- "exchange": exchange,
131
- "apikey": os.environ['FMP_API_KEY']
132
- }
133
-
134
- endpoint = f"{BASE_URL}/search?query={query}&{urlencode(params)}"
135
- response = requests.get(endpoint)
136
- return handle_response(response)
137
-
138
- def company_profile(symbol):
139
- """
140
- Fetches a company's profile, including key stats such as price, market capitalization, beta, and other essential details.
141
-
142
- Parameters:
143
- -----------
144
- symbol : str
145
- The stock ticker symbol or CIK (Central Index Key) for the company (e.g., 'AAPL' for Apple).
146
-
147
- Returns:
148
- --------
149
- dict or list of dict
150
- The company's profile data, including fields such as symbol, price, beta, market cap, industry, CEO, and description.
151
-
152
- Example:
153
- --------
154
- company_profile('AAPL')
155
-
156
- Response format:
157
- ----------------
158
- [
159
- {
160
- "symbol": "AAPL",
161
- "price": 145.30,
162
- "beta": 1.25,
163
- "volAvg": 98364732,
164
- "mktCap": 2423446000000,
165
- "lastDiv": 0.88,
166
- "range": "122.25-157.33",
167
- "changes": -2.00,
168
- "companyName": "Apple Inc.",
169
- "currency": "USD",
170
- "cik": "0000320193",
171
- "isin": "US0378331005",
172
- "cusip": "037833100",
173
- "exchange": "NasdaqGS",
174
- "exchangeShortName": "NASDAQ",
175
- "industry": "Consumer Electronics",
176
- "website": "https://www.apple.com",
177
- "description": "Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide."
178
- }
179
- ]
180
- """
181
- params = {
182
- 'apikey': os.environ['FMP_API_KEY']
183
- }
184
-
185
- endpoint = f"{BASE_URL}/profile/{symbol}?{urlencode(params)}"
186
- response = requests.get(endpoint)
187
- return handle_response(response)
188
-
189
- def stock_grade(symbol, limit = 500):
190
-
191
- params = {
192
- 'apikey':os.environ['FMP_API_KEY'],
193
- 'limit':limit
194
- }
195
-
196
- endpoint = f"{BASE_URL}/grade/{symbol}?{urlencode(params)}"
197
- response = requests.get(endpoint)
198
- return handle_response(response)
199
-
200
- def current_market_cap(symbol):
201
- """
202
- Fetches the current market capitalization of a given company based on its stock symbol.
203
-
204
- Parameters:
205
- -----------
206
- symbol : str
207
- The stock ticker symbol for the company (e.g., 'AAPL' for Apple).
208
-
209
- Returns:
210
- --------
211
- dict or list of dict
212
- The market capitalization data, including fields such as symbol, date, and market cap.
213
-
214
- Example:
215
- --------
216
- current_market_cap('AAPL')
217
-
218
- Response format:
219
- ----------------
220
- [
221
- {
222
- "symbol": "AAPL",
223
- "date": "2023-03-02",
224
- "marketCap": 2309048053309
225
- }
226
- ]
227
- """
228
- params = {
229
- 'apikey': os.environ['FMP_API_KEY']
230
- }
231
-
232
- endpoint = f"{BASE_URL}/market-capitalization/{symbol}?{urlencode(params)}"
233
- response = requests.get(endpoint)
234
- return handle_response(response)
235
-
236
- def historical_market_cap(symbol, from_date=None, to_date=None, limit=None):
237
- """
238
- Fetches the historical market capitalization of a given company within a specified date range.
239
-
240
- Parameters:
241
- -----------
242
- symbol : str
243
- The stock ticker symbol for the company (e.g., 'AAPL' for Apple).
244
-
245
- from_date : str, optional
246
- The start date for the historical data in 'YYYY-MM-DD' format (e.g., '2023-10-10').
247
- Default is None, which fetches data from the earliest available date.
248
-
249
- to_date : str, optional
250
- The end date for the historical data in 'YYYY-MM-DD' format (e.g., '2023-12-10').
251
- Default is None, which fetches data up to the latest available date.
252
-
253
- limit : int, optional
254
- Limits the number of records returned. Default is None, which fetches all available records.
255
-
256
- Returns:
257
- --------
258
- dict or list of dict
259
- The historical market cap data, including fields such as symbol, date, and market capitalization.
260
-
261
- Example:
262
- --------
263
- historical_market_cap('AAPL', from_date='2023-10-10', to_date='2023-12-10', limit=100)
264
-
265
- Response format:
266
- ----------------
267
- [
268
- {
269
- "symbol": "AAPL",
270
- "date": "2023-03-02",
271
- "marketCap": 2313794623242
272
- }
273
- ]
274
- """
275
- params = {
276
- 'apikey': os.environ['FMP_API_KEY'],
277
- 'from': from_date,
278
- 'to': to_date,
279
- 'limit': limit
280
- }
281
-
282
- endpoint = f"{BASE_URL}/historical-market-capitalization/{symbol}?{urlencode(params)}"
283
- response = requests.get(endpoint)
284
- return handle_response(response)
285
-
286
- def analyst_recommendations(symbol):
287
- """
288
- Fetches the analyst recommendations for a given company based on its stock symbol.
289
- This includes buy, hold, and sell ratings.
290
-
291
- Parameters:
292
- -----------
293
- symbol : str
294
- The stock ticker symbol for the company (e.g., 'AAPL' for Apple).
295
-
296
- Returns:
297
- --------
298
- dict or list of dict
299
- The analyst recommendation data, including fields such as buy, hold, sell, and strong buy ratings.
300
-
301
- Example:
302
- --------
303
- analyst_recommendations('AAPL')
304
-
305
- Response format:
306
- ----------------
307
- [
308
- {
309
- "symbol": "AAPL",
310
- "date": "2023-08-01",
311
- "analystRatingsBuy": 21,
312
- "analystRatingsHold": 6,
313
- "analystRatingsSell": 0,
314
- "analystRatingsStrongSell": 0,
315
- "analystRatingsStrongBuy": 11
316
- }
317
- ]
318
- """
319
- params = {
320
- 'apikey': os.environ['FMP_API_KEY']
321
- }
322
-
323
- endpoint = f"{BASE_URL}/analyst-stock-recommendations/{symbol}?{urlencode(params)}"
324
- response = requests.get(endpoint)
325
- return handle_response(response)
326
-
327
- def stock_peers(symbol):
328
- """
329
- Fetches a list of companies that are considered peers of the given company.
330
- These peers are companies that trade on the same exchange, are in the same sector,
331
- and have a similar market capitalization.
332
-
333
- Parameters:
334
- -----------
335
- symbol : str
336
- The stock ticker symbol for the company (e.g., 'AAPL' for Apple).
337
-
338
- Returns:
339
- --------
340
- dict or list of dict
341
- The peers data, including a list of peer company ticker symbols.
342
-
343
- Example:
344
- --------
345
- stock_peers('AAPL')
346
-
347
- Response format:
348
- ----------------
349
- [
350
- {
351
- "symbol": "AAPL",
352
- "peersList": [
353
- "LPL",
354
- "SNEJF",
355
- "PCRFY",
356
- "SONO",
357
- "VZIO",
358
- ...
359
- ]
360
- }
361
- ]
362
- """
363
- params = {
364
- 'apikey': os.environ['FMP_API_KEY'],
365
- 'symbol': symbol
366
- }
367
-
368
- BASE_URL = "https://financialmodelingprep.com/api/v4"
369
- endpoint = f"{BASE_URL}/stock_peers?{urlencode(params)}"
370
- response = requests.get(endpoint)
371
- return handle_response(response)
372
-
373
- def earnings_historical_and_upcoming(symbol, limit=100):
374
- """
375
- Fetches historical and upcoming earnings announcements for a given company.
376
- The response includes the date, EPS (earnings per share), estimated EPS, revenue, and estimated revenue.
377
-
378
- Parameters:
379
- -----------
380
- symbol : str
381
- The stock ticker symbol for the company (e.g., 'AAPL' for Apple).
382
-
383
- limit : int, optional
384
- Limits the number of records returned. The default is 100.
385
-
386
- Returns:
387
- --------
388
- dict or list of dict
389
- The earnings data, including fields such as date, EPS, estimated EPS, revenue, and estimated revenue.
390
-
391
- Example:
392
- --------
393
- earnings_historical_and_upcoming('AAPL', limit=100)
394
-
395
- Response format:
396
- ----------------
397
- [
398
- {
399
- "date": "1998-10-14",
400
- "symbol": "AAPL",
401
- "eps": 0.0055,
402
- "epsEstimated": 0.00393,
403
- "time": "amc",
404
- "revenue": 1556000000,
405
- "revenueEstimated": 2450700000,
406
- "updatedFromDate": "2023-12-04",
407
- "fiscalDateEnding": "1998-09-25"
408
- }
409
- ]
410
- """
411
- params = {
412
- 'apikey': os.environ['FMP_API_KEY'],
413
- 'limit': limit
414
- }
415
-
416
- endpoint = f"{BASE_URL}/historical/earning_calendar/{symbol}?{urlencode(params)}"
417
- response = requests.get(endpoint)
418
- return handle_response(response)
419
-
420
- def intraday_stock_prices(timeframe, symbol, from_date=None, to_date=None, extended='false'):
421
- """
422
- Fetches the historical intraday stock price for a given company over a specified timeframe.
423
-
424
- Parameters:
425
- -----------
426
- timeframe : str
427
- The time interval for the stock data. Allowable values are:
428
- - '1min' : 1 minute interval
429
- - '5min' : 5 minute interval
430
- - '15min' : 15 minute interval
431
- - '30min' : 30 minute interval
432
- - '1hour' : 1 hour interval
433
- - '4hour' : 4 hour interval
434
-
435
- symbol : str
436
- The stock symbol for which to retrieve the data (e.g., 'AAPL' for Apple).
437
-
438
- from_date : str, optional
439
- The start date for the historical data in 'YYYY-MM-DD' format (e.g., '2023-08-10').
440
- Default is None, which fetches all available data up to the present.
441
-
442
- to_date : str, optional
443
- The end date for the historical data in 'YYYY-MM-DD' format (e.g., '2023-09-10').
444
- Default is None, which fetches data from the beginning up to the current date.
445
-
446
- extended : str, optional
447
- Whether to fetch extended market data (pre-market and after-hours).
448
- Allowable values:
449
- - 'true' : Fetch extended market data
450
- - 'false' : Fetch only regular market hours data (default).
451
-
452
- Returns:
453
- --------
454
- dict or list of dict
455
- The historical intraday stock data, including open, high, low, close, and volume for each time interval.
456
-
457
- Example:
458
- --------
459
- intraday_stock_price('5min', 'AAPL', from_date='2023-08-10', to_date='2023-09-10', extended='false')
460
-
461
- Response format:
462
- ----------------
463
- [
464
- {
465
- "date": "2023-03-02 16:00:00",
466
- "open": 145.92,
467
- "low": 145.72,
468
- "high": 146.00,
469
- "close": 145.79,
470
- "volume": 1492644
471
- },
472
- ...
473
- ]
474
- """
475
- params = {
476
- 'apikey': os.environ['FMP_API_KEY'],
477
- 'from': from_date,
478
- 'to': to_date,
479
- 'extended': extended
480
- }
481
-
482
- endpoint = f"{BASE_URL}/historical-chart/{timeframe}/{symbol}?{urlencode(params)}"
483
- response = requests.get(endpoint)
484
- return handle_response(response)
485
-
486
-
487
- intraday_stock_prices('5min','AAPL','2024-09-30')
488
-
489
- def daily_stock_prices(symbol, from_date=None, to_date=None, serietype='line'):
490
- """
491
- Fetches the daily End-Of-Day (EOD) stock price for a given company over a specified date range.
492
-
493
- Parameters:
494
- -----------
495
- symbol : str
496
- The stock symbol for which to retrieve the data (e.g., 'AAPL' for Apple).
497
-
498
- from_date : str, optional
499
- The start date for the historical data in 'YYYY-MM-DD' format (e.g., '1990-10-10').
500
- Default is None, which fetches the earliest available data.
501
-
502
- to_date : str, optional
503
- The end date for the historical data in 'YYYY-MM-DD' format (e.g., '2023-10-10').
504
- Default is None, which fetches data up to the most recent date.
505
-
506
- serietype : str, optional
507
- The type of data series to return. Allowable values are:
508
- - 'line' : Line chart data (default).
509
- - 'other types' can be specified if supported by the API in the future.
510
-
511
- Returns:
512
- --------
513
- dict or list of dict
514
- The daily stock data, including open, high, low, close, volume, adjusted close, etc.
515
-
516
- Example:
517
- --------
518
- daily_stock_price('AAPL', from_date='1990-10-10', to_date='2023-10-10', serietype='line')
519
-
520
- Response format:
521
- ----------------
522
- {
523
- "symbol": "AAPL",
524
- "historical": [
525
- {
526
- "date": "2023-10-06",
527
- "open": 173.8,
528
- "high": 176.61,
529
- "low": 173.18,
530
- "close": 176.53,
531
- "adjClose": 176.53,
532
- "volume": 21712747,
533
- "unadjustedVolume": 21712747,
534
- "change": 2.73,
535
- "changePercent": 1.57077,
536
- "vwap": 175.44,
537
- "label": "October 06, 23",
538
- "changeOverTime": 0.0157077
539
- },
540
- ...
541
- ]
542
- }
543
- """
544
- params = {
545
- 'apikey': os.environ['FMP_API_KEY'],
546
- 'from': from_date,
547
- 'to': to_date,
548
- 'serietype': serietype
549
- }
550
-
551
- endpoint = f"{BASE_URL}/historical-price-full/{symbol}?{urlencode(params)}"
552
- response = requests.get(endpoint)
553
- return handle_response(response)
554
-