-
Notifications
You must be signed in to change notification settings - Fork 10
/
data.py
415 lines (336 loc) · 16.6 KB
/
data.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
403
404
405
406
407
408
409
410
411
412
413
414
415
"""
This module provides functions for retrieving financial data from the Financial Modeling Prep and Alpha Vantage API.
"""
# Import necessary libraries
import requests
import pandas as pd
import numpy as np
import streamlit as st
FMP_API_KEY = st.secrets["FMP_API_KEY"] # replace with your Financial Modeling Prep API key
ALPHA_API_KEY = st.secrets["ALPHA_API_KEY"] # replace with your Alpha Vantage API key
def get_company_info(symbol: str) -> dict:
"""
Returns a dictionary containing information about a company with the given stock symbol.
Parameters:
symbol (str): Stock symbol
Returns:
dict: Dictionary containing information about the company
"""
# Set the API endpoint URL
api_endpoint = f'https://financialmodelingprep.com/api/v3/profile/{symbol}/'
params = {
'apikey': FMP_API_KEY,
}
try:
# Make an HTTP GET request to the API with the specified parameters
response = requests.get(api_endpoint, params=params)
# Check for any errors in the HTTP response status code
response.raise_for_status()
# Convert the response data to a Python dictionary
data = response.json()
# Extract the first (and only) item from the list of company data
data = data[0]
# Extract the desired company information from the dictionary
company_info = {
'Name': data['companyName'],
'Exchange': data['exchangeShortName'],
'Currency': data['currency'],
'Country': data['country'],
'Sector': data['sector'],
'Market Cap': data['mktCap'],
'Price': data['price'],
'Beta': data['beta'],
'Price change': data['changes'],
'Website': data['website'],
'Image': data['image']
}
# Return the company information dictionary
return company_info
except requests.exceptions.RequestException as e:
# Handle any errors that occur while making the API request
print(f"Error occurred while fetching data from API: {e}")
return None
except ValueError as e:
# Handle any errors that occur while parsing the response data
print(f"Error occurred while parsing JSON response: {e}")
return None
def get_stock_price(symbol: str) -> pd.DataFrame:
"""
Returns a Pandas DataFrame containing the monthly adjusted closing prices of a given stock symbol
for the last 5 years.
Parameters:
symbol (str): Stock symbol
Returns:
pd.DataFrame: Pandas DataFrame containing the monthly adjusted closing prices of the stock
"""
api_endpoint = 'https://www.alphavantage.co/query'
params = {
'function': 'TIME_SERIES_MONTHLY_ADJUSTED',
'symbol': symbol,
'apikey': ALPHA_API_KEY,
}
try:
# Make an HTTP GET request to the API
response = requests.get(api_endpoint, params=params)
response.raise_for_status() # raise exception for any bad HTTP status code
# Parse the response JSON data into a Pandas DataFrame
data = response.json()['Monthly Adjusted Time Series']
df = pd.DataFrame.from_dict(data, orient='index')
df.index = pd.to_datetime(df.index)
df = df[:12*5] # get data for the last 5 years
df = df[['4. close']].astype(float)
df = df.rename(columns={'4. close': 'Price'})
return df
except requests.exceptions.RequestException as e:
print(f"Error occurred while fetching data from API: {e}")
return None
except ValueError as e:
print(f"Error occurred while parsing JSON response: {e}")
return None
def get_income_statement(symbol: str) -> pd.DataFrame:
"""
Retrieves the income statement data for a given stock symbol from the Financial Modeling Prep API.
Args:
symbol (str): The stock symbol to retrieve the income statement data for.
Returns:
pd.DataFrame: A Pandas DataFrame containing the income statement data.
"""
# define the API endpoint and parameters
api_endpoint = f'https://financialmodelingprep.com/api/v3/income-statement/{symbol}/'
params = {
'limit': 5,
'apikey': FMP_API_KEY,
}
try:
# create an empty list to store the income statement data
income_statement_data = []
# make an HTTP GET request to the API
response = requests.get(api_endpoint, params=params)
response.raise_for_status() # raise exception for any bad HTTP status code
# parse the response JSON data into a list of dictionaries
response_data = response.json()
# extract the income statement data from the list of dictionaries
for report in response_data:
year = report['calendarYear']
income_statement_data.append({
'Year': year,
'Revenue': (report['revenue']),
'(-) Cost of Revenue': (report['costOfRevenue']),
'= Gross Profit': (report['grossProfit']),
'(-) Operating Expense': (report['operatingExpenses']),
'= Operating Income': (report['operatingIncome']),
'(+-) Other Income/Expenses': (report['totalOtherIncomeExpensesNet']),
'= Income Before Tax': (report['incomeBeforeTax']),
'(+-) Tax Income/Expense': (report['incomeTaxExpense']),
'= Net Income': (report['netIncome']),
})
# create a Pandas DataFrame from the list of dictionaries and return it
income_statement = pd.DataFrame(income_statement_data).set_index('Year')
return income_statement
except requests.exceptions.RequestException as e:
print(f"Error occurred while fetching data from API: {e}")
return None
except ValueError as e:
print(f"Error occurred while parsing JSON response: {e}")
return None
def get_balance_sheet(symbol: str) -> pd.DataFrame:
"""
Retrieves the balance sheet data for a given stock symbol.
Args:
symbol (str): Stock symbol to retrieve balance sheet data for.
Returns:
pd.DataFrame: Pandas DataFrame containing the balance sheet data.
"""
# Define the API endpoint and parameters
api_endpoint = f'https://financialmodelingprep.com/api/v3/balance-sheet-statement/{symbol}'
params = {
'limit': 5,
'apikey': FMP_API_KEY,
}
try:
# Create an empty list to store the balance sheet data
balance_sheet_data = []
# Make an HTTP GET request to the API
response = requests.get(api_endpoint, params=params)
response.raise_for_status() # Raise exception for any bad HTTP status code
# Parse the response JSON data into a list of dictionaries
response_data = response.json()
# Extract the balance sheet data from the list of dictionaries
for report in response_data:
year = report['calendarYear']
balance_sheet_data.append({
'Year': year,
'Assets': report['totalAssets'],
'Current Assets': report['totalCurrentAssets'],
'Non-Current Assets': report['totalNonCurrentAssets'],
'Current Liabilities': report['totalCurrentLiabilities'],
'Non-Current Liabilities': report['totalNonCurrentLiabilities'],
'Liabilities': report['totalLiabilities'],
'Equity': report['totalEquity']
})
# Create a Pandas DataFrame from the list of dictionaries and return it
balance_sheet_df = pd.DataFrame(balance_sheet_data).set_index('Year')
return balance_sheet_df
except requests.exceptions.RequestException as e:
# If an error occurs, print the error message and return None
print('Error getting balance sheet data:', e)
return None
def get_cash_flow(symbol: str) -> pd.DataFrame:
"""
Retrieve cash flow data for a given stock symbol from the Financial Modeling Prep API.
Args:
symbol (str): The stock symbol for the company.
Returns:
pd.DataFrame: A Pandas DataFrame containing cash flow data for the company.
"""
# Define the API endpoint and parameters
api_endpoint = f'https://financialmodelingprep.com/api/v3/cash-flow-statement/{symbol}'
params = {
'limit': 5,
'apikey': FMP_API_KEY,
}
try:
# Create an empty list to store the cash flow data
cashflow_data = []
# Make an HTTP GET request to the API
response = requests.get(api_endpoint, params=params)
response.raise_for_status() # Raise an exception for any bad HTTP status code
# Parse the response JSON data into a list of dictionaries
response_data = response.json()
# Extract the cash flow data from the list of dictionaries
for report in response_data:
year = report['date'].split('-')[0]
cashflow_data.append({
'Year': year,
"Cash flows from operating activities": report['netCashProvidedByOperatingActivities'],
'Cash flows from investing activities': report['netCashUsedForInvestingActivites'],
'Cash flows from financing activities': report['netCashUsedProvidedByFinancingActivities'],
'Free cash flow': report['freeCashFlow']
})
# Create a Pandas DataFrame from the list of dictionaries and set the 'Year' column as the index
cashflow_df = pd.DataFrame(cashflow_data).set_index('Year')
return cashflow_df
except requests.exceptions.RequestException as e:
# If an error occurs, print the error message and return None
print('Error getting cash flow data:', e)
return None
def get_key_metrics(symbol: str) -> pd.DataFrame:
"""
Returns a Pandas DataFrame containing the key financial metrics of a given company symbol for the last 10 years.
Parameters:
symbol (str): Company symbol.
Returns:
pd.DataFrame: Pandas DataFrame containing the key financial metrics.
"""
# Define the API endpoint and parameters.
api_endpoint = f'https://financialmodelingprep.com/api/v3/key-metrics/{symbol}'
params = {
'limit': 5, # Get data for the last 10 years.
'apikey': FMP_API_KEY,
}
try:
# Create an empty list to store the ratios data.
metrics_data = []
# Make an HTTP GET request to the API.
response = requests.get(api_endpoint, params=params)
response.raise_for_status() # Raise exception for any bad HTTP status code.
# Parse the response JSON data into a list of dictionaries.
response_data = response.json()
# Extract the ratios data from the list of dictionaries.
for report in response_data:
year = report['date'].split('-')[0] # Extract the year from the date string.
metrics_data.append({
'Year': year,
"Market Cap": report['marketCap'],
'Working Capital': report['workingCapital'],
'D/E ratio': report['debtToEquity'],
'P/E Ratio': report['peRatio'],
'ROE': report['roe'],
'Dividend Yield': report['dividendYield']
})
# Create a Pandas DataFrame from the list of dictionaries and return it.
metrics_df = pd.DataFrame(metrics_data).set_index('Year')
return metrics_df
except requests.exceptions.RequestException as e:
# If an error occurs, print the error message and return None.
print(f"Error occurred while fetching data from API: {e}")
return None
def get_financial_ratios(symbol: str) -> pd.DataFrame:
"""
Fetches financial ratios for a given stock symbol using the Financial Modeling Prep API.
Parameters:
symbol (str): The stock symbol to fetch the ratios for.
Returns:
pandas.DataFrame: A DataFrame containing the financial ratios data.
"""
# Define the API endpoint and parameters
api_endpoint = f'https://financialmodelingprep.com/api/v3/ratios/{symbol}'
params = {
'limit': 5,
'apikey': FMP_API_KEY,
}
try:
# Create an empty list to store the ratios data
ratios_data = []
# Make an HTTP GET request to the API
response = requests.get(api_endpoint, params=params)
response.raise_for_status() # Raise exception for any bad HTTP status code
# Parse the response JSON data into a list of dictionaries
response_data = response.json()
# Extract the ratios data from the list of dictionaries
for report in response_data:
year = report['date'].split('-')[0]
ratios_data.append({
'Year': year,
'Current Ratio': report['currentRatio'],
'Quick Ratio': report['quickRatio'],
'Cash Ratio': report['cashRatio'],
'Days of Sales Outstanding': report['daysOfSalesOutstanding'],
'Days of Inventory Outstanding': report['daysOfInventoryOutstanding'],
'Operating Cycle': report['operatingCycle'],
'Days of Payables Outstanding': report['daysOfPayablesOutstanding'],
'Cash Conversion Cycle': report['cashConversionCycle'],
'Gross Profit Margin': report['grossProfitMargin'],
'Operating Profit Margin': report['operatingProfitMargin'],
'Pretax Profit Margin': report['pretaxProfitMargin'],
'Net Profit Margin': report['netProfitMargin'],
'Effective Tax Rate': report['effectiveTaxRate'],
'Return on Assets': report['returnOnAssets'],
'Return on Equity': report['returnOnEquity'],
'Return on Capital Employed': report['returnOnCapitalEmployed'],
'Net Income per EBT': report['netIncomePerEBT'],
'EBT per EBIT': report['ebtPerEbit'],
'EBIT per Revenue': report['ebitPerRevenue'],
'Debt Ratio': report['debtRatio'],
'Debt Equity Ratio': report['debtEquityRatio'],
'Long-term Debt to Capitalization': report['longTermDebtToCapitalization'],
'Total Debt to Capitalization': report['totalDebtToCapitalization'],
'Interest Coverage': report['interestCoverage'],
'Cash Flow to Debt Ratio': report['cashFlowToDebtRatio'],
'Company Equity Multiplier': report['companyEquityMultiplier'],
'Receivables Turnover': report['receivablesTurnover'],
'Payables Turnover': report['payablesTurnover'],
'Inventory Turnover': report['inventoryTurnover'],
'Fixed Asset Turnover': report['fixedAssetTurnover'],
'Asset Turnover': report['assetTurnover'],
'Operating Cash Flow per Share': report['operatingCashFlowPerShare'],
'Free Cash Flow per Share': report['freeCashFlowPerShare'],
'Cash per Share': report['cashPerShare'],
'Payout Ratio': report['payoutRatio'],
'Operating Cash Flow Sales Ratio': report['operatingCashFlowSalesRatio'],
'Free Cash Flow Operating Cash Flow Ratio': report['freeCashFlowOperatingCashFlowRatio'],
'Cash Flow Coverage Ratios': report['cashFlowCoverageRatios'],
'Price to Book Value Ratio': report['priceToBookRatio'],
'Price to Earnings Ratio': report['priceEarningsRatio'],
'Price to Sales Ratio': report['priceToSalesRatio'],
'Dividend Yield': report['dividendYield'],
'Enterprise Value to EBITDA': report['enterpriseValueMultiple'],
'Price to Fair Value': report['priceFairValue']
})
# Create a Pandas DataFrame from the list of dictionaries and return it
ratios_df = pd.DataFrame(ratios_data).set_index('Year')
return ratios_df
except requests.exceptions.RequestException as e:
# If an error occurs, print the error message and return None
print('Error getting ratios data:', e)
return None