mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-10-27 12:40:35 +00:00
Add treasury rates
This commit is contained in:
175
openbb_terminal/fixedincome/econdb_model.py
Normal file
175
openbb_terminal/fixedincome/econdb_model.py
Normal file
@@ -0,0 +1,175 @@
|
||||
""" EconDB Model """
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import logging
|
||||
from typing import Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
|
||||
import pandas as pd
|
||||
import pandas_datareader.data as web
|
||||
|
||||
from openbb_terminal.decorators import log_start_end
|
||||
from openbb_terminal.rich_config import console
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
TREASURIES: Dict = {
|
||||
"frequencies": {
|
||||
"annually": 203,
|
||||
"monthly": 129,
|
||||
"weekly": 21,
|
||||
"daily": 9,
|
||||
},
|
||||
"instruments": {
|
||||
"nominal": {
|
||||
"identifier": "TCMNOM",
|
||||
"maturities": {
|
||||
"1m": "1-month",
|
||||
"3m": "3-month",
|
||||
"6m": "6-month",
|
||||
"1y": "1-year",
|
||||
"2y": "2-year",
|
||||
"3y": "3-year",
|
||||
"5y": "5-year",
|
||||
"7y": "7-year",
|
||||
"10y": "10-year",
|
||||
"20y": "20-year",
|
||||
"30y": "30-year",
|
||||
},
|
||||
},
|
||||
"inflation": {
|
||||
"identifier": "TCMII",
|
||||
"maturities": {
|
||||
"5y": "5-year",
|
||||
"7y": "7-year",
|
||||
"10y": "10-year",
|
||||
"20y": "20-year",
|
||||
"30y": "30-year",
|
||||
},
|
||||
},
|
||||
"average": {
|
||||
"identifier": "LTAVG",
|
||||
"maturities": {
|
||||
"Longer than 10-year": "Longer than 10-year",
|
||||
},
|
||||
},
|
||||
"secondary": {
|
||||
"identifier": "TB",
|
||||
"maturities": {
|
||||
"4w": "4-week",
|
||||
"3m": "3-month",
|
||||
"6m": "6-month",
|
||||
"1y": "1-year",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@log_start_end(log=logger)
|
||||
def get_treasuries(
|
||||
instruments: list = None,
|
||||
maturities: list = None,
|
||||
frequency: str = "monthly",
|
||||
start_date: str = "1900-01-01",
|
||||
end_date: Optional[str] = None,
|
||||
) -> pd.DataFrame:
|
||||
"""Get U.S. Treasury rates [Source: EconDB]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
instruments: list
|
||||
Type(s) of treasuries, nominal, inflation-adjusted (long term average) or secondary market.
|
||||
Available options can be accessed through economy.treasury_maturities().
|
||||
maturities : list
|
||||
Treasury maturities to get. Available options can be accessed through economy.treasury_maturities().
|
||||
frequency : str
|
||||
Frequency of the data, this can be annually, monthly, weekly or daily.
|
||||
start_date : str
|
||||
Starting date, format "YEAR-MONTH-DAY", i.e. 2010-12-31.
|
||||
end_date : Optional[str]
|
||||
End date, format "YEAR-MONTH-DAY", i.e. 2020-06-05.
|
||||
|
||||
Returns
|
||||
-------
|
||||
treasury_data: pd.Dataframe
|
||||
Holds data of the selected types and maturities
|
||||
"""
|
||||
|
||||
if end_date is None:
|
||||
end_date = datetime.today().strftime("%Y-%m-%d")
|
||||
|
||||
if instruments is None:
|
||||
instruments = ["nominal"]
|
||||
if maturities is None:
|
||||
maturities = ["10y"]
|
||||
|
||||
treasury_data: Dict[Any, Dict[Any, pd.Series]] = {}
|
||||
|
||||
for instrument in instruments:
|
||||
if instrument not in TREASURIES["instruments"]:
|
||||
console.print(
|
||||
f"{instrument} is not an option. Please choose between: "
|
||||
f"{', '.join(TREASURIES['instruments'].keys())}"
|
||||
)
|
||||
else:
|
||||
instrument_identifier = TREASURIES["instruments"][instrument]["identifier"]
|
||||
frequency_number = TREASURIES["frequencies"][frequency]
|
||||
df = web.DataReader(
|
||||
"&".join(
|
||||
[
|
||||
"dataset=FRB_H15",
|
||||
"v=Instrument",
|
||||
"h=TIME",
|
||||
f"instrument=[{instrument_identifier}]",
|
||||
f"from={start_date}",
|
||||
f"to={end_date}",
|
||||
f"freq=[{frequency_number}",
|
||||
"UNIT=[PERCENT:_PER_YEAR]",
|
||||
]
|
||||
),
|
||||
"econdb",
|
||||
)
|
||||
|
||||
if instrument == "average":
|
||||
maturities_list = ["Longer than 10-year"]
|
||||
type_string = "Long-term average"
|
||||
else:
|
||||
maturities_list = maturities
|
||||
type_string = instrument.capitalize()
|
||||
|
||||
treasury_data[type_string] = {}
|
||||
|
||||
for maturity in maturities_list:
|
||||
if maturity not in TREASURIES["instruments"][instrument]["maturities"]:
|
||||
console.print(
|
||||
f"The maturity {maturity} is not an option for {instrument}. Please choose between "
|
||||
f"{', '.join(TREASURIES['instruments'][instrument]['maturities'].keys())}"
|
||||
)
|
||||
else:
|
||||
maturity_string = TREASURIES["instruments"][instrument][
|
||||
"maturities"
|
||||
][maturity]
|
||||
|
||||
for column in df.columns:
|
||||
# check if type inside the name and maturity inside the maturity string
|
||||
if (
|
||||
type_string.lower() in column[2].lower()
|
||||
and maturity_string in column[3]
|
||||
):
|
||||
treasury_data[type_string][maturity_string] = df[
|
||||
column
|
||||
].dropna()
|
||||
break
|
||||
|
||||
if maturity_string not in treasury_data[type_string]:
|
||||
console.print(
|
||||
f"No data found for the combination {instrument} and {maturity}."
|
||||
)
|
||||
|
||||
df = pd.DataFrame.from_dict(treasury_data, orient="index").stack().to_frame()
|
||||
df = pd.DataFrame(df[0].values.tolist(), index=df.index).T
|
||||
df.columns = ["_".join(column) for column in df.columns]
|
||||
|
||||
return df
|
||||
238
openbb_terminal/fixedincome/econdb_view.py
Normal file
238
openbb_terminal/fixedincome/econdb_view.py
Normal file
@@ -0,0 +1,238 @@
|
||||
""" EconDB view """
|
||||
__docformat__ = "numpy"
|
||||
|
||||
from typing import Optional, List
|
||||
from itertools import cycle
|
||||
import logging
|
||||
import os
|
||||
|
||||
from matplotlib import pyplot as plt
|
||||
|
||||
from openbb_terminal.config_terminal import theme
|
||||
from openbb_terminal.config_plot import PLOT_DPI
|
||||
from openbb_terminal.decorators import log_start_end, check_api_key
|
||||
from openbb_terminal.helper_funcs import (
|
||||
export_data,
|
||||
plot_autoscale,
|
||||
is_valid_axes_count,
|
||||
)
|
||||
from openbb_terminal.fixedincome import econdb_model
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MATURITY_TO_ID = {
|
||||
"4_week": "4w",
|
||||
"3_month": "3m",
|
||||
"6_month": "6m",
|
||||
"1_year": "1y",
|
||||
"1_month": "1m",
|
||||
"2_year": "2y",
|
||||
"3_year": "3y",
|
||||
"5_year": "5y",
|
||||
"7_year": "7y",
|
||||
"10_year": "10y",
|
||||
"20_year": "20y",
|
||||
"30_year": "30y"
|
||||
}
|
||||
|
||||
|
||||
@log_start_end(log=logger)
|
||||
@check_api_key(["API_FRED_KEY"])
|
||||
def plot_cmn(
|
||||
maturity: str = "3_month",
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
export: str = "",
|
||||
external_axes: Optional[List[plt.Axes]] = None,
|
||||
):
|
||||
"""Plot Treasury Constant Maturity Nominal Market Yield.
|
||||
|
||||
Yields on Treasury nominal securities at “constant maturity” are interpolated by the U.S. Treasury from the daily
|
||||
yield curve for non-inflation-indexed Treasury securities. This curve, which relates the yield on a security to
|
||||
its time to maturity, is based on the closing market bid yields on actively traded Treasury securities in the
|
||||
over-the-counter market. These market yields are calculated from composites of quotations obtained by the Federal
|
||||
Reserve Bank of New York. The constant maturity yield values are read from the yield curve at fixed maturities,
|
||||
currently 1, 3, and 6 months and 1, 2, 3, 5, 7, 10, 20, and 30 years. This method provides a yield for a 10-year
|
||||
maturity, for example, even if no outstanding security has exactly 10 years remaining to maturity. Similarly,
|
||||
yields on inflation-indexed securities at “constant maturity” are interpolated from the daily yield curve for
|
||||
Treasury inflation protected securities in the over-the-counter market. The inflation-indexed constant maturity
|
||||
yields are read from this yield curve at fixed maturities, currently 5, 7, 10, 20, and 30 years.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
maturity: str
|
||||
Maturity to plot, options: ['1_month', '3_month', '6_month', '1_year', '2_year', '3_year', '5_year', '7_year', '10_year', '20_year', '30_year']
|
||||
start_date: Optional[str]
|
||||
Start date, formatted YYYY-MM-DD
|
||||
end_date: Optional[str]
|
||||
End date, formatted YYYY-MM-DD
|
||||
export: str
|
||||
Export data to csv or excel file
|
||||
external_axes: Optional[List[plt.Axes]]
|
||||
External axes (1 axis is expected in the list)
|
||||
"""
|
||||
df = econdb_model.get_treasuries(instruments=["nominal"], maturities=[MATURITY_TO_ID[maturity]], frequency="daily", start_date=start_date, end_date=end_date)
|
||||
|
||||
# This plot has 1 axis
|
||||
if not external_axes:
|
||||
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
elif is_valid_axes_count(external_axes, 1):
|
||||
(ax,) = external_axes
|
||||
else:
|
||||
return
|
||||
|
||||
colors = cycle(theme.get_colors())
|
||||
ax.plot(
|
||||
df.index,
|
||||
df.values,
|
||||
marker="o",
|
||||
linestyle="dashed",
|
||||
linewidth=2,
|
||||
markersize=4,
|
||||
color=next(colors, "#FCED00"),
|
||||
)
|
||||
ax.set_title(f"{maturity.replace('-', ' ')} Treasury Constant Maturity Nominal Market Yield [Percent]")
|
||||
theme.style_primary_axis(ax)
|
||||
|
||||
if external_axes is None:
|
||||
theme.visualize_output()
|
||||
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)),
|
||||
f"cmn, {maturity}",
|
||||
df,
|
||||
)
|
||||
|
||||
|
||||
@log_start_end(log=logger)
|
||||
@check_api_key(["API_FRED_KEY"])
|
||||
def plot_tips(
|
||||
maturity: str = "10_year",
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
export: str = "",
|
||||
external_axes: Optional[List[plt.Axes]] = None,
|
||||
):
|
||||
"""Plot Yields on Treasury inflation protected securities (TIPS) adjusted to constant maturities.
|
||||
|
||||
Yields on Treasury nominal securities at “constant maturity” are interpolated by the U.S. Treasury from the daily
|
||||
yield curve for non-inflation-indexed Treasury securities. This curve, which relates the yield on a security to
|
||||
its time to maturity, is based on the closing market bid yields on actively traded Treasury securities in the
|
||||
over-the-counter market. These market yields are calculated from composites of quotations obtained by the Federal
|
||||
Reserve Bank of New York. The constant maturity yield values are read from the yield curve at fixed maturities,
|
||||
currently 1, 3, and 6 months and 1, 2, 3, 5, 7, 10, 20, and 30 years. This method provides a yield for a 10-year
|
||||
maturity, for example, even if no outstanding security has exactly 10 years remaining to maturity. Similarly,
|
||||
yields on inflation-indexed securities at “constant maturity” are interpolated from the daily yield curve for
|
||||
Treasury inflation protected securities in the over-the-counter market. The inflation-indexed constant maturity
|
||||
yields are read from this yield curve at fixed maturities, currently 5, 7, 10, 20, and 30 years.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
maturity: str
|
||||
Maturity to plot, options: ['5_year', '7_year', '10_year', '20_year', '30_year']
|
||||
start_date: Optional[str]
|
||||
Start date, formatted YYYY-MM-DD
|
||||
end_date: Optional[str]
|
||||
End date, formatted YYYY-MM-DD
|
||||
export: str
|
||||
Export data to csv or excel file
|
||||
external_axes: Optional[List[plt.Axes]]
|
||||
External axes (1 axis is expected in the list)
|
||||
"""
|
||||
df = econdb_model.get_treasuries(instruments=["inflation"], maturities=[MATURITY_TO_ID[maturity]], frequency="daily", start_date=start_date, end_date=end_date)
|
||||
|
||||
# This plot has 1 axis
|
||||
if not external_axes:
|
||||
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
elif is_valid_axes_count(external_axes, 1):
|
||||
(ax,) = external_axes
|
||||
else:
|
||||
return
|
||||
|
||||
colors = cycle(theme.get_colors())
|
||||
ax.plot(
|
||||
df.index,
|
||||
df.values,
|
||||
marker="o",
|
||||
linestyle="dashed",
|
||||
linewidth=2,
|
||||
markersize=4,
|
||||
color=next(colors, "#FCED00"),
|
||||
)
|
||||
ax.set_title(f"{maturity.replace('-', ' ')} Yields on Treasury inflation protected securities (TIPS) adjusted to "
|
||||
f"constant maturities [Percent]")
|
||||
theme.style_primary_axis(ax)
|
||||
|
||||
if external_axes is None:
|
||||
theme.visualize_output()
|
||||
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)),
|
||||
f"tips, {maturity}",
|
||||
df,
|
||||
)
|
||||
|
||||
|
||||
@log_start_end(log=logger)
|
||||
@check_api_key(["API_FRED_KEY"])
|
||||
def plot_tbill(
|
||||
maturity: str = "3_month",
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
export: str = "",
|
||||
external_axes: Optional[List[plt.Axes]] = None,
|
||||
):
|
||||
"""Plot the Treasury Bill Secondary Market Rate.
|
||||
|
||||
A Treasury Bill (T-Bill) is a short-term U.S. government debt obligation backed by the Treasury Department with a
|
||||
maturity of one year or less. Treasury bills are usually sold in denominations of $1,000. However, some can reach
|
||||
a maximum denomination of $5 million in non-competitive bids. These securities are widely regarded as low-risk
|
||||
and secure investments.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
maturity: str
|
||||
Maturity to plot, options: ['4_week', '3_month', '6_month', '1_year']
|
||||
start_date: Optional[str]
|
||||
Start date, formatted YYYY-MM-DD
|
||||
end_date: Optional[str]
|
||||
End date, formatted YYYY-MM-DD
|
||||
export: str
|
||||
Export data to csv or excel file
|
||||
external_axes: Optional[List[plt.Axes]]
|
||||
External axes (1 axis is expected in the list)
|
||||
"""
|
||||
df = econdb_model.get_treasuries(instruments=["secondary"], maturities=[MATURITY_TO_ID[maturity]], frequency="daily", start_date=start_date, end_date=end_date)
|
||||
|
||||
# This plot has 1 axis
|
||||
if not external_axes:
|
||||
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
elif is_valid_axes_count(external_axes, 1):
|
||||
(ax,) = external_axes
|
||||
else:
|
||||
return
|
||||
|
||||
colors = cycle(theme.get_colors())
|
||||
ax.plot(
|
||||
df.index,
|
||||
df.values,
|
||||
marker="o",
|
||||
linestyle="dashed",
|
||||
linewidth=2,
|
||||
markersize=4,
|
||||
color=next(colors, "#FCED00"),
|
||||
)
|
||||
ax.set_title(f"{maturity.replace('-', ' ')} Treasury Bill Secondary Market Rate, Discount Basis [Percent]")
|
||||
theme.style_primary_axis(ax)
|
||||
|
||||
if external_axes is None:
|
||||
theme.visualize_output()
|
||||
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)),
|
||||
f"tbill, {maturity}",
|
||||
df,
|
||||
)
|
||||
@@ -12,7 +12,7 @@ from openbb_terminal.custom_prompt_toolkit import NestedCompleter
|
||||
|
||||
from openbb_terminal import feature_flags as obbff
|
||||
from openbb_terminal.decorators import log_start_end
|
||||
from openbb_terminal.fixedincome import ecb_view, nyfed_view, oecd_view
|
||||
from openbb_terminal.fixedincome import ecb_view, nyfed_view, oecd_view, econdb_view, yfinance_view
|
||||
from openbb_terminal.fixedincome import fred_view
|
||||
|
||||
from openbb_terminal.helper_funcs import (
|
||||
@@ -53,6 +53,11 @@ class FixedIncomeController(BaseController):
|
||||
"ycrv",
|
||||
"iiycrv",
|
||||
"ecbycrv",
|
||||
"tbill",
|
||||
"tips",
|
||||
"cmn",
|
||||
"tbffr",
|
||||
"ty"
|
||||
]
|
||||
|
||||
PATH = "/fixedincome/"
|
||||
@@ -153,6 +158,37 @@ class FixedIncomeController(BaseController):
|
||||
"5_year": "T5YFF",
|
||||
"1_year": "T1YFF",
|
||||
"6_month": "T6MFF",
|
||||
"3_month": "T3MFF",
|
||||
}
|
||||
tbill_parameter_to_fred_id = {
|
||||
"4_week": "DTB4WK",
|
||||
"3_month": "TB3MS",
|
||||
"6_month": "DTB6",
|
||||
"1_year": "DTB1YR",
|
||||
}
|
||||
tips_parameter_to_fred_id = {
|
||||
"5_year": "DFII5",
|
||||
"7_year": "DFII7",
|
||||
"10_year": "DFII10",
|
||||
"20_year": "DFII20",
|
||||
"30_year": "DFII30",
|
||||
}
|
||||
cmn_parameter_to_fred_id = {
|
||||
"1_month": "DGS1MO",
|
||||
"3_month": "DGS3MO",
|
||||
"6_month": "DGS6MO",
|
||||
"1_year": "DGS1",
|
||||
"2_year": "DGS2",
|
||||
"3_year": "DGS3",
|
||||
"5_year": "DGS5",
|
||||
"7_year": "DGS7",
|
||||
"10_year": "DGS10",
|
||||
"20_year": "DGS20",
|
||||
"30_year": "DGS30",
|
||||
}
|
||||
tbffr_parameter_to_fred_id = {
|
||||
"3_month": "TB3SMFFM",
|
||||
"6_month": "TB6SMFFM",
|
||||
}
|
||||
|
||||
def __init__(self, queue: List[str] = None):
|
||||
@@ -187,14 +223,21 @@ class FixedIncomeController(BaseController):
|
||||
mt.add_cmd("stir")
|
||||
mt.add_cmd("ltir")
|
||||
mt.add_raw("\n")
|
||||
mt.add_info("_constant_maturities_spreads_")
|
||||
mt.add_cmd("tmc")
|
||||
mt.add_cmd("ffrmc")
|
||||
mt.add_raw("\n")
|
||||
mt.add_info("_yield_curves_")
|
||||
mt.add_cmd("ycrv")
|
||||
mt.add_cmd("iiycrv")
|
||||
mt.add_cmd("ecbycrv")
|
||||
mt.add_raw("\n")
|
||||
mt.add_info("_us_government_securities_")
|
||||
mt.add_cmd("tbill")
|
||||
mt.add_cmd("cmn")
|
||||
mt.add_cmd("tips")
|
||||
mt.add_cmd("ty")
|
||||
mt.add_raw("\n")
|
||||
mt.add_info("_spreads_")
|
||||
mt.add_cmd("tmc")
|
||||
mt.add_cmd("ffrmc")
|
||||
mt.add_cmd("tbffr")
|
||||
|
||||
console.print(text=mt.menu_text, menu="Fixed Income")
|
||||
|
||||
@@ -889,7 +932,12 @@ class FixedIncomeController(BaseController):
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="str",
|
||||
description='Plot short term interest rates from selected countries. \nShort-term interest rates are the rates at which short-term borrowings are effected between financial institutions or the rate at which short-term government paper is issued or traded in the market. Short-term interest rates are generally averages of daily rates, measured as a percentage. Short-term interest rates are based on three-month money market rates where available. Typical standardised names are "money market rate" and "treasury bill rate".',
|
||||
description='Plot short term interest rates from selected countries. \nShort-term interest rates are the '
|
||||
'rates at which short-term borrowings are effected between financial institutions or the rate '
|
||||
'at which short-term government paper is issued or traded in the market. Short-term interest '
|
||||
'rates are generally averages of daily rates, measured as a percentage. Short-term interest '
|
||||
'rates are based on three-month money market rates where available. Typical standardised '
|
||||
'names are "money market rate" and "treasury bill rate".',
|
||||
)
|
||||
parser.add_argument(
|
||||
"-c",
|
||||
@@ -947,7 +995,16 @@ class FixedIncomeController(BaseController):
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="str",
|
||||
description="Plot long term interest rates from selected countries. \nLong-term interest rates refer to government bonds maturing in ten years. Rates are mainly determined by the price charged by the lender, the risk from the borrower and the fall in the capital value. Long-term interest rates are generally averages of daily rates, measured as a percentage. These interest rates are implied by the prices at which the government bonds are traded on financial markets, not the interest rates at which the loans were issued. In all cases, they refer to bonds whose capital repayment is guaranteed by governments. Long-term interest rates are one of the determinants of business investment. Low long-term interest rates encourage investment in new equipment and high interest rates discourage it. Investment is, in turn, a major source of economic growth.",
|
||||
description="Plot long term interest rates from selected countries. \nLong-term interest rates refer to "
|
||||
"government bonds maturing in ten years. Rates are mainly determined by the price charged by "
|
||||
"the lender, the risk from the borrower and the fall in the capital value. Long-term interest "
|
||||
"rates are generally averages of daily rates, measured as a percentage. These interest rates "
|
||||
"are implied by the prices at which the government bonds are traded on financial markets, "
|
||||
"not the interest rates at which the loans were issued. In all cases, they refer to bonds "
|
||||
"whose capital repayment is guaranteed by governments. Long-term interest rates are one of "
|
||||
"the determinants of business investment. Low long-term interest rates encourage investment "
|
||||
"in new equipment and high interest rates discourage it. Investment is, in turn, "
|
||||
"a major source of economic growth.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-c",
|
||||
@@ -1263,3 +1320,281 @@ class FixedIncomeController(BaseController):
|
||||
raw=ns_parser.raw,
|
||||
export=ns_parser.export,
|
||||
)
|
||||
|
||||
@log_start_end(log=logger)
|
||||
def call_tbill(self, other_args: List[str]):
|
||||
"""Process tbill command"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="tbill",
|
||||
description="Plot the Treasury Bill Secondary Market Rate.\nA Treasury Bill (T-Bill) is a short-term U.S. "
|
||||
"government debt obligation backed by the Treasury Department with a maturity of one year or "
|
||||
"less. Treasury bills are usually sold in denominations of $1,000. However, some can reach a "
|
||||
"maximum denomination of $5 million in non-competitive bids. These securities are widely "
|
||||
"regarded as low-risk and secure investments.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-p",
|
||||
"--parameter",
|
||||
dest="parameter",
|
||||
type=str,
|
||||
help="Specific Treasury Bill Secondary Market Rate data to plot",
|
||||
default="3_month",
|
||||
choices=list(self.tbill_parameter_to_fred_id.keys()),
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s",
|
||||
"--start",
|
||||
dest="start_date",
|
||||
type=valid_date,
|
||||
help="Starting date (YYYY-MM-DD) of data",
|
||||
default="1980-01-01",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-e",
|
||||
"--end",
|
||||
dest="end_date",
|
||||
type=valid_date,
|
||||
help="Ending date (YYYY-MM-DD) of data",
|
||||
default=None,
|
||||
)
|
||||
ns_parser = self.parse_known_args_and_warn(
|
||||
parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES
|
||||
)
|
||||
if ns_parser:
|
||||
if ns_parser.source == "FRED":
|
||||
fred_view.plot_tbill(
|
||||
self.tbill_parameter_to_fred_id[ns_parser.parameter],
|
||||
ns_parser.start_date,
|
||||
ns_parser.end_date,
|
||||
ns_parser.export,
|
||||
)
|
||||
elif ns_parser.source == "EconDB":
|
||||
econdb_view.plot_tbill(
|
||||
ns_parser.parameter,
|
||||
ns_parser.start_date,
|
||||
ns_parser.end_date,
|
||||
ns_parser.export,
|
||||
)
|
||||
|
||||
@log_start_end(log=logger)
|
||||
def call_cmn(self, other_args: List[str]):
|
||||
"""Process cmn command"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="cmn",
|
||||
description="Plot the Treasury Constant Maturity Nominal Market Yield. \nYields on Treasury nominal "
|
||||
"securities at “constant maturity” are interpolated by the U.S. Treasury from the daily yield "
|
||||
"curve for non-inflation-indexed Treasury securities. This curve, which relates the yield on "
|
||||
"a security to its time to maturity, is based on the closing market bid yields on actively "
|
||||
"traded Treasury securities in the over-the-counter market. These market yields are "
|
||||
"calculated from composites of quotations obtained by the Federal Reserve Bank of New York. "
|
||||
"The constant maturity yield values are read from the yield curve at fixed maturities, "
|
||||
"currently 1, 3, and 6 months and 1, 2, 3, 5, 7, 10, 20, and 30 years. This method provides a "
|
||||
"yield for a 10-year maturity, for example, even if no outstanding security has exactly 10 "
|
||||
"years remaining to maturity. Similarly, yields on inflation-indexed securities at “constant "
|
||||
"maturity” are interpolated from the daily yield curve for Treasury inflation protected "
|
||||
"securities in the over-the-counter market. The inflation-indexed constant maturity yields "
|
||||
"are read from this yield curve at fixed maturities, currently 5, 7, 10, 20, and 30 years.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-p",
|
||||
"--parameter",
|
||||
dest="parameter",
|
||||
type=str,
|
||||
help="Specific Treasury Constant Maturity Nominal Market Yield data to plot",
|
||||
default="3_month",
|
||||
choices=list(self.cmn_parameter_to_fred_id.keys()),
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s",
|
||||
"--start",
|
||||
dest="start_date",
|
||||
type=valid_date,
|
||||
help="Starting date (YYYY-MM-DD) of data",
|
||||
default="1980-01-01",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-e",
|
||||
"--end",
|
||||
dest="end_date",
|
||||
type=valid_date,
|
||||
help="Ending date (YYYY-MM-DD) of data",
|
||||
default=None,
|
||||
)
|
||||
ns_parser = self.parse_known_args_and_warn(
|
||||
parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES
|
||||
)
|
||||
if ns_parser:
|
||||
if ns_parser.source == "FRED":
|
||||
fred_view.plot_cmn(
|
||||
self.cmn_parameter_to_fred_id[ns_parser.parameter],
|
||||
ns_parser.start_date,
|
||||
ns_parser.end_date,
|
||||
ns_parser.export,
|
||||
)
|
||||
elif ns_parser.source == "EconDB":
|
||||
econdb_view.plot_cmn(
|
||||
ns_parser.parameter,
|
||||
ns_parser.start_date,
|
||||
ns_parser.end_date,
|
||||
ns_parser.export,
|
||||
)
|
||||
|
||||
@log_start_end(log=logger)
|
||||
def call_tips(self, other_args: List[str]):
|
||||
"""Process tips command"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="tips",
|
||||
description="Plot Yields on Treasury inflation protected securities (TIPS) adjusted to constant "
|
||||
"maturities. \nYields on Treasury nominal securities at “constant maturity” are interpolated "
|
||||
"by the U.S. Treasury from the daily yield curve for non-inflation-indexed Treasury "
|
||||
"securities. This curve, which relates the yield on a security to its time to maturity, "
|
||||
"is based on the closing market bid yields on actively traded Treasury securities in the "
|
||||
"over-the-counter market. These market yields are calculated from composites of quotations "
|
||||
"obtained by the Federal Reserve Bank of New York. The constant maturity yield values are "
|
||||
"read from the yield curve at fixed maturities, currently 1, 3, and 6 months and 1, 2, 3, 5, "
|
||||
"7, 10, 20, and 30 years. This method provides a yield for a 10-year maturity, for example, "
|
||||
"even if no outstanding security has exactly 10 years remaining to maturity. Similarly, "
|
||||
"yields on inflation-indexed securities at “constant maturity” are interpolated from the "
|
||||
"daily yield curve for Treasury inflation protected securities in the over-the-counter "
|
||||
"market. The inflation-indexed constant maturity yields are read from this yield curve at "
|
||||
"fixed maturities, currently 5, 7, 10, 20, and 30 years.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-p",
|
||||
"--parameter",
|
||||
dest="parameter",
|
||||
type=str,
|
||||
help="Specific Yields on TIPS adjusted to constant maturities data to plot",
|
||||
default="10_year",
|
||||
choices=list(self.tips_parameter_to_fred_id.keys()),
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s",
|
||||
"--start",
|
||||
dest="start_date",
|
||||
type=valid_date,
|
||||
help="Starting date (YYYY-MM-DD) of data",
|
||||
default="1980-01-01",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-e",
|
||||
"--end",
|
||||
dest="end_date",
|
||||
type=valid_date,
|
||||
help="Ending date (YYYY-MM-DD) of data",
|
||||
default=None,
|
||||
)
|
||||
ns_parser = self.parse_known_args_and_warn(
|
||||
parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES
|
||||
)
|
||||
if ns_parser:
|
||||
if ns_parser.source == "FRED":
|
||||
fred_view.plot_tips(
|
||||
self.tips_parameter_to_fred_id[ns_parser.parameter],
|
||||
ns_parser.start_date,
|
||||
ns_parser.end_date,
|
||||
ns_parser.export,
|
||||
)
|
||||
elif ns_parser.source == "EconDB":
|
||||
econdb_view.plot_tips(
|
||||
ns_parser.parameter,
|
||||
ns_parser.start_date,
|
||||
ns_parser.end_date,
|
||||
ns_parser.export,
|
||||
)
|
||||
|
||||
@log_start_end(log=logger)
|
||||
def call_tbffr(self, other_args: List[str]):
|
||||
"""Process tbffr command"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="tbffr",
|
||||
description="Get Selected Treasury Bill Minus Federal Funds Rate.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-p",
|
||||
"--parameter",
|
||||
dest="parameter",
|
||||
type=str,
|
||||
help="Selected Treasury Bill",
|
||||
default="3_month",
|
||||
choices=list(self.tbffr_parameter_to_fred_id.keys()),
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s",
|
||||
"--start",
|
||||
dest="start_date",
|
||||
type=valid_date,
|
||||
help="Starting date (YYYY-MM-DD) of data",
|
||||
default=None,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-e",
|
||||
"--end",
|
||||
dest="end_date",
|
||||
type=valid_date,
|
||||
help="Ending date (YYYY-MM-DD) of data",
|
||||
default=None,
|
||||
)
|
||||
ns_parser = self.parse_known_args_and_warn(
|
||||
parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES
|
||||
)
|
||||
if ns_parser:
|
||||
fred_view.plot_tbffr(
|
||||
self.tbffr_parameter_to_fred_id[ns_parser.parameter],
|
||||
ns_parser.start_date,
|
||||
ns_parser.end_date,
|
||||
ns_parser.export,
|
||||
)
|
||||
|
||||
@log_start_end(log=logger)
|
||||
def call_ty(self, other_args: List[str]):
|
||||
"""Process ty command"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="ty",
|
||||
description="Plot Selected Treasury Yield.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-p",
|
||||
"--parameter",
|
||||
dest="parameter",
|
||||
type=str,
|
||||
help="Selected Treasury Yield",
|
||||
default="10_year",
|
||||
choices=["5_year", "10_year", "30_year"],
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s",
|
||||
"--start",
|
||||
dest="start_date",
|
||||
type=valid_date,
|
||||
help="Starting date (YYYY-MM-DD) of data",
|
||||
default=None,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-e",
|
||||
"--end",
|
||||
dest="end_date",
|
||||
type=valid_date,
|
||||
help="Ending date (YYYY-MM-DD) of data",
|
||||
default=None,
|
||||
)
|
||||
ns_parser = self.parse_known_args_and_warn(
|
||||
parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES
|
||||
)
|
||||
if ns_parser:
|
||||
yfinance_view.plot_ty(
|
||||
ns_parser.parameter,
|
||||
ns_parser.start_date,
|
||||
ns_parser.end_date,
|
||||
ns_parser.export,
|
||||
)
|
||||
|
||||
@@ -101,6 +101,37 @@ ID_TO_NAME_FFRMC = {
|
||||
"T5YFF": "5-Year",
|
||||
"T1YFF": "1-Year",
|
||||
"T6MFF": "6-Month",
|
||||
"T3MFF": "3-Month",
|
||||
}
|
||||
ID_TO_NAME_SECONDARY = {
|
||||
"TB3MS": "3-Month",
|
||||
"DTB4WK": "4-Week",
|
||||
"DTB1YR": "1-Year",
|
||||
"DTB6": "6-Month"
|
||||
}
|
||||
ID_TO_NAME_TIPS = {
|
||||
"DFII5": "5-Year",
|
||||
"DFII7": "7-Year",
|
||||
"DFII10": "10-Year",
|
||||
"DFII20": "20-Year",
|
||||
"DFII30": "30-Year",
|
||||
}
|
||||
ID_TO_NAME_CMN = {
|
||||
"DGS1MO": "1 Month",
|
||||
"DGS3MO": "3 Month",
|
||||
"DGS6MO": "6 Month",
|
||||
"DGS1": "1 Year",
|
||||
"DGS2": "2 Year",
|
||||
"DGS3": "3 Year",
|
||||
"DGS5": "5 Year",
|
||||
"DGS7": "7 Year",
|
||||
"DGS10": "10 Year",
|
||||
"DGS20": "20 Year",
|
||||
"DGS30": "30 Year",
|
||||
}
|
||||
ID_TO_NAME_TBFFR = {
|
||||
"TB3SMFFM": "3 Month",
|
||||
"TB6SMFFM": "6 Month",
|
||||
}
|
||||
|
||||
|
||||
@@ -1184,7 +1215,7 @@ def plot_ffrmc(
|
||||
Parameters
|
||||
----------
|
||||
series_id: str
|
||||
FRED ID of FFRMC data to plot, options: ['T10YFF', 'T5YFF', 'T1YFF', 'T6MFF']
|
||||
FRED ID of FFRMC data to plot, options: ['T10YFF', 'T5YFF', 'T1YFF', 'T6MFF', 'T3MFF']
|
||||
start_date: Optional[str]
|
||||
Start date, formatted YYYY-MM-DD
|
||||
end_date: Optional[str]
|
||||
@@ -1228,7 +1259,7 @@ def plot_ffrmc(
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)),
|
||||
f"tmc, {series_id}",
|
||||
f"ffrmc, {series_id}",
|
||||
df,
|
||||
)
|
||||
|
||||
@@ -1377,3 +1408,274 @@ def display_inflation_indexed_yield_curve(
|
||||
"iiycrv",
|
||||
rates,
|
||||
)
|
||||
|
||||
|
||||
@log_start_end(log=logger)
|
||||
@check_api_key(["API_FRED_KEY"])
|
||||
def plot_tbill(
|
||||
series_id: str = "TB3MS",
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
export: str = "",
|
||||
external_axes: Optional[List[plt.Axes]] = None,
|
||||
):
|
||||
"""Plot Treasury Bill Secondary Market Rate.
|
||||
|
||||
A Treasury Bill (T-Bill) is a short-term U.S. government debt obligation backed by the Treasury Department with a
|
||||
maturity of one year or less. Treasury bills are usually sold in denominations of $1,000. However, some can reach
|
||||
a maximum denomination of $5 million in non-competitive bids. These securities are widely regarded as low-risk
|
||||
and secure investments.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
series_id: str
|
||||
FRED ID of Treasury Bill Secondary Market Rate data to plot, options: ['TB3MS', 'DTB4WK', 'DTB1YR', 'DTB6']
|
||||
start_date: Optional[str]
|
||||
Start date, formatted YYYY-MM-DD
|
||||
end_date: Optional[str]
|
||||
End date, formatted YYYY-MM-DD
|
||||
export: str
|
||||
Export data to csv or excel file
|
||||
external_axes: Optional[List[plt.Axes]]
|
||||
External axes (1 axis is expected in the list)
|
||||
"""
|
||||
df = fred_model.get_series_data(
|
||||
series_id=series_id, start_date=start_date, end_date=end_date
|
||||
)
|
||||
|
||||
# This plot has 1 axis
|
||||
if not external_axes:
|
||||
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
elif is_valid_axes_count(external_axes, 1):
|
||||
(ax,) = external_axes
|
||||
else:
|
||||
return
|
||||
|
||||
colors = cycle(theme.get_colors())
|
||||
ax.plot(
|
||||
df.index,
|
||||
df.values,
|
||||
marker="o",
|
||||
linestyle="dashed",
|
||||
linewidth=2,
|
||||
markersize=4,
|
||||
color=next(colors, "#FCED00"),
|
||||
)
|
||||
ax.set_title(f"{ID_TO_NAME_SECONDARY[series_id]} Treasury Bill Secondary Market Rate, Discount Basis [Percent]")
|
||||
theme.style_primary_axis(ax)
|
||||
|
||||
if external_axes is None:
|
||||
theme.visualize_output()
|
||||
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)),
|
||||
f"tbill, {series_id}",
|
||||
df,
|
||||
)
|
||||
|
||||
|
||||
@log_start_end(log=logger)
|
||||
@check_api_key(["API_FRED_KEY"])
|
||||
def plot_cmn(
|
||||
series_id: str = "DGS10",
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
export: str = "",
|
||||
external_axes: Optional[List[plt.Axes]] = None,
|
||||
):
|
||||
"""Plot Treasury Constant Maturity Nominal Market Yield.
|
||||
|
||||
Yields on Treasury nominal securities at “constant maturity” are interpolated by the U.S. Treasury from the daily
|
||||
yield curve for non-inflation-indexed Treasury securities. This curve, which relates the yield on a security to
|
||||
its time to maturity, is based on the closing market bid yields on actively traded Treasury securities in the
|
||||
over-the-counter market. These market yields are calculated from composites of quotations obtained by the Federal
|
||||
Reserve Bank of New York. The constant maturity yield values are read from the yield curve at fixed maturities,
|
||||
currently 1, 3, and 6 months and 1, 2, 3, 5, 7, 10, 20, and 30 years. This method provides a yield for a 10-year
|
||||
maturity, for example, even if no outstanding security has exactly 10 years remaining to maturity. Similarly,
|
||||
yields on inflation-indexed securities at “constant maturity” are interpolated from the daily yield curve for
|
||||
Treasury inflation protected securities in the over-the-counter market. The inflation-indexed constant maturity
|
||||
yields are read from this yield curve at fixed maturities, currently 5, 7, 10, 20, and 30 years.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
series_id: str
|
||||
FRED ID of Treasury Constant Maturity Nominal Market Yield data to plot, options: ['DGS1MO', 'DGS3MO', 'DGS6MO', 'DGS1', 'DGS2', 'DGS3', 'DGS5', 'DGS7', 'DGS10', 'DGS20', DGS30']
|
||||
start_date: Optional[str]
|
||||
Start date, formatted YYYY-MM-DD
|
||||
end_date: Optional[str]
|
||||
End date, formatted YYYY-MM-DD
|
||||
export: str
|
||||
Export data to csv or excel file
|
||||
external_axes: Optional[List[plt.Axes]]
|
||||
External axes (1 axis is expected in the list)
|
||||
"""
|
||||
df = fred_model.get_series_data(
|
||||
series_id=series_id, start_date=start_date, end_date=end_date
|
||||
)
|
||||
|
||||
# This plot has 1 axis
|
||||
if not external_axes:
|
||||
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
elif is_valid_axes_count(external_axes, 1):
|
||||
(ax,) = external_axes
|
||||
else:
|
||||
return
|
||||
|
||||
colors = cycle(theme.get_colors())
|
||||
ax.plot(
|
||||
df.index,
|
||||
df.values,
|
||||
marker="o",
|
||||
linestyle="dashed",
|
||||
linewidth=2,
|
||||
markersize=4,
|
||||
color=next(colors, "#FCED00"),
|
||||
)
|
||||
ax.set_title(f"{ID_TO_NAME_CMN[series_id]} Treasury Constant Maturity Nominal Market Yield [Percent]")
|
||||
theme.style_primary_axis(ax)
|
||||
|
||||
if external_axes is None:
|
||||
theme.visualize_output()
|
||||
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)),
|
||||
f"cmn, {series_id}",
|
||||
df,
|
||||
)
|
||||
|
||||
|
||||
@log_start_end(log=logger)
|
||||
@check_api_key(["API_FRED_KEY"])
|
||||
def plot_tips(
|
||||
series_id: str = "DFII10",
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
export: str = "",
|
||||
external_axes: Optional[List[plt.Axes]] = None,
|
||||
):
|
||||
"""Plot Plot Yields on Treasury inflation protected securities (TIPS) adjusted to constant maturities.
|
||||
|
||||
Yields on Treasury nominal securities at “constant maturity” are interpolated by the U.S. Treasury from the daily
|
||||
yield curve for non-inflation-indexed Treasury securities. This curve, which relates the yield on a security to
|
||||
its time to maturity, is based on the closing market bid yields on actively traded Treasury securities in the
|
||||
over-the-counter market. These market yields are calculated from composites of quotations obtained by the Federal
|
||||
Reserve Bank of New York. The constant maturity yield values are read from the yield curve at fixed maturities,
|
||||
currently 1, 3, and 6 months and 1, 2, 3, 5, 7, 10, 20, and 30 years. This method provides a yield for a 10-year
|
||||
maturity, for example, even if no outstanding security has exactly 10 years remaining to maturity. Similarly,
|
||||
yields on inflation-indexed securities at “constant maturity” are interpolated from the daily yield curve for
|
||||
Treasury inflation protected securities in the over-the-counter market. The inflation-indexed constant maturity
|
||||
yields are read from this yield curve at fixed maturities, currently 5, 7, 10, 20, and 30 years.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
series_id: str
|
||||
FRED ID of TIPS adjusted to constant maturities data to plot, options: ['DFII5', 'DFII7', 'DFII10', 'DFII20', 'DFII30']
|
||||
start_date: Optional[str]
|
||||
Start date, formatted YYYY-MM-DD
|
||||
end_date: Optional[str]
|
||||
End date, formatted YYYY-MM-DD
|
||||
export: str
|
||||
Export data to csv or excel file
|
||||
external_axes: Optional[List[plt.Axes]]
|
||||
External axes (1 axis is expected in the list)
|
||||
"""
|
||||
df = fred_model.get_series_data(
|
||||
series_id=series_id, start_date=start_date, end_date=end_date
|
||||
)
|
||||
|
||||
# This plot has 1 axis
|
||||
if not external_axes:
|
||||
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
elif is_valid_axes_count(external_axes, 1):
|
||||
(ax,) = external_axes
|
||||
else:
|
||||
return
|
||||
|
||||
colors = cycle(theme.get_colors())
|
||||
ax.plot(
|
||||
df.index,
|
||||
df.values,
|
||||
marker="o",
|
||||
linestyle="dashed",
|
||||
linewidth=2,
|
||||
markersize=4,
|
||||
color=next(colors, "#FCED00"),
|
||||
)
|
||||
ax.set_title(f"{ID_TO_NAME_TIPS[series_id]} Yields on Treasury inflation protected securities (TIPS) adjusted to "
|
||||
f"constant maturities [Percent]")
|
||||
theme.style_primary_axis(ax)
|
||||
|
||||
if external_axes is None:
|
||||
theme.visualize_output()
|
||||
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)),
|
||||
f"tips, {series_id}",
|
||||
df,
|
||||
)
|
||||
|
||||
|
||||
@log_start_end(log=logger)
|
||||
@check_api_key(["API_FRED_KEY"])
|
||||
def plot_tbffr(
|
||||
series_id: str = "TB3SMFFM",
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
export: str = "",
|
||||
external_axes: Optional[List[plt.Axes]] = None,
|
||||
):
|
||||
"""Plot Selected Treasury Bill Minus Federal Funds Rate data.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
series_id: str
|
||||
FRED ID of TBFFR data to plot, options: ['TB3SMFFM', 'TB6SMFFM']
|
||||
start_date: Optional[str]
|
||||
Start date, formatted YYYY-MM-DD
|
||||
end_date: Optional[str]
|
||||
End date, formatted YYYY-MM-DD
|
||||
export: str
|
||||
Export data to csv or excel file
|
||||
external_axes: Optional[List[plt.Axes]]
|
||||
External axes (1 axis is expected in the list)
|
||||
"""
|
||||
df = fred_model.get_series_data(
|
||||
series_id=series_id, start_date=start_date, end_date=end_date
|
||||
)
|
||||
|
||||
# This plot has 1 axis
|
||||
if not external_axes:
|
||||
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
elif is_valid_axes_count(external_axes, 1):
|
||||
(ax,) = external_axes
|
||||
else:
|
||||
return
|
||||
|
||||
colors = cycle(theme.get_colors())
|
||||
ax.plot(
|
||||
df.index,
|
||||
df.values,
|
||||
marker="o",
|
||||
linestyle="dashed",
|
||||
linewidth=2,
|
||||
markersize=4,
|
||||
color=next(colors, "#FCED00"),
|
||||
)
|
||||
ax.set_title(
|
||||
ID_TO_NAME_TBFFR[series_id]
|
||||
+ " Treasury Bill Minus Federal Funds Rate [Percent]"
|
||||
)
|
||||
theme.style_primary_axis(ax)
|
||||
|
||||
if external_axes is None:
|
||||
theme.visualize_output()
|
||||
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)),
|
||||
f"tbffr, {series_id}",
|
||||
df,
|
||||
)
|
||||
|
||||
77
openbb_terminal/fixedincome/yfinance_model.py
Normal file
77
openbb_terminal/fixedincome/yfinance_model.py
Normal file
@@ -0,0 +1,77 @@
|
||||
""" Yahoo Finance Model """
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
import pandas as pd
|
||||
import yfinance as yf
|
||||
|
||||
from openbb_terminal.decorators import log_start_end
|
||||
from openbb_terminal.rich_config import console
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@log_start_end(log=logger)
|
||||
def get_series(
|
||||
series_id: str,
|
||||
interval: str = "1d",
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
column: str = "Adj Close",
|
||||
) -> pd.Series:
|
||||
"""Obtain data on any index [Source: Yahoo Finance]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
series_id: str
|
||||
The series you wish to collect data for.
|
||||
start_date : Optional[str]
|
||||
the selected country
|
||||
end_date : Optional[str]
|
||||
The currency you wish to convert the data to.
|
||||
interval : str
|
||||
Valid intervals: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo or 3mo
|
||||
Intraday data cannot extend last 60 days
|
||||
column : str
|
||||
The column you wish to select, by default this is Adjusted Close.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.Series
|
||||
A series with the requested index
|
||||
"""
|
||||
try:
|
||||
if start_date:
|
||||
datetime.strptime(str(start_date), "%Y-%m-%d")
|
||||
if end_date:
|
||||
datetime.strptime(str(end_date), "%Y-%m-%d")
|
||||
except ValueError:
|
||||
console.print("[red]Please format date as YYYY-MM-DD[/red]\n")
|
||||
return pd.Series(dtype="object")
|
||||
|
||||
index_data = yf.download(
|
||||
series_id,
|
||||
start=start_date,
|
||||
end=end_date,
|
||||
interval=interval,
|
||||
progress=False,
|
||||
show_errors=False,
|
||||
)
|
||||
|
||||
if column not in index_data.columns:
|
||||
console.print(
|
||||
f"The chosen column is not available for {series_id}. Please choose "
|
||||
f"between: {', '.join(index_data.columns)}\n"
|
||||
)
|
||||
return pd.Series(dtype="float64")
|
||||
if index_data.empty or len(index_data) < 2:
|
||||
console.print(
|
||||
f"The chosen index {series_id}, returns no data. Please check if "
|
||||
f"there is any data available.\n"
|
||||
)
|
||||
return pd.Series(dtype="float64")
|
||||
|
||||
return index_data[column]
|
||||
81
openbb_terminal/fixedincome/yfinance_view.py
Normal file
81
openbb_terminal/fixedincome/yfinance_view.py
Normal file
@@ -0,0 +1,81 @@
|
||||
""" Yahoo Finance view """
|
||||
__docformat__ = "numpy"
|
||||
|
||||
from typing import Optional, List
|
||||
from itertools import cycle
|
||||
import logging
|
||||
import os
|
||||
|
||||
from matplotlib import pyplot as plt
|
||||
|
||||
from openbb_terminal.config_terminal import theme
|
||||
from openbb_terminal.config_plot import PLOT_DPI
|
||||
from openbb_terminal.decorators import log_start_end, check_api_key
|
||||
from openbb_terminal.helper_funcs import (
|
||||
export_data,
|
||||
plot_autoscale,
|
||||
is_valid_axes_count,
|
||||
)
|
||||
from openbb_terminal.fixedincome import yfinance_model
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TY_TO_ID = {
|
||||
"5_year": "^FVX",
|
||||
"10_year": "^TNX",
|
||||
"30_year": "^TYX",
|
||||
}
|
||||
|
||||
|
||||
@log_start_end(log=logger)
|
||||
@check_api_key(["API_FRED_KEY"])
|
||||
def plot_ty(
|
||||
maturity: str = "3_month",
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
export: str = "",
|
||||
external_axes: Optional[List[plt.Axes]] = None,
|
||||
):
|
||||
"""Plot Treasury Yield.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
maturity: str
|
||||
Maturity to plot, options: ['5_year', '10_year', '30_year']
|
||||
start_date: Optional[str]
|
||||
Start date, formatted YYYY-MM-DD
|
||||
end_date: Optional[str]
|
||||
End date, formatted YYYY-MM-DD
|
||||
export: str
|
||||
Export data to csv or excel file
|
||||
external_axes: Optional[List[plt.Axes]]
|
||||
External axes (1 axis is expected in the list)
|
||||
"""
|
||||
df = yfinance_model.get_series(TY_TO_ID[maturity], start_date=start_date, end_date=end_date)
|
||||
|
||||
# This plot has 1 axis
|
||||
if not external_axes:
|
||||
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
elif is_valid_axes_count(external_axes, 1):
|
||||
(ax,) = external_axes
|
||||
else:
|
||||
return
|
||||
|
||||
colors = cycle(theme.get_colors())
|
||||
ax.plot(
|
||||
df.index,
|
||||
df.values,
|
||||
color=next(colors, "#FCED00"),
|
||||
)
|
||||
ax.set_title(f"{maturity.replace('-', ' ')} Treasury Yield [Percent]")
|
||||
theme.style_primary_axis(ax)
|
||||
|
||||
if external_axes is None:
|
||||
theme.visualize_output()
|
||||
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)),
|
||||
f"ty, {maturity}",
|
||||
df,
|
||||
)
|
||||
@@ -525,7 +525,12 @@
|
||||
"ffrmc": ["FRED"],
|
||||
"ycrv": ["FRED"],
|
||||
"iiycrv": ["FRED"],
|
||||
"ecbycrv": ["ECB"]
|
||||
"ecbycrv": ["ECB"],
|
||||
"tbill": ["FRED", "EconDB"],
|
||||
"cmn": ["FRED", "EconDB"],
|
||||
"tips": ["FRED", "EconDB"],
|
||||
"tbffr": ["FRED"],
|
||||
"ty": ["YahooFinance"]
|
||||
},
|
||||
"alternative": {
|
||||
"oss": {
|
||||
|
||||
12
openbb_terminal/miscellaneous/i18n/en.yml
vendored
12
openbb_terminal/miscellaneous/i18n/en.yml
vendored
@@ -790,13 +790,19 @@ en:
|
||||
fixedincome/ecbmrofr: ECB main refinancing operations rate, fixed rate tender
|
||||
fixedincome/stir: plot countries (incl. forecasted) short term interest rate
|
||||
fixedincome/ltir: plot countries (incl. forecasted) long term interest rate
|
||||
fixedincome/_constant_maturities_spreads_: Constant Maturity Spreads
|
||||
fixedincome/tmc: 10-year treasury constant maturity minus selected treasury constant maturity
|
||||
fixedincome/ffrmc: selected treasury constant maturity minus federal funds rate
|
||||
fixedincome/_yield_curves_: Yield curves
|
||||
fixedincome/ycrv: plot US yield curve
|
||||
fixedincome/iiycrv: plot US inflation-indexed yield curve
|
||||
fixedincome/ecbycrv: plot euro area yield curve
|
||||
fixedincome/_us_government_securities_: US government securities
|
||||
fixedincome/tbill: plot secondary market rate of treasury bills
|
||||
fixedincome/cmn: plot nominal constant maturity treasuries
|
||||
fixedincome/tips: plot treasury inflation protected securities (tips)
|
||||
fixedincome/ty: plot treasury yields
|
||||
fixedincome/_spreads_: Spreads
|
||||
fixedincome/tmc: 10-year treasury constant maturity minus selected treasury constant maturity
|
||||
fixedincome/ffrmc: selected treasury constant maturity minus federal funds rate
|
||||
fixedincome/tbffr: selected treasury bill minus federal funds rate
|
||||
forex/_ticker: Ticker
|
||||
forex/_from: From
|
||||
forex/_to: To
|
||||
|
||||
Reference in New Issue
Block a user