Files
OpenBB/openbb_terminal/stocks/fundamental_analysis/polygon_model.py
montezdesousa 475ebb5acd [WIP] Migrate user, feature flags and configurations to dataclass (#4309)
* implement user and change is guest

* replace User methods

* move remaining functions to user

* fix bug

* portfolio test

* fix tests

* fix tests

* uncomment skip

* ruff

* start credentials model implementation

* change deault structure

* refacto quandl

* change default struct and file names

* bug

* start using global user

* add comments

* move update flair

* change cfg references in keys model

* reddit & fmp

* refactore additional keys

* remaing config keys

* remove unsude imports and fix hub keys

* ruff

* fix line too long

* unblock unittests

* fix keys model tests

* remove os patch

* fix account controller tests

* fix account controller tests

* fix account model

* account fixed

* fix user tests

* User Model

* User Model

* User Model

* Move session folder

* User Model : grouping the models

* User Model : fix bugs

* Config Plot + bug fix

* User Model : Refactoring plots

* Feature flags

* Remove dup

* clean comments a fix some vars

* fix feature flags controller

* refactor obbff from settings controller

* refactor a bunch of obbff variables

* fix bug blocking terminal

* fix integration tests

* refactor controllers with obbff

* refactor remaining ffs

* remove comments

* log not started

* mispelled variable

* set current user on local model

* User Model : moving files + updating

* User Preferences

* User : Refactor is_guest function + bug fix

* User : refactor is_guest function

* Fix conftest.py

* remove lost obbffs

* typo on fileoverwrite

* Plot config: move variables and start plot dpi

* User : tests

* refactor plot dpi references

* remove plot dpi imports

* refactor some config terminal leftover

* /account/sync : fix bug

* remove configs reload

* start path refactor

* installation paths vs user paths

* remove cfg_plot

* Tests : User Refactoring

* user prefix only for preferences

* user prefix only for preferences

* move user paths

* remove comment

* update apply remote configs

* fix tz not updating

* save some copys

* small fix

* create interface for credentials and preferences

* wrong docstrings fixed

* ruff core

* fix some pref setting

* login is better

* ruff

* ruff

* remove Literal

* add small comment

* Tests : User Refactoring

* Credentials Model : add DataBento

* Fix helper_funcs

* Fixing code

* Tests : fixing

* User Model : freezing the models

* Fixed Income + Databento

* Tests : fixing keys

* black

* ruff

* Tests : user model

* Tests : user model

* Fix linting

* Fix linting

* Linting

* Linting

* Fixing code and tests

* Fix tests

* mypy

* SDK

* Clean ruff cache

* Fix syntax issue

* Update fred_view

* Black

* Linting

* Update code

* Update tests

* Linting

* Linting

* Tests

* Black

* Linting

* Linting

* Mock os.listdir to avoid looking for file that doesnt exist

* Mock options paths

* lint

* Tests : fix

* Code : update

* Tests + Linting

* Tests

* Ruff

* Code : update

* Tests

* Code : update

* Fix workflow

* Code : update

---------

Co-authored-by: Chavithra PARANA <chavithra@gmail.com>
Co-authored-by: luqazino@gmail.com <luqazino@gmail.com>
Co-authored-by: James Maslek <jmaslek11@gmail.com>
2023-03-05 00:37:19 +01:00

164 lines
5.3 KiB
Python

"""Polygon Model"""
__docformat__ = "numpy"
import logging
import pandas as pd
from openbb_terminal.core.session.current_user import get_current_user
from openbb_terminal.decorators import check_api_key, log_start_end
from openbb_terminal.helper_funcs import request
from openbb_terminal.rich_config import console
logger = logging.getLogger(__name__)
@log_start_end(log=logger)
@check_api_key(["API_POLYGON_KEY"])
def get_financials(
symbol: str, statement: str, quarterly: bool = False, ratios: bool = False
) -> pd.DataFrame:
"""Get ticker financial statements from polygon
Parameters
----------
symbol: str
Stock ticker symbol
statement: str
Financial statement data to retrieve, can be balance, income or cash
quarterly:bool
Flag to get quarterly reports, by default False
ratios: bool
Shows percentage change, by default False
Returns
-------
pd.DataFrame
Balance Sheets or Income Statements
"""
# Note the filing date is over 30 years so will always get as many as allowed
json_request = request(
"https://api.polygon.io/vX/reference/financials?"
f"ticker={symbol}"
f"&timeframe={['annual','quarterly'][quarterly]}"
"&limit=100"
"&filing_date.gte=1980-01-01"
f"&apiKey={get_current_user().credentials.API_POLYGON_KEY}"
).json()
if statement == "cash" and quarterly:
console.print(
"[red]Quarterly information not available for statement of cash flows[/red]\n"
)
if statement not in ["balance", "income", "cash"]:
console.print("financial must be 'balance' or 'income'.\n")
return pd.DataFrame()
if json_request["status"] == "ERROR":
console.print(json_request["status"])
return pd.DataFrame()
all_results = json_request["results"]
if len(all_results) == 0:
console.print("No financials found from Polygon.\n")
return pd.DataFrame()
balance_sheets = pd.DataFrame()
income_statements = pd.DataFrame()
cash_flows = pd.DataFrame()
first = True
for single_thing in all_results:
if first:
balance_sheets = pd.concat(
[
pd.DataFrame(),
pd.DataFrame.from_dict(
single_thing["financials"]["balance_sheet"], orient="index"
),
],
axis=1,
)
balance_sheets = balance_sheets[["value"]]
balance_sheets.columns = [single_thing["filing_date"]]
income_statements = pd.concat(
[
pd.DataFrame(),
pd.DataFrame.from_dict(
single_thing["financials"]["income_statement"], orient="index"
),
],
axis=1,
)
income_statements = income_statements[["value"]]
income_statements.columns = [single_thing["filing_date"]]
if not quarterly:
cash_flows = pd.concat(
[
pd.DataFrame(),
pd.DataFrame.from_dict(
single_thing["financials"]["cash_flow_statement"],
orient="index",
),
],
axis=1,
)
cash_flows = cash_flows[["value"]]
cash_flows.columns = [single_thing["filing_date"]]
first = False
else:
values = pd.DataFrame(
pd.DataFrame.from_dict(
single_thing["financials"]["balance_sheet"], orient="index"
).value
)
values.columns = [single_thing["filing_date"]]
balance_sheets = pd.concat([balance_sheets, values], axis=1)
values = pd.DataFrame(
pd.DataFrame.from_dict(
single_thing["financials"]["income_statement"], orient="index"
).value
)
values.columns = [single_thing["filing_date"]]
income_statements = pd.concat([income_statements, values], axis=1)
if not quarterly:
values = pd.DataFrame(
pd.DataFrame.from_dict(
single_thing["financials"]["cash_flow_statement"],
orient="index",
).value
)
values.columns = [single_thing["filing_date"]]
cash_flows = pd.concat([cash_flows, values], axis=1)
if statement == "balance":
df_fa = balance_sheets
elif statement == "income":
df_fa = income_statements
elif statement == "cash":
df_fa = cash_flows
else:
return pd.DataFrame()
if ratios:
types = df_fa.copy().applymap(lambda x: isinstance(x, (float, int)))
types = types.all(axis=1)
# For rows with complete data
valid = []
i = 0
for row in types:
if row:
valid.append(i)
i += 1
df_fa_pc = df_fa.iloc[valid].pct_change(axis="columns", periods=-1).fillna(0)
j = 0
for i in valid:
df_fa.iloc[i] = df_fa_pc.iloc[j]
j += 1
return df_fa