-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathsimfin.py
182 lines (169 loc) · 6.69 KB
/
simfin.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
import json
import requests
class SimFin:
def __init__(self, api_key):
self.url = "https://backend.simfin.com/api/v3"
self.api_key = api_key
def _extract_financial_data(self, json_data):
if not json_data or not json_data[0] or not json_data[0]["statements"]:
raise Exception("No data found")
data = json_data[0]["statements"][0]['data'][0]
extracted_data = {}
columns = json_data[0]["statements"][0]['columns']
for index, key in enumerate(columns):
extracted_data[key] = data[index]
return extracted_data
def _get_company_statements(self, ticker, statement, fyear, period):
headers = {
"Authorization": f"api-key {self.api_key}",
"Accept": "application/json",
}
params = {
"ticker": ticker,
"statements": statement,
"fyear": fyear,
"period": period,
}
response = requests.get(f"{self.url}/companies/statements/compact", headers=headers, params=params)
if response.status_code != 200:
raise Exception(
f"Request failed with status code: {response.status_code}, response: {response.text}"
)
return response.json()
def _build_summary_json(self, extracted_data, categories):
summary_json = {}
for category, keys in categories.items():
summary_json[category] = {}
for key in keys:
value = extracted_data.get(key)
if value is None:
formatted_value = "N/A"
elif isinstance(value, (int, float)):
formatted_value = f"{value:,}"
else:
formatted_value = value
summary_json[category][key] = formatted_value
return summary_json
def get_derived(self, ticker, fyear, period):
data = self._get_company_statements(ticker, "derived", fyear, period)
extracted_data = self._extract_financial_data(data)
column_map = {
"Profitability Metrics": [
"EBITDA",
"Gross Profit Margin",
"Operating Margin",
"Net Profit Margin",
"Return on Equity",
"Return on Assets",
"Return On Invested Capital",
],
"Liquidity Metrics": ["Current Ratio"],
"Solvency Metrics": [
"Total Debt",
"Liabilities to Equity Ratio",
"Debt Ratio",
],
"Cash Flow Metrics": [
"Free Cash Flow",
"Free Cash Flow to Net Income",
"Cash Return On Invested Capital",
],
"Other Important Metrics": [
"Piotroski F-Score",
"Net Debt / EBITDA",
"Dividend Payout Ratio",
],
"Metadata": ["Report Date"],
}
summary_json = self._build_summary_json(extracted_data, column_map)
return summary_json
def get_cash_flow(self, ticker, fyear, period):
data = self._get_company_statements(ticker, "cf", fyear, period)
extracted_data = self._extract_financial_data(data)
column_map = {
"Operating Activities": [
"Change in Working Capital",
"Net Cash from Operating Activities",
],
"Investing Activities": [
"Acquisition of Fixed Assets & Intangibles",
"Net Cash from Investing Activities",
],
"Financing Activities": [
"Dividends Paid",
"Cash from (Repayment of) Debt",
"Net Cash from Financing Activities",
],
"Net Change": ["Net Change in Cash"],
"Metadata": ["Report Date", "Publish Date", "Source"],
}
summary_json = self._build_summary_json(extracted_data, column_map)
return summary_json
def get_profit_loss(self, ticker, fyear, period):
data = self._get_company_statements(ticker, "pl", fyear, period)
extracted_data = self._extract_financial_data(data)
categories = {
"Income": ["Revenue", "Gross Profit"],
"Expenses": [
"Operating Expenses",
],
"Profitability": ["Operating Income (Loss)", "Pretax Income (Loss)"],
"Metadata": ["Report Date", "Publish Date", "Source"],
}
summary_json = self._build_summary_json(extracted_data, categories)
return summary_json
def get_balance_sheet(self, ticker, fyear, period):
data = self._get_company_statements(ticker, "bs", fyear, period)
extracted_data = self._extract_financial_data(data)
categories = {
"Assets": [
"Cash, Cash Equivalents & Short Term Investments",
"Accounts & Notes Receivable",
"Inventories",
"Other Short Term Assets",
"Total Current Assets",
"Total Noncurrent Assets",
"Total Assets",
],
"Liabilities": [
"Accounts Payable",
"Short Term Debt",
"Total Current Liabilities",
"Long Term Debt",
"Total Noncurrent Liabilities",
"Total Liabilities",
],
"Equity": [
"Common Stock",
"Retained Earnings",
"Total Equity",
],
"Summary": ["Total Liabilities & Equity"],
"Metadata": ["Report Date", "Publish Date", "Source"],
}
summary_json = self._build_summary_json(extracted_data, categories)
return summary_json
def get_financials(self, ticker, fyear, period):
balance_json = self.get_balance_sheet(ticker, fyear, period)
cash_flow_json = self.get_cash_flow(ticker, fyear, period)
derived_json = self.get_derived(ticker, fyear, period)
profit_loss_json = self.get_profit_loss(ticker, fyear, period)
return (
balance_json,
cash_flow_json,
derived_json,
profit_loss_json,
)
def get_financial_info_text(self, ticker: str, fyear: str, period: str):
(
balance_json,
cash_flow_json,
derived_json,
profit_loss_json,
) = self.get_financials(ticker=ticker, fyear=fyear, period=period)
return f"\
{json.dumps(balance_json, indent=4)}\
{json.dumps(cash_flow_json, indent=4)}\
{json.dumps(derived_json, indent=4)}\
{json.dumps(profit_loss_json, indent=4)}\
"