Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/usd-liquidity-index: Adds USD Liquidity Index to Economy menu #5174

Merged
merged 16 commits into from
Jul 6, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions openbb_terminal/core/sdk/models/economy_sdk_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ class EconomyRoot(Category):
`trust`: Trust in government refers to the share of people who report having confidence in\n
`trust_chart`: Trust in government refers to the share of people who report having confidence in\n
`usbonds`: Scrape data for us bonds\n
`usdli`: The USD Liquidity Index is defined as: [WALCL - WLRRAL - WDTGAL]. It is expressed in billions of USD.\n
`usdli_chart`: Display US Dollar Liquidity\n
`valuation`: Get group (sectors, industry or country) valuation data. [Source: Finviz]\n
"""

Expand Down Expand Up @@ -116,4 +118,6 @@ def __init__(self):
self.trust = lib.economy_oecd_model.get_trust
self.trust_chart = lib.economy_oecd_view.plot_trust
self.usbonds = lib.economy_wsj_model.us_bonds
self.usdli = lib.economy_fred_model.get_usd_liquidity
self.usdli_chart = lib.economy_fred_view.display_usd_liquidity
self.valuation = lib.economy_finviz_model.get_valuation_data
1 change: 1 addition & 0 deletions openbb_terminal/core/sdk/trail_map.csv
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ economy.treasury,economy_econdb_model.get_treasuries,economy_econdb_view.show_tr
economy.treasury_maturities,economy_econdb_model.get_treasury_maturities,
economy.trust,economy_oecd_model.get_trust,economy_oecd_view.plot_trust
economy.usbonds,economy_wsj_model.us_bonds,
economy.usdli,economy_fred_model.get_usd_liquidity,economy_fred_view.display_usd_liquidity
economy.valuation,economy_finviz_model.get_valuation_data,
etf.candle,stocks_helper.display_candle,
etf.compare,etf_stockanalysis_model.compare_etfs,
Expand Down
47 changes: 46 additions & 1 deletion openbb_terminal/economy/economy_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ class EconomyController(BaseController):
"bigmac",
"events",
"edebt",
"usdli",
]

CHOICES_MENUS = [
Expand Down Expand Up @@ -314,10 +315,10 @@ def print_help(self):
mt.add_cmd("bigmac")
mt.add_cmd("events")
mt.add_cmd("edebt")
mt.add_raw("\n")
mt.add_cmd("rtps")
mt.add_cmd("valuation")
mt.add_cmd("performance")
mt.add_cmd("usdli")
mt.add_raw("\n")
mt.add_info("_country_")
mt.add_cmd("gdp")
Expand Down Expand Up @@ -2423,6 +2424,50 @@ def call_edebt(self, other_args: List[str]):
limit=ns_parser.limit,
)

@log_start_end(log=logger)
def call_usdli(self, other_args: List[str]):
"""Process usdli command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="usdli",
description="""
The USD Liquidity Index is defined as: [WALCL - WLRRAL - WDTGAL]. It is expressed in billions of USD.
""",
)
parser.add_argument(
"-o",
"--overlay",
type=str,
choices=list(fred_model.EQUITY_INDICES.keys()),
default="SP500",
dest="overlay",
help="The equity index to compare against. Set `show = True` for the list of choices.",
)
parser.add_argument(
"-s",
"--show",
action="store_true",
dest="show",
default=False,
help="Show the list of available equity indices to overlay.",
)
ns_parser = self.parse_known_args_and_warn(
parser,
other_args,
export_allowed=EXPORT_BOTH_RAW_DATA_AND_FIGURES,
raw=True,
)
if ns_parser:
fred_view.display_usd_liquidity(
overlay=ns_parser.overlay,
show=ns_parser.show,
export=ns_parser.export,
sheet_name=" ".join(ns_parser.sheet_name)
if ns_parser.sheet_name
else None,
)

