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

Country debt #2311

Merged
merged 11 commits into from
Aug 16, 2022
Merged
Show file tree
Hide file tree
Changes from 10 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
1 change: 1 addition & 0 deletions i18n/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -783,6 +783,7 @@ en:
economy/treasury: obtain U.S. treasury rates
economy/ycrv: show sovereign yield curves
economy/events: display economic calendar
economy/cdebt: shows debt statistics for various countries
economy/plot: plot data from the above commands together
economy/rtps: real-time performance sectors
economy/valuation: valuation of sectors, industry, country
Expand Down
44 changes: 44 additions & 0 deletions openbb_terminal/economy/commodity_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import logging
import re

import requests
import pandas as pd

from openbb_terminal.decorators import log_start_end
from openbb_terminal.helper_funcs import get_user_agent

logger = logging.getLogger(__name__)


def format_number(text: str) -> float:
numbers = re.findall(r"[-+]?(?:\d*\.\d+|\d+)", text)
if "t" in text.lower():
multiplier = 1_000_000_000_000
elif "b" in text.lower():
multiplier = 1_000_000_000
elif "m" in text.lower():
multiplier = 1_000_000
else:
multiplier = 1

return round(float(numbers[0]) * multiplier, 2)


@log_start_end(log=logger)
def get_debt() -> pd.DataFrame:
"Retrieves national debt information for various countries. [Source: wikipedia.org]"
url = "https://en.wikipedia.org/wiki/List_of_countries_by_external_debt"
response = requests.get(url, headers={"User-Agent": get_user_agent()})
df = pd.read_html(response.text)[0]
df = df.rename(
columns={
"Country/Region": "Country",
"External debtUS dollars": "Debt",
"Per capitaUS dollars": "Per Capita",
}
)
df = df.set_index("Rank")
df = df.drop(["Date", "% of GDP"], axis=1)
df["Debt"] = df["Debt"].apply(lambda x: format_number(x))
df = df[["Country", "Debt", "Per Capita"]]
return df
52 changes: 52 additions & 0 deletions openbb_terminal/economy/commodity_view.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import os
import logging

from openbb_terminal.decorators import log_start_end
from openbb_terminal.economy import commodity_model
from openbb_terminal.helper_funcs import export_data, print_rich_table

logger = logging.getLogger(__name__)


def format_large_numbers(num: float) -> str:
"""Converts floats into strings and adds commas to the number

Parameters
----------
num: float
The number to convert

Returns
----------
num: str
The formatted number
"""
return f"{num:,}"


@log_start_end(log=logger)
def display_debt(export: str = "", limit: int = 20):
"""Displays national debt for given countries [Source: Yahoo Finance]

Parameters
----------
export : str
The path to export to
limit : int
The number of countries to show
"""
debt_df = commodity_model.get_debt()

for col in ["Debt", "Per Capita"]:
debt_df[col] = debt_df[col].apply(lambda x: format_large_numbers(x))

print_rich_table(
debt_df[:limit],
show_index=True,
headers=debt_df.columns,
title="National Debt (USD)",
)
if export:
export_data(
export, os.path.dirname(os.path.abspath(__file__)), "cdebt", debt_df
)
26 changes: 23 additions & 3 deletions openbb_terminal/economy/economy_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
investingcom_model,
investingcom_view,
plot_view,
commodity_view,
)
from openbb_terminal.helper_funcs import (
EXPORT_BOTH_RAW_DATA_AND_FIGURES,
Expand All @@ -38,9 +39,9 @@
print_rich_table,
valid_date,
)
from openbb_terminal.menu import session
from openbb_terminal.parent_classes import BaseController
from openbb_terminal.rich_config import console, MenuText
from openbb_terminal.menu import session

logger = logging.getLogger(__name__)

Expand All @@ -65,6 +66,7 @@ class EconomyController(BaseController):
"bigmac",
"ycrv",
"events",
"cdebt",
]

