-
Notifications
You must be signed in to change notification settings - Fork 3.2k
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/yieldcurve #1734
Merged
DidierRLopes
merged 21 commits into
OpenBB-finance:main
from
montezdesousa:feature/yieldcurve
May 17, 2022
Merged
Feature/yieldcurve #1734
Changes from 13 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
8ccd963
Adds yield curves
montezdesousa 13704d7
Adds yield curves for several countries
montezdesousa e6242f8
Adds yield curves for several countries
montezdesousa 056623f
Adds yield curves for several countries
montezdesousa ac1749d
Adds yield curves for several countries
montezdesousa 6689ca6
Adds yield curves for several countries
montezdesousa c1f0a2c
Merge branch 'main' into feature/yieldcurve
JerBouma 2d3e414
Merge branch 'main' into feature/yieldcurve
jose-donato f501ee2
Merge branch 'OpenBB-finance:main' into feature/yieldcurve
montezdesousa 0577c46
Merge branch 'main' into feature/yieldcurve
montezdesousa 3adc1d9
Merge branch 'main' into feature/yieldcurve
DidierRLopes 78881cc
Merge branch 'OpenBB-finance:main' into feature/yieldcurve
montezdesousa df59824
ycrv plots by default
montezdesousa 1573a55
Merge branch 'OpenBB-finance:main' into feature/yieldcurve
montezdesousa 86838fb
Limits source choices and renames raw columns
montezdesousa d4674a9
Merge branch 'main' into feature/yieldcurve
jmaslek 92ad6ef
Fix test
jmaslek e2ee3f0
Merge remote-tracking branch 'montezdesousa/feature/yieldcurve' into …
jmaslek d591f5b
Merge branch 'main' into feature/yieldcurve
DidierRLopes e328581
Fix test
jmaslek 2486781
lint
jmaslek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -26,6 +26,8 @@ | |
fred_model, | ||
yfinance_model, | ||
yfinance_view, | ||
investingcom_model, | ||
investingcom_view, | ||
plot_view, | ||
) | ||
from openbb_terminal.helper_funcs import ( | ||
|
@@ -63,6 +65,7 @@ class EconomyController(BaseController): | |
"rtps", | ||
"industry", | ||
"bigmac", | ||
"ycrv", | ||
] | ||
|
||
CHOICES_MENUS = ["pred", "qa"] | ||
|
@@ -172,6 +175,11 @@ def __init__(self, queue: List[str] = None): | |
c: None for c in econdb_model.COUNTRY_CODES | ||
} | ||
|
||
self.choices["ycrv"]["-c"] = {c: None for c in investingcom_model.COUNTRIES} | ||
self.choices["ycrv"]["--countries"] = { | ||
c: None for c in investingcom_model.COUNTRIES | ||
} | ||
|
||
self.choices["valuation"]["-s"] = { | ||
c: None for c in self.valuation_sort_cols | ||
} | ||
|
@@ -224,6 +232,7 @@ def print_help(self): | |
index find and plot any (major) index on the market [src][Source: Yahoo Finance][/src] | ||
treasury obtain U.S. treasury rates [src][Source: EconDB][/src] | ||
yield show the U.S. Treasury yield curve [src][Source: FRED][/src] | ||
ycrv show sovereign yield curves [src][Source: Investing.com/FRED][/src] | ||
plot plot data from the above commands together | ||
options show the available options for 'plot' or show/export the data | ||
|
||
|
@@ -966,6 +975,63 @@ def call_yield(self, other_args: List[str]): | |
if ns_parser: | ||
fred_view.display_yield_curve(ns_parser.date) | ||
|
||
@log_start_end(log=logger) | ||
def call_ycrv(self, other_args: List[str]): | ||
"""Process ycrv command""" | ||
parser = argparse.ArgumentParser( | ||
add_help=False, | ||
formatter_class=argparse.ArgumentDefaultsHelpFormatter, | ||
prog="ycrv", | ||
description="Generate country yield curve. The yield curve shows the bond rates" | ||
" at different maturities.", | ||
) | ||
parser.add_argument( | ||
"-s", | ||
"--source", | ||
action="store", | ||
dest="source", | ||
type=str, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you can use parameter |
||
default="investpy", | ||
help="Source for the data. If not supplied, the most recent entry from Investpy will be used.", | ||
) | ||
parser.add_argument( | ||
"-c", | ||
"--country", | ||
action="store", | ||
dest="country", | ||
nargs="+", | ||
default="united states", | ||
help="Display yield curve for specific country.", | ||
) | ||
parser.add_argument( | ||
"-d", | ||
"--date", | ||
type=valid_date, | ||
help="Date to get data from FRED. If not supplied, the most recent entry will be used.", | ||
dest="date", | ||
default=None, | ||
) | ||
ns_parser = parse_known_args_and_warn( | ||
parser, | ||
other_args, | ||
export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED, | ||
raw=True, | ||
) | ||
if ns_parser: | ||
if isinstance(ns_parser.country, list): | ||
ns_parser.country = " ".join(ns_parser.country) | ||
|
||
investingcom_model.check_correct_country(ns_parser.country) | ||
|
||
if ns_parser.source == "FRED": | ||
fred_view.display_yield_curve(ns_parser.date) | ||
else: | ||
investingcom_view.display_yieldcurve( | ||
country=ns_parser.country, | ||
raw=ns_parser.raw, | ||
export=ns_parser.export, | ||
) | ||
|
||
@log_start_end(log=logger) | ||
def call_plot(self, other_args: List[str]): | ||
"""Process plot command""" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
""" Investing.com Model """ | ||
__docformat__ = "numpy" | ||
|
||
import logging | ||
import argparse | ||
|
||
import pandas as pd | ||
import investpy | ||
|
||
from openbb_terminal.decorators import log_start_end | ||
from openbb_terminal.helper_funcs import log_and_raise | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
COUNTRIES = investpy.bonds.get_bond_countries() | ||
|
||
|
||
def check_correct_country(country): | ||
"""Argparse type to check that correct country is inserted""" | ||
if country not in investpy.bonds.get_bond_countries(): | ||
log_and_raise( | ||
argparse.ArgumentTypeError( | ||
f"{country} is an invalid country. Choose from {', '.join(investpy.bonds.get_bond_countries())}" | ||
) | ||
) | ||
return country | ||
|
||
|
||
@log_start_end(log=logger) | ||
def get_yieldcurve(country) -> pd.DataFrame: | ||
"""Get country yield curve [Source: Investing.com] | ||
|
||
Returns | ||
------- | ||
pd.DataFrame | ||
Country yield curve | ||
""" | ||
|
||
data = investpy.bonds.get_bonds_overview(country) | ||
|
||
return data |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
""" Investing.com View """ | ||
__docformat__ = "numpy" | ||
|
||
import logging | ||
import os | ||
from typing import Optional, List | ||
|
||
import matplotlib.pyplot as plt | ||
from pandas.plotting import register_matplotlib_converters | ||
|
||
from openbb_terminal.config_plot import PLOT_DPI | ||
from openbb_terminal.config_terminal import theme | ||
from openbb_terminal.decorators import log_start_end | ||
from openbb_terminal.economy import investingcom_model | ||
from openbb_terminal.helper_funcs import ( | ||
export_data, | ||
plot_autoscale, | ||
print_rich_table, | ||
) | ||
from openbb_terminal.rich_config import console | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
register_matplotlib_converters() | ||
|
||
tenors_dict = { | ||
"1M": 1 / 12, | ||
"3M": 0.25, | ||
"6M": 0.5, | ||
"9M": 0.75, | ||
"1Y": 1, | ||
"2Y": 2, | ||
"3Y": 3, | ||
"4Y": 4, | ||
"5Y": 5, | ||
"6Y": 6, | ||
"7Y": 7, | ||
"8Y": 8, | ||
"9Y": 9, | ||
"10Y": 10, | ||
"15Y": 15, | ||
"20Y": 20, | ||
"25Y": 25, | ||
"30Y": 30, | ||
"50Y": 50, | ||
} | ||
|
||
|
||
@log_start_end(log=logger) | ||
def display_yieldcurve( | ||
country: str, | ||
external_axes: Optional[List[plt.Axes]] = None, | ||
raw: bool = False, | ||
export: str = "", | ||
): | ||
"""Display yield curve. [Source: Investing.com] | ||
|
||
Parameters | ||
---------- | ||
country: str | ||
Country to display | ||
export : str | ||
Export dataframe data to csv,json,xlsx file | ||
""" | ||
country = country.replace("_", " ") | ||
df = investingcom_model.get_yieldcurve(country) | ||
df = df.replace(float("NaN"), "") | ||
|
||
if df.empty: | ||
console.print(f"[red]Yield data not found for {country.title()}[/red].\n") | ||
return | ||
if external_axes is None: | ||
_, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) | ||
|
||
else: | ||
if len(external_axes) != 1: | ||
logger.error("Expected list of 3 axis items") | ||
console.print("[red]Expected list of 3 axis items.\n[/red]") | ||
return | ||
(ax,) = external_axes | ||
|
||
df.drop(columns=df.columns[0], axis=1, inplace=True) | ||
|
||
tenors = [] | ||
for t in df["name"]: | ||
if t[-1] == "M": | ||
tenors.append(int(t[-t[::-1].find(" ") : -1]) / 12) | ||
elif t[-1] == "Y": | ||
tenors.append(int(t[-t[::-1].find(" ") : -1])) | ||
|
||
ax.plot(tenors, df["last"], "-o") | ||
ax.set_xlabel("Maturity") | ||
ax.set_ylabel("Rate (%)") | ||
theme.style_primary_axis(ax) | ||
if external_axes is None: | ||
ax.set_title(f"Yield Curve for {country.title()} ") | ||
theme.visualize_output() | ||
|
||
if raw: | ||
print_rich_table( | ||
df, | ||
headers=list(df.columns), | ||
show_index=False, | ||
title=f"{country.title()} Yield Curve", | ||
) | ||
console.print("") | ||
|
||
export_data( | ||
export, | ||
os.path.dirname(os.path.abspath(__file__)), | ||
"ycrv", | ||
df, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# IMPORTATION STANDARD | ||
|
||
# IMPORTATION THIRDPARTY | ||
import pandas as pd | ||
import pytest | ||
|
||
# IMPORTATION INTERNAL | ||
from openbb_terminal.economy import investingcom_model | ||
|
||
|
||
# @pytest.mark.vcr | ||
@pytest.mark.parametrize( | ||
"country", | ||
[ | ||
"united states", | ||
"portugal", | ||
"spain", | ||
"germany", | ||
], | ||
) | ||
def test_get_yieldcurve(country): | ||
result_df = investingcom_model.get_yieldcurve(country) | ||
|
||
assert isinstance(result_df, pd.DataFrame) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
# IMPORTATION STANDARD | ||
# import gzip | ||
|
||
# IMPORTATION THIRDPARTY | ||
# import pandas as pd | ||
|
||
# import pytest | ||
|
||
# IMPORTATION INTERNAL | ||
from openbb_terminal.economy import investingcom_view | ||
|
||
|
||
# @pytest.mark.vcr | ||
# @pytest.mark.record_stdout | ||
def test_display_yieldcurve(): | ||
investingcom_view.display_yieldcurve(country="portugal", export="") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@montezdesousa you want to remove your key here 😄