From 47f5838abaa867752b3bf2c1706fe812ef96803a Mon Sep 17 00:00:00 2001 From: didier Date: Mon, 22 Mar 2021 23:28:47 +0000 Subject: [PATCH 1/7] Change news source from Finviz to News API --- gamestonk_terminal/config_terminal.py | 3 + gamestonk_terminal/due_diligence/README.md | 8 +-- gamestonk_terminal/due_diligence/dd_menu.py | 5 +- gamestonk_terminal/due_diligence/news_api.py | 66 ++++++++++++++++++++ 4 files changed, 76 insertions(+), 6 deletions(-) create mode 100644 gamestonk_terminal/due_diligence/news_api.py diff --git a/gamestonk_terminal/config_terminal.py b/gamestonk_terminal/config_terminal.py index fb7c764ad67..4189a27ce4e 100644 --- a/gamestonk_terminal/config_terminal.py +++ b/gamestonk_terminal/config_terminal.py @@ -29,6 +29,9 @@ API_TWITTER_BEARER_TOKEN = os.getenv("GT_API_TWITTER_BEARER_TOKEN") or "REPLACE_ # https://fred.stlouisfed.org/docs/api/api_key.html API_FRED_KEY = os.getenv("GT_FRED_API_KEY") or "REPLACE_ME" +# https://newsapi.org +API_NEWS_TOKEN = os.getenv("GT_API_NEWS_TOKEN") or "REPLACE_ME" + # Robinhood RH_USERNAME = os.getenv("GT_RH_USERNAME") or "REPLACE_ME" RH_PASSWORD = os.getenv("GT_RH_PASSWORD") or "REPLACE_ME" diff --git a/gamestonk_terminal/due_diligence/README.md b/gamestonk_terminal/due_diligence/README.md index 2d84c90c276..9630a39ca9e 100644 --- a/gamestonk_terminal/due_diligence/README.md +++ b/gamestonk_terminal/due_diligence/README.md @@ -3,7 +3,7 @@ This menu aims to help in due-diligence of a pre-loaded stock, and the usage of the following commands along with an example will be exploited below. * [news](#news) - * latest news of the company [Finviz] + * latest news of the company [News API] * [red](#red) * gets due diligence from another user's post [Reddit] * [analyst](#analyst) @@ -31,9 +31,9 @@ This menu aims to help in due-diligence of a pre-loaded stock, and the usage of news [-n N_NUM] ``` -Prints latest news about company, including title and web link. [Source: Finviz] +Prints latest news about company, including date, title and web link. [Source: News API] -* -n : Number of latest news being printed. Default 5. +* -n : Number of latest news being printed. Default 10. news @@ -54,7 +54,7 @@ Print top stock's due diligence from other users. [Source: Reddit] ## analyst ```text -usage: analyst +usage: analyst ``` Print analyst prices and ratings of the company. The following fields are expected: date, analyst, category, price from, price to, and rating. [Source: Finviz] diff --git a/gamestonk_terminal/due_diligence/dd_menu.py b/gamestonk_terminal/due_diligence/dd_menu.py index ffc27b8193f..94635e6d8c8 100644 --- a/gamestonk_terminal/due_diligence/dd_menu.py +++ b/gamestonk_terminal/due_diligence/dd_menu.py @@ -6,6 +6,7 @@ from gamestonk_terminal.due_diligence import finviz_api as fvz_api from gamestonk_terminal.due_diligence import market_watch_api as mw_api from gamestonk_terminal.due_diligence import quandl_api as q_api from gamestonk_terminal.due_diligence import reddit_api as r_api +from gamestonk_terminal.due_diligence import news_api from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.helper_funcs import get_flair from gamestonk_terminal.menu import session @@ -27,7 +28,7 @@ def print_due_diligence(s_ticker, s_start, s_interval): print(" q quit this menu, and shows back to main menu") print(" quit quit to abandon program") print("") - print(" news latest news of the company [Finviz]") + print(" news latest news of the company [News API]") print(" red gets due diligence from another user's post [Reddit]") print(" analyst analyst prices and ratings of the company [Finviz]") print(" rating rating of the company from strong sell to strong buy [FMP]") @@ -111,7 +112,7 @@ def dd_menu(df_stock, s_ticker, s_start, s_interval): fvz_api.insider(l_args, s_ticker) elif ns_known_args.cmd == "news": - fvz_api.news(l_args, s_ticker) + news_api.news(l_args, s_ticker) elif ns_known_args.cmd == "analyst": fvz_api.analyst(l_args, s_ticker) diff --git a/gamestonk_terminal/due_diligence/news_api.py b/gamestonk_terminal/due_diligence/news_api.py new file mode 100644 index 00000000000..99786231a9b --- /dev/null +++ b/gamestonk_terminal/due_diligence/news_api.py @@ -0,0 +1,66 @@ +import requests +import json +import argparse +from datetime import datetime, timedelta +from gamestonk_terminal import config_terminal as cfg +from gamestonk_terminal.helper_funcs import ( + check_positive, + parse_known_args_and_warn, +) + + +def news(l_args, s_ticker): + parser = argparse.ArgumentParser( + add_help=False, + prog="news", + description=""" + Prints latest news about company, including date, title and web link. [Source: News API] + """, + ) + + parser.add_argument( + "-n", + "--num", + action="store", + dest="n_num", + type=check_positive, + default=10, + help="Number of latest news being printed.", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, l_args) + if not ns_parser: + return + + s_from = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d") + + response = requests.get( + f"https://newsapi.org/v2/everything?q={s_ticker}&from={s_from}" + f"&sortBy=publishedAt&language=en&apiKey={cfg.API_NEWS_TOKEN}", + ) + + # Check that the API response was successful + if response.status_code != 200: + print("Invalid News API token\n") + + else: + print( + f"{response.json()['totalResults']} news articles from {s_ticker} were found since {s_from}\n" + ) + + for idx, article in enumerate(response.json()["articles"]): + print( + article["publishedAt"].replace("T", " ").replace("Z", ""), + " ", + article["title"], + ) + # Unnecessary to use name of the source because contained in link article["source"]["name"] + print(article["url"]) + print("") + + if idx >= ns_parser.n_num - 1: + break + + except Exception as e: + print(e, "\n") \ No newline at end of file From 1b64ba29c9a72a1543c895dcb9e6fbc9727d1755 Mon Sep 17 00:00:00 2001 From: DidierRLopes Date: Mon, 22 Mar 2021 23:31:39 +0000 Subject: [PATCH 2/7] Update README.md --- gamestonk_terminal/due_diligence/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gamestonk_terminal/due_diligence/README.md b/gamestonk_terminal/due_diligence/README.md index 9630a39ca9e..70bfb49340b 100644 --- a/gamestonk_terminal/due_diligence/README.md +++ b/gamestonk_terminal/due_diligence/README.md @@ -35,7 +35,8 @@ Prints latest news about company, including date, title and web link. [Source: N * -n : Number of latest news being printed. Default 10. -news +Captura de ecrã 2021-03-22, às 22 47 42 + ## red From 850bba7c4c774552e379ae2227ba377e23d44498 Mon Sep 17 00:00:00 2001 From: DidierRLopes Date: Mon, 22 Mar 2021 23:34:40 +0000 Subject: [PATCH 3/7] Update news_api.py --- gamestonk_terminal/due_diligence/news_api.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/gamestonk_terminal/due_diligence/news_api.py b/gamestonk_terminal/due_diligence/news_api.py index 99786231a9b..7d61da02925 100644 --- a/gamestonk_terminal/due_diligence/news_api.py +++ b/gamestonk_terminal/due_diligence/news_api.py @@ -1,7 +1,6 @@ -import requests -import json import argparse from datetime import datetime, timedelta +import requests from gamestonk_terminal import config_terminal as cfg from gamestonk_terminal.helper_funcs import ( check_positive, @@ -63,4 +62,4 @@ def news(l_args, s_ticker): break except Exception as e: - print(e, "\n") \ No newline at end of file + print(e, "\n") From 5f62d99f977afabede6dd37d91581ee995a30335 Mon Sep 17 00:00:00 2001 From: DidierRLopes Date: Mon, 22 Mar 2021 23:41:25 +0000 Subject: [PATCH 4/7] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f2615a4a072..577eb352042 100644 --- a/README.md +++ b/README.md @@ -226,10 +226,11 @@ These are the ones where a key is necessary: * Polygon: https://polygon.io * Financial Modeling Prep: https://financialmodelingprep.com/developer * FRED: https://fred.stlouisfed.org/docs/api/api_key.html + * News API: https://newsapi.org When these are obtained, don't forget to update [config_terminal.py](/gamestonk_terminal/config_terminal.py). -Alternatively, you can also set them to the following environment variables: GT_API_KEY_ALPHAVANTAGE, GT_API_KEY_FINANCIALMODELINGPREP, GT_API_KEY_QUANDL, GT_API_REDDIT_CLIENT_ID, GT_API_REDDIT_CLIENT_SECRET, GT_API_REDDIT_USERNAME, GT_API_REDDIT_USER_AGENT, GT_API_REDDIT_PASSWORD, GT_API_TWITTER_KEY, GT_API_TWITTER_SECRET_KEY, GT_API_TWITTER_BEARER_TOKEN, GT_API_POLYGON_KEY, GT_FRED_API_KEY. +Alternatively, you can also set them to the following environment variables: GT_API_KEY_ALPHAVANTAGE, GT_API_KEY_FINANCIALMODELINGPREP, GT_API_KEY_QUANDL, GT_API_REDDIT_CLIENT_ID, GT_API_REDDIT_CLIENT_SECRET, GT_API_REDDIT_USERNAME, GT_API_REDDIT_USER_AGENT, GT_API_REDDIT_PASSWORD, GT_API_TWITTER_KEY, GT_API_TWITTER_SECRET_KEY, GT_API_TWITTER_BEARER_TOKEN, GT_API_POLYGON_KEY, GT_FRED_API_KEY, GT_API_NEWS_TOKEN. Example: ``` From d9a2394ccd5b52dd1ea0c6f4ce064d3a427a682f Mon Sep 17 00:00:00 2001 From: DidierRLopes Date: Mon, 22 Mar 2021 23:43:29 +0000 Subject: [PATCH 5/7] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 577eb352042..95eefd9a008 100644 --- a/README.md +++ b/README.md @@ -333,7 +333,8 @@ Distributed under the MIT License. See [LICENSE](https://github.com/DidierRLopes * [VICE article](https://www.vice.com/en/article/qjp9vp/gamestonk-terminal-is-a-diy-meme-stock-version-of-bloomberg-terminal) * [Daily Fintech article](https://dailyfintech.com/2021/02/25/never-underestimate-bloomberg-but-here-are-5-reasons-why-the-gamestonk-terminal-is-a-contender/) * [HackerNews](https://news.ycombinator.com/item?id=26258773) -* [Reddit](https://www.reddit.com/r/algotrading/comments/lrndzi/cant_afford_the_bloomberg_terminal_no_worries_i/) +* [Reddit r/algotrading](https://www.reddit.com/r/algotrading/comments/m4uvza/gamestonk_terminal_the_next_best_thing_after/) +* [Reddit r/Python](https://www.reddit.com/r/Python/comments/m515yk/gamestonk_terminal_the_equivalent_to_an/) From 97a1efdd16c0fadf38ae1b78eb3fdafc2fa07b2b Mon Sep 17 00:00:00 2001 From: Artem Veremey Date: Mon, 22 Mar 2021 23:36:45 -0700 Subject: [PATCH 6/7] Adding test data parametrization --- conda-environment.yaml | 0 gamestonk_terminal/test_helper.py | 63 ++++++++++++++++++ gamestonk_terminal/thought_of_the_day.py | 2 +- notebooks/templates/due_diligence.ipynb | 0 tests/data/thought_of_the_day.yaml | 55 +++++++++++++++ tests/test_thought_of_the_day.py | 85 ++++++------------------ 6 files changed, 141 insertions(+), 64 deletions(-) mode change 100755 => 100644 conda-environment.yaml create mode 100644 gamestonk_terminal/test_helper.py mode change 100755 => 100644 notebooks/templates/due_diligence.ipynb create mode 100644 tests/data/thought_of_the_day.yaml mode change 100755 => 100644 tests/test_thought_of_the_day.py diff --git a/conda-environment.yaml b/conda-environment.yaml old mode 100755 new mode 100644 diff --git a/gamestonk_terminal/test_helper.py b/gamestonk_terminal/test_helper.py new file mode 100644 index 00000000000..8956dc672d4 --- /dev/null +++ b/gamestonk_terminal/test_helper.py @@ -0,0 +1,63 @@ +""" Test helper """ +__docformat__ = "numpy" + +import pathlib +from typing import Callable +import yaml + + +def parametrize_from_file(test_namespace: str, parameter_file: str) -> Callable: + """A test helper function returns a wrapper function that loads sets of parameters from a YAML and + attaches test scenarios as metadata + + Parameters + ---------- + test_namespace : str + Test namespace to use within the YAML + parameter_file : str + Test scenario YAML to load + + Returns + ------- + Callable + Wrapper function + """ + + def wrapper(function): + test_file_base_path = pathlib.Path(__file__).parent.absolute() + data_file_full_path = pathlib.Path(test_file_base_path, parameter_file) + + with open(data_file_full_path, "r", encoding="utf-8") as file: + parameter_data = yaml.full_load(file) + + idlist = [] + argnames = [] + argvalues = [] + + for scenario in parameter_data[test_namespace]: + idlist.append(scenario) + argnames = [] + tempvalues = [] + for argname in parameter_data[test_namespace][scenario].keys(): + argnames.append(argname) + tempvalues.append(parameter_data[test_namespace][scenario][argname]) + argvalues.append(tempvalues) + + function.test_params_names = argnames + function.test_param_values = argvalues + function.test_ids = idlist + + return function + + return wrapper + + +def pytest_generate_tests(metafunc): + """ https://docs.pytest.org/en/stable/parametrize.html#pytest-generate-tests """ + if getattr(metafunc.function, "test_params_names", None): + metafunc.parametrize( + metafunc.function.test_params_names, + metafunc.function.test_param_values, + ids=metafunc.function.test_ids, + scope="class", + ) diff --git a/gamestonk_terminal/thought_of_the_day.py b/gamestonk_terminal/thought_of_the_day.py index 2278b71461a..8a891254223 100644 --- a/gamestonk_terminal/thought_of_the_day.py +++ b/gamestonk_terminal/thought_of_the_day.py @@ -1,4 +1,4 @@ -""" Fundamental Analysis Market Watch API """ +""" Thought of The Day """ __docformat__ = "numpy" import re diff --git a/notebooks/templates/due_diligence.ipynb b/notebooks/templates/due_diligence.ipynb old mode 100755 new mode 100644 diff --git a/tests/data/thought_of_the_day.yaml b/tests/data/thought_of_the_day.yaml new file mode 100644 index 00000000000..ec396fa26e3 --- /dev/null +++ b/tests/data/thought_of_the_day.yaml @@ -0,0 +1,55 @@ +test_get_urls: + base_case: + urls: + "some author": "https://www.goodreads.com/author/quotes/someauthor" +test_get_metadata: + base_case: + urls: + "some author": "https://www.goodreads.com/author/quotes/someauthor" + mock_goodreads_page: | + + +
+

Epicurus quotes + Showing 1-30 of 171 + +

+
+
+ +
+ “Do not spoil what you have” +
― + + Epicurus + +
+ + +
+
+ tags: + desire, + gratitude, + hope +
+ +
+ +
+
+ Like +
+
+
+
« previous 1 3 4 5 6
+
+ + + expected_result: + "pages": "6" + "quoutes": "171" + "quotes": + - "\n “Do not spoil what you have”\n ―\n \n Epicurus\n \n" diff --git a/tests/test_thought_of_the_day.py b/tests/test_thought_of_the_day.py old mode 100755 new mode 100644 index 4ee3d94f144..4f71a2093e7 --- a/tests/test_thought_of_the_day.py +++ b/tests/test_thought_of_the_day.py @@ -2,79 +2,38 @@ import unittest from unittest import mock +# pylint: disable=unused-import +from gamestonk_terminal.test_helper import ( # noqa: F401 + parametrize_from_file, + pytest_generate_tests, +) from gamestonk_terminal import thought_of_the_day - -mock_goodreads_page = """ # noqa: E501, E101, W191 - - -
-

Epicurus quotes -Showing 1-30 of 171 - -

-
-
- -
- “Do not spoil what you have” -
― - - Epicurus - -
+assertions = unittest.TestCase("__init__") -
-
- tags: - desire, - gratitude, - hope -
- -
- -
-
-Like -
-
-
-
« previous 1 3 4 5 6
-
- - -""" - - -class TestThoughtOfTheDay(unittest.TestCase): - def test_get_urls(self): - urls = {"some author": "https://www.goodreads.com/author/quotes/someauthor"} - +class TestThoughtOfTheDay: + @parametrize_from_file( + "test_get_urls", + "../tests/data/thought_of_the_day.yaml", + ) + def test_get_urls(self, urls): a_totd = thought_of_the_day.ThoughtOfTheDay(urls) - self.assertEqual(a_totd.get_urls(), urls) + assertions.assertEqual(a_totd.get_urls(), urls) @mock.patch("gamestonk_terminal.thought_of_the_day.requests") - def test_get_metadata(self, mock_request_get): - urls = {"some author": "https://www.goodreads.com/author/quotes/someauthor"} - + @parametrize_from_file( + "test_get_metadata", + "../tests/data/thought_of_the_day.yaml", + ) + def test_get_metadata( + self, mock_request_get, urls, mock_goodreads_page, expected_result + ): mock_request_get.get().text = mock_goodreads_page a_totd = thought_of_the_day.ThoughtOfTheDay(urls) - meta = a_totd.get_metadata("some author") + meta = a_totd.get_metadata(list(urls.keys())[0]) - self.assertEqual( - meta, - { - "pages": "6", - "quoutes": "171", - "quotes": [ - "\n “Do not spoil what you have”\n ―\n \n Epicurus\n \n" - ], - }, - ) + assertions.assertEqual(meta, expected_result) From 5cf2cc4d5e523e724179df5247bd01ba725b2525 Mon Sep 17 00:00:00 2001 From: Artem Veremey Date: Mon, 22 Mar 2021 23:38:51 -0700 Subject: [PATCH 7/7] Interesting suggestion by pyupgrade --- gamestonk_terminal/test_helper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gamestonk_terminal/test_helper.py b/gamestonk_terminal/test_helper.py index 8956dc672d4..2800fd93e05 100644 --- a/gamestonk_terminal/test_helper.py +++ b/gamestonk_terminal/test_helper.py @@ -27,7 +27,7 @@ def parametrize_from_file(test_namespace: str, parameter_file: str) -> Callable: test_file_base_path = pathlib.Path(__file__).parent.absolute() data_file_full_path = pathlib.Path(test_file_base_path, parameter_file) - with open(data_file_full_path, "r", encoding="utf-8") as file: + with open(data_file_full_path, encoding="utf-8") as file: parameter_data = yaml.full_load(file) idlist = []