@log_start_end(log=logger)
def call_eval(self, other_args):
parser = argparse.ArgumentParser(
Expand Down
90 changes: 90 additions & 0 deletions openbb_terminal/economy/fred_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,42 @@

CPI_FREQUENCY = ["monthly", "quarterly", "annual"]

EQUITY_INDICES = {
"SP500": "S&P 500 Index",
"CBBTCUSD": "Coinbase Bitcoin",
"CBETHUSD": "Coinbase Ethereum",
"DJCA": "Dow Jones Composite Average",
"DJIA": "Dow Jones Industrial Average",
"DJTA": "Dow Jones Transportation Average",
"DJUA": "Dow Jones Utility Average",
"NASDAQCOM": "Nasdaq Composite Index",
"NASDAQ100": "Nasdaq 100 Index",
"WILL2500PR": "Wilshire 2500 Price Index",
"WILL2500PRGR": "Wilshire 2500 Growth Price Index",
"WILL2500INDGR": "Wilshire 2500 Growth Total Market Index",
"WILL2500PRVAL": "Wilshire 2500 Value Price Index",
"WILL2500INDVAL": "Wilshire 2500 Value Total Market Index",
"WILL4500PR": "Wilshire 4500 Price Index",
"WILL5000PR": "Wilshire 5000 Price Index",
"WILL5000PRFC": "Wilshire 5000 Full Cap Price Index",
"WILLLRGCAP": "Wilshire US Large-Cap Total Market Index",
"WILLLRGCAPPR": "Wilshire US Large-Cap Price Index",
"WILLLRGCAPGRPR": "Wilshire US Large-Cap Growth Price Index",
"WILLLRGCAPVALPR": "Wilshire US Large-Cap Value Price Index",
"WILLMIDCAP": "Wilshire US Mid-Cap Total Market Index",
"WILLMIDCAPPR": "Wilshire US Mid-Cap Price Index",
"WILLMIDCAPGRPR": "Wilshire US Mid-Cap Growth Price Index",
"WILLMIDCAPVALPR": "Wilshire US Mid-Cap Value Price Index",
"WILLSMLCAP": "Wilshire US Small-Cap Total Market Index",
"WILLSMLCAPPR": "Wilshire US Small-Cap Price Index",
"WILLSMLCAPGR": "Wilshire US Small-Cap Growth Total Market Index",
"WILLSMLCAPVAL": "Wilshire US Small-Cap Value Total Market Index",
"WILLMICROCAP": "Wilshire US Micro-Cap Total Market Index",
"WILLREITIND": "Wilshire US Real Estate Investment Trust Price Index",
"WILLRESIPR": "Wilshire US Real Estate Securities Price Index",
"DTWEXBGS": "Nominal Broad US Dollar Index",
}


@log_start_end(log=logger)
@check_api_key(["API_FRED_KEY"])
Expand Down Expand Up @@ -348,3 +384,57 @@ def get_cpi(
df = df.dropna()

return df


@log_start_end(log=logger)
@check_api_key(["API_FRED_KEY"])
def get_usd_liquidity(overlay: str = "SP500", show: bool = False) -> pd.DataFrame:
deeleeramone marked this conversation as resolved.
Show resolved Hide resolved
"""The USD Liquidity Index is defined as: [WALCL - WLRRAL - WDTGAL]. It is expressed in billions of USD.

Parameters
-----------
overlay: str
An equity index to overlay, as a FRED Series ID. Defaults to "SP500".
show: bool
Shows the list of valid equity indices to overlay.

Returns
--------
pd.DataFrame
DataFrame with the USD Liquidity Index.

Examples
----------
>>> from openbb_terminal.economy import fred_model
>>> usd_liquidity = fred_model.get_usd_liquidity()

Display the list of equity indices:
>>> fred_model.get_usd_liquidity(show = True)
"""

if show:
return pd.DataFrame.from_dict(data=EQUITY_INDICES, orient="index").rename(
columns={0: "Index Name"}
)

data = pd.DataFrame()
data["WALCL"] = get_series_data("WALCL").astype(int) * 1000000
data["WLRRAL"] = get_series_data("WLRRAL").astype(int) * 1000000
data["WDTGAL"] = get_series_data("WDTGAL").astype(int) * 1000000
data["USD Liquidity Index (Billions of USD)"] = round(
(data["WALCL"] - data["WLRRAL"] - data["WDTGAL"]) / 1000000000, 2
)

overlay = overlay.upper()
if overlay not in EQUITY_INDICES:
print(
"Invalid choice for the overlay."
"Use `get_usd_liquidity(show = True)` to see display the list of choices."
)
return pd.DataFrame()

overlay_df = pd.DataFrame()
overlay_df[f"{EQUITY_INDICES[overlay]}"] = get_series_data(overlay)
liquidity_df = data[["USD Liquidity Index (Billions of USD)"]].join(overlay_df)

return liquidity_df.dropna()
94 changes: 94 additions & 0 deletions openbb_terminal/economy/fred_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from openbb_terminal import OpenBBFigure
from openbb_terminal.decorators import check_api_key, log_start_end
from openbb_terminal.economy import fred_model
from openbb_terminal.economy.plot_view import show_plot
from openbb_terminal.helper_funcs import export_data, print_rich_table
from openbb_terminal.rich_config import console

Expand Down Expand Up @@ -313,3 +314,96 @@ def format_data_to_plot(data: pd.DataFrame, detail: dict) -> Tuple[pd.DataFrame,
data_to_plot.index = pd.to_datetime(data_to_plot.index)

return data_to_plot, title


def display_usd_liquidity(
overlay: str = "SP500",
show: bool = False,
raw: bool = False,
export: str = "",
sheet_name: Optional[str] = "",
external_axes: bool = False,
) -> Union[None, OpenBBFigure]:
"""Display US Dollar Liquidity
Parameters
-----------
overlay: str
An equity index to overlay, as a FRED Series ID. Defaults to "SP500".
show: bool
Shows the list of valid equity indices to overlay.
raw: bool
Show raw data
export: str
Export data to csv or excel file
sheet_name: str
Name of the sheet to export to
external_axes : bool, optional
Whether to return the figure object or not, by default False
"""

if show:
print_rich_table(
fred_model.get_usd_liquidity(show=True),
title="Available Equity Indices to Overlay",
show_index=True,
index_name="FRED Series ID",
export=bool(export),
)
return None

overlay = overlay.upper()
if overlay not in fred_model.EQUITY_INDICES:
print(
"Invalid choice. Display available choices by adding the parameter, `show = True`."
)
return None

data = fred_model.get_usd_liquidity(overlay=overlay)
y1 = pd.DataFrame(data.iloc[:, 0])
y2 = pd.DataFrame(data.iloc[:, 1])
fig = show_plot(y1, y2, external_axes=True)

fig.update_layout(
title=dict(text="USD Liquidity Index"),
margin=dict(l=125, t=100),
yaxis=dict(
title=dict(
text="USD Liquidity Index (Billions of USD)",
),
),
yaxis2=dict(title=data.columns[1]),
title_y=0.97,
title_x=0.5,
legend=dict(
orientation="h",
yanchor="top",
y=1.075,
xanchor="center",
x=0.5,
),
)
fig.update_yaxes(title_font=dict(size=16))

if raw:
print_rich_table(
data,
title="USD Liquidity Index",
show_index=True,
index_name="Date",
floatfmt=".2f",
export=bool(export),
)
return None

if export and export != "":
export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
"usd_liquidity",
data,
sheet_name,
fig,
)
return None

return fig.show(external=raw or external_axes)
1 change: 1 addition & 0 deletions openbb_terminal/miscellaneous/i18n/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,7 @@ en:
economy/spread: show bond spread matrix
economy/events: show economic calendar
economy/edebt: show external debt statistics for various countries
economy/usdli: Compare the USD Liquidity Index against a choice of indices
economy/plot: plot data from the above commands together
economy/rtps: real-time performance sectors
economy/valuation: valuation of sectors, industry, country
Expand Down
Loading