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

Economic calendar #2936

Merged
merged 7 commits into from
Oct 21, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ repos:
args:
[
"--ignore-files=settings_controller.py,featflags_controller.py,keys_controller.py,degiro_controller.py,",
"--ignore-commands=login,alswe,info_swe,goodness,resources,yf,yolo,from,to,featflags,guess,settings,survey,intro",
"--ignore-commands=login,alswe,info_swe,goodness,resources,yf,yolo,from,to,featflags,guess,settings,survey,intro"
]
entry: python custom_pre_commit/check_doc.py
- repo: https://github.com/pre-commit/pre-commit-hooks
Expand All @@ -32,7 +32,7 @@ repos:
- id: flake8
entry: flake8 --ignore=E203,W503 --max-line-length=122 --exclude ./build/pyinstaller/*
- repo: https://github.com/codespell-project/codespell
rev: v2.2.1
rev: v2.2.2
hooks:
- id: codespell
entry: codespell
Expand Down Expand Up @@ -68,7 +68,7 @@ repos:
["--baseline", ".secrets.baseline", "--exclude-files", "cassettes/*", "--exclude-files", "website/content/api/*"]
exclude: package.lock.json
- repo: https://github.com/asottile/pyupgrade
rev: v3.0.0
rev: v3.1.0
hooks:
- id: pyupgrade
args: [--py38-plus]
Expand Down
95 changes: 63 additions & 32 deletions openbb_terminal/economy/economy_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import logging
import os
import itertools
from datetime import date
from datetime import date, datetime as dt
from typing import List, Dict, Any

import pandas as pd
Expand Down Expand Up @@ -69,7 +69,7 @@ class EconomyController(BaseController):
"rtps",
"bigmac",
"ycrv",
"spread",
# "spread",
"events",
"edebt",
]
Expand Down Expand Up @@ -388,7 +388,8 @@ def print_help(self):
mt.add_cmd("map")
mt.add_cmd("bigmac")
mt.add_cmd("ycrv")
mt.add_cmd("spread")
# Comment out spread while investpy is donw :()
# mt.add_cmd("spread")
mt.add_cmd("events")
mt.add_cmd("edebt")
mt.add_raw("\n")
Expand Down Expand Up @@ -1269,42 +1270,50 @@ def call_events(self, other_args: List[str]):
"--country",
action="store",
dest="country",
nargs="+",
default="all",
type=str,
default="",
help="Display calendar for specific country.",
)
parser.add_argument(
"-i",
"--importance",
action="store",
dest="importance",
choices=investingcom_model.IMPORTANCES,
help="Event importance classified as high, medium, low or all.",
)
parser.add_argument(
"--categories",
action="store",
dest="category",
choices=investingcom_model.CATEGORIES,
default=None,
help="Event category.",
)
parser.add_argument(
"-s",
"--start",
dest="start_date",
type=valid_date,
help="The start date of the data (format: YEAR-MONTH-DAY, i.e. 2010-12-31)",
default=None,
default=dt.now().strftime("%Y-%m-%d"),
)
parser.add_argument(
"-e",
"--end",
dest="end_date",
type=valid_date,
help="The start date of the data (format: YEAR-MONTH-DAY, i.e. 2010-12-31)",
default=dt.now().strftime("%Y-%m-%d"),
)
parser.add_argument(
"-d",
"--date",
dest="spec_date",
type=valid_date,
help="Get a specific date for events. Overrides start and end dates.",
default=None,
)
parser.add_argument(
"-i",
"--importance",
action="store",
dest="importance",
choices=investingcom_model.IMPORTANCES,
help="Event importance classified as high, medium, low or all.",
)
parser.add_argument(
"--categories",
action="store",
dest="category",
choices=investingcom_model.CATEGORIES,
default=None,
help="[INVESTING source only] Event category.",
)
ns_parser = self.parse_known_args_and_warn(
parser,
other_args,
Expand All @@ -1315,7 +1324,8 @@ def call_events(self, other_args: List[str]):

if ns_parser:
if isinstance(ns_parser.country, list):
ns_parser.country = " ".join(ns_parser.country)
if ns_parser.source == "Investing":
ns_parser.country = " ".join(ns_parser.country)

if ns_parser.start_date:
start_date = ns_parser.start_date.strftime("%Y-%m-%d")
Expand All @@ -1327,15 +1337,36 @@ def call_events(self, other_args: List[str]):
else:
end_date = None

investingcom_view.display_economic_calendar(
country=ns_parser.country,
importance=ns_parser.importance,
category=ns_parser.category,
start_date=start_date,
end_date=end_date,
limit=ns_parser.limit,
export=ns_parser.export,
)
if ns_parser.source == "Investing":
investingcom_view.display_economic_calendar(
country=ns_parser.country,
importance=ns_parser.importance,
category=ns_parser.category,
start_date=start_date,
end_date=end_date,
limit=ns_parser.limit,
export=ns_parser.export,
)
elif ns_parser.source == "Nasdaq":
countries = (
ns_parser.country.replace("_", " ").title().split(",")
if ns_parser.country
else []
)

if ns_parser.spec_date:
start_date = ns_parser.spec_date.strftime("%Y-%m-%d")
end_date = ns_parser.spec_date.strftime("%Y-%m-%d")

else:
start_date, end_date = sorted([start_date, end_date])
nasdaq_view.display_economic_calendar(
country=countries,
start_date=start_date,
end_date=end_date,
limit=ns_parser.limit,
export=ns_parser.export,
)

@log_start_end(log=logger)
def call_plot(self, other_args: List[str]):
Expand Down
69 changes: 68 additions & 1 deletion openbb_terminal/economy/nasdaq_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
import argparse
import logging
import os
from typing import List
from typing import List, Union

from datetime import datetime as dt
import pandas as pd
import requests

Expand All @@ -16,6 +17,72 @@
logger = logging.getLogger(__name__)


@log_start_end(log=logger)
def get_economic_calendar(
countries: Union[List[str], str] = "",
start_date: str = dt.now().strftime("%Y-%m-%d"),
end_date: str = dt.now().strftime("%Y-%m-%d"),
) -> pd.DataFrame:
"""Get economic calendar for countries between specified dates

Parameters
----------
countries : [List[str],str]
List of countries to include in calendar. Empty returns all
start_date : str
Start date for calendar
end_date : str
End date for calendar

Returns
-------
pd.DataFrame
Economic calendar
"""
if isinstance(countries, str):
countries = [countries]
if start_date == end_date:
dates = [start_date]
else:
dates = (
pd.date_range(start=start_date, end=end_date).strftime("%Y-%m-%d").tolist()
)
calendar = pd.DataFrame()
for date in dates:
try:
df = pd.DataFrame(
requests.get(
f"https://api.nasdaq.com/api/calendar/economicevents?date={date}",
headers={
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"
},
).json()["data"]["rows"]
).replace(" ", "-")
df.loc[:, "Date"] = date
calendar = pd.concat([calendar, df], axis=0)
except TypeError:
continue

if calendar.empty:
console.print("[red]No data found for date range.[/red]")
return pd.DataFrame()

calendar = calendar.rename(
columns={"gmt": "Time (GMT)", "country": "Country", "eventName": "Event"}
)

calendar = calendar.drop(columns=["description"])
if not countries:
return calendar

calendar = calendar[calendar["Country"].isin(countries)].reset_index(drop=True)
if calendar.empty:
console.print(f"[red]No data found for {','.join(countries)}[/red]")
return pd.DataFrame()
return calendar


@log_start_end(log=logger)
def check_country_code_type(list_of_codes: str) -> List[str]:
"""Check that codes are valid for NASDAQ API"""
Expand Down
32 changes: 32 additions & 0 deletions openbb_terminal/economy/nasdaq_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,38 @@
logger = logging.getLogger(__name__)


@log_start_end(log=logger)
def display_economic_calendar(
country: str, start_date: str, end_date: str, limit: int = 10, export: str = ""
) -> None:
"""Display economic calendar for specified country between start and end dates

Parameters
----------
country : str
Country to display calendar for
start_date : str
Start date for calendar
end_date : str
End date for calendar
limit : int
Limit number of rows to display
export : str
Export data to csv or excel file
"""
df = nasdaq_model.get_economic_calendar(country, start_date, end_date)
if df.empty:
return
print_rich_table(
df.head(limit),
title="Economic Calendar",
show_index=False,
headers=df.columns,
)
console.print()
export_data(export, os.path.dirname(os.path.abspath(__file__)), "events", df)


@log_start_end(log=logger)
@check_api_key(["API_KEY_QUANDL"])
def display_big_mac_index(
Expand Down
4 changes: 2 additions & 2 deletions openbb_terminal/miscellaneous/data_sources_default.json
Original file line number Diff line number Diff line change
Expand Up @@ -471,8 +471,8 @@
"futures": ["WallStreetJournal", "Finviz"],
"map": ["Finviz"],
"bigmac": ["Nasdaq"],
"ycrv": ["Investing", "FRED"],
"events": ["Investing"],
"ycrv": ["FRED","Investing"],
"events": ["Nasdaq","Investing"],
"edebt": ["Wikipedia"],
"rtps": ["AlphaVantage"],
"valuation": ["Finviz"],
Expand Down
Loading