CHOICES_MENUS = ["pred", "qa"]
Expand Down Expand Up @@ -259,6 +261,7 @@ def print_help(self):
mt.add_cmd("bigmac", "NASDAQ Datalink")
mt.add_cmd("ycrv", "Investing.com / FRED")
mt.add_cmd("events", "Investing.com")
mt.add_cmd("cdebt", "USDebtClock.org")
mt.add_raw("\n")
mt.add_cmd("rtps", "Alpha Vantage")
mt.add_cmd("valuation", "Finviz")
Expand Down Expand Up @@ -287,8 +290,8 @@ def call_overview(self, other_args: List[str]):
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="overview",
description="""
Provide a market overview of a variety of options. This can be a general overview, indices,
bonds and currencies. [Source: Wall St. Journal]
Provide a market overview of a variety of options. This can be a general overview,
indices, bonds and currencies. [Source: Wall St. Journal]
""",
)

Expand Down Expand Up @@ -1388,6 +1391,23 @@ def call_performance(self, other_args: List[str]):
export=ns_parser.export,
)

@log_start_end(log=logger)
def call_cdebt(self, other_args: List[str]):
"""Process cdebt command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="cdebt",
description="""
National debt statistics for various countries. [Source: Wikipedia]
""",
)
ns_parser = self.parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED, limit=20
)
if ns_parser:
commodity_view.display_debt(export=ns_parser.export, limit=ns_parser.limit)

@log_start_end(log=logger)
colin99d marked this conversation as resolved.
Show resolved Hide resolved
def call_spectrum(self, other_args: List[str]):
"""Process spectrum command"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
bigmac The Economist Big Mac index [NASDAQ Datalink]
ycrv show sovereign yield curves [Investing.com / FRED]
events display economic calendar [Investing.com]
cdebt shows debt statistics for various countries [USDebtClock.org]

rtps real-time performance sectors [Alpha Vantage]
valuation valuation of sectors, industry, country [Finviz]
Expand Down
65 changes: 65 additions & 0 deletions website/content/terminal/economy/cdebt/_index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
```
usage: cdebt [-h] [--export EXPORT] [-l LIMIT]
```
National debt statistics for various countries. [Source: Wikipedia]

```
optional arguments:
-h, --help show this help message (default: False)
--export EXPORT Export raw data into csv, json, xlsx (default: )
-l LIMIT, --limit LIMIT
Number of entries to show in data. (default: 20)

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

Sample usage:

```
2022 Aug 12, 16:51 (🦋) /economy/ $ cdebt

National Debt (USD)
┏━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
┃ ┃ Country ┃ Debt ┃ Per Capita ┃
┡━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━┩
│ 1 │ United States │ 30,400,000,000,000.0 │ 60,526.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 2 │ China │ 13,000,000,000,000.0 │ 8,248.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 3 │ United Kingdom │ 9,020,000,000,000.0 │ 127,000.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 4 │ France │ 7,320,000,000,000.0 │ 87,200.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 5 │ Germany │ 5,740,000,000,000.0 │ 69,000.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 6 │ Japan │ 4,770,000,000,000.0 │ 38,000.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 7 │ Italy │ 2,510,000,000,000.0 │ 42,300.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 8 │ Spain │ 2,260,000,000,000.0 │ 48,700.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 9 │ Canada │ 1,930,000,000,000.0 │ 52,300.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 10 │ Australia │ 1,830,000,000,000.0 │ 71,906.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 11 │ Switzerland │ 1,820,000,000,000.0 │ 213,100.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 12 │ Singapore │ 1,670,000,000,000.0 │ 231,000.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 13 │ Belgium │ 1,280,000,000,000.0 │ 112,000.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 14 │ Sweden │ 994,000,000,000.0 │ 94,500.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 15 │ Austria │ 757,000,000,000.0 │ 84,061.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 16 │ Norway │ 604,000,000,000.0 │ 117,000.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 17 │ India │ 614,900,000,000.0 │ 6,390.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 18 │ Brazil │ 556,000,000,000.0 │ 3,200.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 19 │ Netherlands │ 555,000,000,000.0 │ 26,540.0 │
├────┼────────────────┼──────────────────────┼────────────┤
│ 20 │ Russia │ 489,000,000,000.0 │ 3,700.0 │
└────┴────────────────┴──────────────────────┴────────────┘
```
2 changes: 2 additions & 0 deletions website/data/menu/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -983,6 +983,8 @@ main:
ref: "/terminal/economy/macro"
- name: fred
ref: "/terminal/economy/fred"
- name: cdebt
ref: "/terminal/economy/cdebt"
- name: index
ref: "/terminal/economy/index"
- name: treasury
Expand Down