Skip to content

Commit

Permalink
feature/usd-liquidity-index: Adds USD Liquidity Index to Economy menu (
Browse files Browse the repository at this point in the history
…#5174)

* add USD Liquidity Index to Economy menu

* mypy

* add screenshots to Terminal Economy Intro

* add test to test_fred_model

* add Broad US Dollar Index to list of comparables

* docs pages update

* fix test_nasdaq_model

* ask obb indexing

* return just the calculated series by default

* a grid for Squares

* raw table output

---------

Co-authored-by: James Maslek <[email protected]>
Co-authored-by: martinb-bb <[email protected]>
  • Loading branch information
3 people authored Jul 6, 2023
1 parent be2af59 commit 8df31f8
Show file tree
Hide file tree
Showing 24 changed files with 15,949 additions and 1,450 deletions.
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 @@ -221,6 +221,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
48 changes: 47 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,51 @@ 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,
raw=ns_parser.raw,
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
92 changes: 92 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,59 @@ 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 = "", show: bool = False) -> pd.DataFrame:
"""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 none.
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
)

if overlay != "":
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()

return data[["USD Liquidity Index (Billions of USD)"]]
98 changes: 98 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,100 @@ 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(
showgrid=False,
title=dict(
text="USD Liquidity Index (Billions of USD)",
),
),
yaxis2=dict(
title=data.columns[1],
showgrid=True,
),
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)
30 changes: 30 additions & 0 deletions openbb_terminal/miscellaneous/gpt_index/data/economy_usdli.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
parent_command:economy
usage: usdli [-o {SP500,CBBTCUSD,CBETHUSD,DJCA,DJIA,DJTA,DJUA,NASDAQCOM,NASDAQ100,WILL2500PR,WILL2500PRGR,WILL2500INDGR,WILL2500PRVAL,WILL2500INDVAL,WILL4500PR,WILL5000PR,WILL5000PRFC,WILLLRGCAP,WILLLRGCAPPR,WILLLRGCAPGRPR,WILLLRGCAPVALPR,WILLMIDCAP,WILLMIDCAPPR,WILLMIDCAPGRPR,WILLMIDCAPVALPR,WILLSMLCAP,WILLSMLCAPPR,WILLSMLCAPGR,WILLSMLCAPVAL,WILLMICROCAP,WILLREITIND,WILLRESIPR,DTWEXBGS}]
[-s] [-h] [--export EXPORT] [--sheet-name SHEET_NAME [SHEET_NAME ...]] [--raw]

The USD Liquidity Index is defined as: [WALCL - WLRRAL - WDTGAL]. It is expressed in billions of USD.

options:
-o {SP500,CBBTCUSD,CBETHUSD,DJCA,DJIA,DJTA,DJUA,NASDAQCOM,NASDAQ100,WILL2500PR,WILL2500PRGR,WILL2500INDGR,WILL2500PRVAL,WILL2500INDVAL,WILL4500PR,WILL5000PR,WILL5000PRFC,WILLLRGCAP,WILLLRGCAPPR,WILLLRGCAPGRPR,WILLLRGCAPVALPR,WILLMIDCAP,WILLMIDCAPPR,WILLMIDCAPGRPR,WILLMIDCAPVALPR,WILLSMLCAP,WILLSMLCAPPR,WILLSMLCAPGR,WILLSMLCAPVAL,WILLMICROCAP,WILLREITIND,WILLRESIPR,DTWEXBGS}, --overlay {SP500,CBBTCUSD,CBETHUSD,DJCA,DJIA,DJTA,DJUA,NASDAQCOM,NASDAQ100,WILL2500PR,WILL2500PRGR,WILL2500INDGR,WILL2500PRVAL,WILL2500INDVAL,WILL4500PR,WILL5000PR,WILL5000PRFC,WILLLRGCAP,WILLLRGCAPPR,WILLLRGCAPGRPR,WILLLRGCAPVALPR,WILLMIDCAP,WILLMIDCAPPR,WILLMIDCAPGRPR,WILLMIDCAPVALPR,WILLSMLCAP,WILLSMLCAPPR,WILLSMLCAPGR,WILLSMLCAPVAL,WILLMICROCAP,WILLREITIND,WILLRESIPR,DTWEXBGS}
The equity index to compare against. Set `show = True` for the list of choices. (default: SP500)
-s, --show Show the list of available equity indices to overlay. (default: False)
-h, --help show this help message (default: False)
--export EXPORT Export raw data into csv, json, xlsx and figure into png, jpg, pdf, svg (default: )
--sheet-name SHEET_NAME [SHEET_NAME ...]
Name of excel sheet to save data to. Only valid for .xlsx files. (default: None)
--raw Flag to display raw data (default: False)

For more information and examples, use 'about usdli' to access the related guide.


Examples:
- display the USD Liquidity Index along with the S&P 500 Index:economy/usdli -o SP500
- show the list of available equity indices to overlay with the USD Liquidity Index:economy/usdli --show
- display the USD Liquidity Index along with the NASDAQ Composite Index:economy/usdli -o NASDAQCOM
- display the USD Liquidity Index along with the Dow Jones Industrial Average (DJIA):economy/usdli --overlay DJIA
- export raw data of the USD Liquidity Index to a JSON file:economy/usdli --export data.json --raw
- export raw data of the USD Liquidity Index and overlay with NASDAQ 100 Index into an Excel file with a custom sheet name:economy/usdli -o NASDAQ100 --export data.xlsx --sheet-name LiquidityData --raw
- display the USD Liquidity Index compared against the Dow Jones Composite Average (DJCA) Index:economy/usdli --overlay DJCA
- export a graph of the USD Liquidity Index and overlay with the Wilshire 5000 Index to a PNG image:economy/usdli -o WILL5000PR --export graph.png
- display raw data of the USD Liquidity Index:economy/usdli --raw
- export raw data of the USD Liquidity Index with an overlay of the Coinbase Bitcoin to USD (CBBTCUSD) index into a CSV file:economy/usdli -o CBBTCUSD --export data.csv --raw

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions openbb_terminal/miscellaneous/i18n/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,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

0 comments on commit 8df31f8

Please sign in to comment.