-
Notifications
You must be signed in to change notification settings - Fork 7.1k
Expand file tree
/
Copy pathkey_metrics.py
More file actions
341 lines (317 loc) · 11.5 KB
/
Copy pathkey_metrics.py
File metadata and controls
341 lines (317 loc) · 11.5 KB
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
"""YFinance Key Metrics Model."""
# pylint: disable=unused-argument
from typing import Any
from openbb_core.provider.abstract.fetcher import Fetcher
from openbb_core.provider.standard_models.key_metrics import (
KeyMetricsData,
KeyMetricsQueryParams,
)
from pydantic import Field, field_validator
class YFinanceKeyMetricsQueryParams(KeyMetricsQueryParams):
"""YFinance Key Metrics Query."""
__json_schema_extra__ = {"symbol": {"multiple_items_allowed": True}}
class YFinanceKeyMetricsData(KeyMetricsData):
"""YFinance Key Metrics Data."""
__alias_dict__ = {
"market_cap": "marketCap",
"pe_ratio": "trailingPE",
"forward_pe": "forwardPE",
"peg_ratio": "pegRatio",
"peg_ratio_ttm": "trailingPegRatio",
"eps_ttm": "trailingEps",
"eps_forward": "forwardEps",
"enterprise_to_ebitda": "enterpriseToEbitda",
"earnings_growth": "earningsGrowth",
"earnings_growth_quarterly": "earningsQuarterlyGrowth",
"revenue_per_share": "revenuePerShare",
"revenue_growth": "revenueGrowth",
"enterprise_to_revenue": "enterpriseToRevenue",
"cash_per_share": "totalCashPerShare",
"quick_ratio": "quickRatio",
"current_ratio": "currentRatio",
"debt_to_equity": "debtToEquity",
"gross_margin": "grossMargins",
"operating_margin": "operatingMargins",
"ebitda_margin": "ebitdaMargins",
"profit_margin": "profitMargins",
"return_on_assets": "returnOnAssets",
"return_on_equity": "returnOnEquity",
"dividend_yield": "dividendYield",
"dividend_yield_5y_avg": "fiveYearAvgDividendYield",
"payout_ratio": "payoutRatio",
"book_value": "bookValue",
"price_to_book": "priceToBook",
"enterprise_value": "enterpriseValue",
"overall_risk": "overallRisk",
"audit_risk": "auditRisk",
"board_risk": "boardRisk",
"compensation_risk": "compensationRisk",
"shareholder_rights_risk": "shareHolderRightsRisk",
"price_return_1y": "52WeekChange",
"currency": "financialCurrency",
}
pe_ratio: float | None = Field(
default=None,
description="Price-to-earnings ratio (TTM).",
)
forward_pe: float | None = Field(
default=None,
description="Forward price-to-earnings ratio.",
)
peg_ratio: float | None = Field(
default=None,
description="PEG ratio (5-year expected).",
)
peg_ratio_ttm: float | None = Field(
default=None,
description="PEG ratio (TTM).",
)
eps_ttm: float | None = Field(
default=None,
description="Earnings per share (TTM).",
)
eps_forward: float | None = Field(
default=None,
description="Forward earnings per share.",
)
enterprise_to_ebitda: float | None = Field(
default=None,
description="Enterprise value to EBITDA ratio.",
)
earnings_growth: float | None = Field(
default=None,
description="Earnings growth (Year Over Year), as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
earnings_growth_quarterly: float | None = Field(
default=None,
description="Quarterly earnings growth (Year Over Year), as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
revenue_per_share: float | None = Field(
default=None,
description="Revenue per share (TTM).",
)
revenue_growth: float | None = Field(
default=None,
description="Revenue growth (Year Over Year), as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
enterprise_to_revenue: float | None = Field(
default=None,
description="Enterprise value to revenue ratio.",
)
cash_per_share: float | None = Field(
default=None,
description="Cash per share.",
)
quick_ratio: float | None = Field(
default=None,
description="Quick ratio.",
)
current_ratio: float | None = Field(
default=None,
description="Current ratio.",
)
debt_to_equity: float | None = Field(
default=None,
description="Debt-to-equity ratio.",
)
gross_margin: float | None = Field(
default=None,
description="Gross margin, as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
operating_margin: float | None = Field(
default=None,
description="Operating margin, as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
ebitda_margin: float | None = Field(
default=None,
description="EBITDA margin, as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
profit_margin: float | None = Field(
default=None,
description="Profit margin, as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
return_on_assets: float | None = Field(
default=None,
description="Return on assets, as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
return_on_equity: float | None = Field(
default=None,
description="Return on equity, as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
dividend_yield: float | None = Field(
default=None,
description="Dividend yield, as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
dividend_yield_5y_avg: float | None = Field(
default=None,
description="5-year average dividend yield, as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
payout_ratio: float | None = Field(
default=None,
description="Payout ratio.",
)
book_value: float | None = Field(
default=None,
description="Book value per share.",
)
price_to_book: float | None = Field(
default=None,
description="Price-to-book ratio.",
)
enterprise_value: int | None = Field(
default=None,
description="Enterprise value.",
)
overall_risk: float | None = Field(
default=None,
description="Overall risk score.",
)
audit_risk: float | None = Field(
default=None,
description="Audit risk score.",
)
board_risk: float | None = Field(
default=None,
description="Board risk score.",
)
compensation_risk: float | None = Field(
default=None,
description="Compensation risk score.",
)
shareholder_rights_risk: float | None = Field(
default=None,
description="Shareholder rights risk score.",
)
beta: float | None = Field(
default=None,
description="Beta relative to the broad market (5-year monthly).",
)
price_return_1y: float | None = Field(
default=None,
description="One-year price return, as a normalized percent.",
json_schema_extra={"x-unit_measurement": "percent", "x-frontend_multiply": 100},
)
currency: str | None = Field(
default=None,
description="Currency in which the data is presented.",
)
@field_validator("dividend_yield_5y_avg")
@classmethod
def normalize_percent(cls, v: float):
"""Normalize the percent values."""
return float(v) / 100 if v else None
class YFinanceKeyMetricsFetcher(
Fetcher[YFinanceKeyMetricsQueryParams, list[YFinanceKeyMetricsData]]
):
"""YFinance Key Metrics fetcher."""
@staticmethod
def transform_query(params: dict[str, Any]) -> YFinanceKeyMetricsQueryParams:
"""Transform the query."""
return YFinanceKeyMetricsQueryParams(**params)
@staticmethod
async def aextract_data(
query: YFinanceKeyMetricsQueryParams,
credentials: dict[str, str] | None,
**kwargs: Any,
) -> list[dict]:
"""Extract the raw data from YFinance."""
# pylint: disable=import-outside-toplevel
import asyncio # noqa
from openbb_core.app.model.abstract.error import OpenBBError
from openbb_core.provider.utils.errors import EmptyDataError
from openbb_yfinance.utils.helpers import normalize_yfinance_symbol
from warnings import warn
from yfinance import Ticker
symbols = [s.strip() for s in query.symbol.split(",") if s.strip()]
results = []
fields = [
"symbol",
"marketCap",
"trailingPE",
"forwardPE",
"pegRatio",
"trailingPegRatio",
"earningsQuarterlyGrowth",
"earningsGrowth",
"revenuePerShare",
"revenueGrowth",
"cashPerShare",
"quickRatio",
"currentRatio",
"debtToEquity",
"grossMargins",
"ebitdaMargins",
"operatingMargins",
"profitMargins",
"returnOnAssets",
"returnOnEquity",
"dividendYield",
"fiveYearAvgDividendYield",
"payoutRatio",
"bookValue",
"priceToBook",
"enterpriseValue",
"enterpriseToRevenue",
"enterpriseToEbitda",
"overallRisk",
"auditRisk",
"boardRisk",
"compensationRisk",
"shareHolderRightsRisk",
"beta",
"52WeekChange",
"financialCurrency",
]
messages: list = []
async def get_one(symbol):
"""Get the data for one ticker symbol."""
requested_symbol = symbol.upper()
provider_symbol = normalize_yfinance_symbol(symbol)
result: dict = {}
ticker: dict = {}
try:
ticker = await asyncio.to_thread(
lambda: Ticker(provider_symbol).get_info()
)
except Exception as e:
messages.append(
f"Error getting data for {symbol} -> {e.__class__.__name__}: {e}"
)
if not ticker:
messages.append(f"No data found for {symbol}")
elif ticker:
for field in fields:
if field in ticker:
result[field] = ticker.get(field, None)
if result and result.get("52WeekChange") is not None:
result["symbol"] = requested_symbol
results.append(result)
tasks = [get_one(symbol) for symbol in symbols]
await asyncio.gather(*tasks)
if not results and not messages:
raise EmptyDataError("No data was returned for the given symbol(s).")
if not results and messages:
raise OpenBBError("\n".join(messages))
if results and messages:
for message in messages:
warn(message)
return results
@staticmethod
def transform_data(
query: YFinanceKeyMetricsQueryParams,
data: list[dict],
**kwargs: Any,
) -> list[YFinanceKeyMetricsData]:
"""Transform the data."""
return [YFinanceKeyMetricsData.model_validate(d) for d in data]