Fix stocks/news (#2442)

* fix stocks/news

* fixtest
This commit is contained in:
DidierRLopes
2022-08-28 04:25:34 +03:00
committed by GitHub
parent 17629fc9ae
commit 817bca657e
5 changed files with 16422 additions and 15997 deletions

2
i18n/en.yml vendored
View File

@@ -99,7 +99,7 @@ en:
stocks/CANDLE_raw: Shows raw data instead of chart. If sort is set those are the top ones, otherwise we grab latest data to date
stocks/CANDLE_trend: Flag to add high and low trends to candle
stocks/CANDLE_mov_avg: Add moving average in number of days to plot and separate by a comma
stocks/NEWS: latest news of the company
stocks/news: latest news of the company
stocks/codes: FIGI, SIK and SIC codes codes
stocks/NEWS_date: The starting date (format YYYY-MM-DD) to search articles from
stocks/NEWS_oldest: Show oldest articles first

View File

@@ -1,6 +1,7 @@
""" News View """
__docformat__ = "numpy"
import os
import logging
from datetime import datetime, timedelta
@@ -9,7 +10,8 @@ import pandas as pd
from openbb_terminal.decorators import check_api_key
from openbb_terminal.common import newsapi_model
from openbb_terminal.decorators import log_start_end
from openbb_terminal.helper_funcs import print_rich_table
from openbb_terminal.helper_funcs import export_data
from openbb_terminal.rich_config import console
logger = logging.getLogger(__name__)
@@ -22,6 +24,7 @@ def display_news(
limit: int = 3,
show_newest: bool = True,
sources: str = "",
export: str = "",
):
"""Display news for a given term. [Source: NewsAPI]
@@ -37,22 +40,33 @@ def display_news(
flag to show newest articles first
sources: str
sources to exclusively show news from
export : str
Export dataframe data to csv,json,xlsx file
"""
articles = newsapi_model.get_news(query, start_date, show_newest, sources)
if articles:
for idx, article in enumerate(articles):
# Unnecessary to use name of the source because contained in link article["source"]["name"]
data = [
[article["publishedAt"].replace("T", " ").replace("Z", "")],
[f"{article['description']}"],
[article["url"]],
]
table = pd.DataFrame(
data, index=["published", "content", "link"], columns=["Content"]
)
print_rich_table(table, title=article["title"])
publishedat = article["publishedAt"].replace("T", " ").replace("Z", "")
title = article["title"]
console.print(f"> {publishedat} - {title}")
console.print(article["url"])
# The description section doesn't exist when this is invoked from UK
if "description" in article:
console.print(article["description"])
console.print()
if idx >= limit - 1:
console.print()
break
export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
f"news_{query}_{'_'.join(sources)}",
pd.DataFrame(articles),
)

View File

@@ -12,7 +12,7 @@ import yfinance as yf
from prompt_toolkit.completion import NestedCompleter
from openbb_terminal import feature_flags as obbff
from openbb_terminal.common import newsapi_view
from openbb_terminal.common import feedparser_view, newsapi_view
from openbb_terminal.common.quantitative_analysis import qa_view
from openbb_terminal.decorators import log_start_end
@@ -110,8 +110,7 @@ class StocksController(StockBaseController):
else:
stock_text = f"{s_intraday} {self.ticker}"
mt = MenuText("stocks/", 80)
mt.add_cmd("news", "Feedparser/News API")
mt = MenuText("stocks/", 100)
mt.add_cmd("search")
mt.add_cmd("load")
mt.add_raw("\n")
@@ -121,6 +120,7 @@ class StocksController(StockBaseController):
mt.add_cmd("quote", "", self.ticker)
mt.add_cmd("candle", "", self.ticker)
mt.add_cmd("codes", "Polygon", self.ticker)
mt.add_cmd("news", "Feedparser / NewsApi", self.ticker)
mt.add_raw("\n")
mt.add_menu("th")
mt.add_menu("options")
@@ -409,13 +409,10 @@ class StocksController(StockBaseController):
@log_start_end(log=logger)
def call_news(self, other_args: List[str]):
"""Process news command"""
if not self.ticker:
console.print("Use 'load <ticker>' prior to this command!", "\n")
return
parser = argparse.ArgumentParser(
add_help=False,
prog="news",
description=translate("stocks/NEWS"),
description=translate("stocks/news"),
)
parser.add_argument(
"-d",
@@ -444,24 +441,44 @@ class StocksController(StockBaseController):
)
if other_args and "-" not in other_args[0][0]:
other_args.insert(0, "-l")
ns_parser = self.parse_known_args_and_warn(parser, other_args, limit=3)
ns_parser = self.parse_known_args_and_warn(
parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED, limit=3
)
if ns_parser:
sources = ns_parser.sources
for idx, source in enumerate(sources):
if source.find(".") == -1:
sources[idx] += ".com"
if not self.ticker:
console.print("Use 'load <ticker>' prior to this command!", "\n")
return
d_stock = yf.Ticker(self.ticker).info
if ns_parser.source == "newsapi":
sources = ns_parser.sources
for idx, source in enumerate(sources):
if source.find(".") == -1:
sources[idx] += ".com"
newsapi_view.display_news(
query=d_stock["shortName"].replace(" ", "+")
if "shortName" in d_stock
else self.ticker,
limit=ns_parser.limit,
start_date=ns_parser.n_start_date.strftime("%Y-%m-%d"),
show_newest=ns_parser.n_oldest,
sources=",".join(sources),
)
d_stock = yf.Ticker(self.ticker).info
newsapi_view.display_news(
query=d_stock["shortName"].replace(" ", "+")
if "shortName" in d_stock
else self.ticker,
limit=ns_parser.limit,
start_date=ns_parser.n_start_date.strftime("%Y-%m-%d"),
show_newest=ns_parser.n_oldest,
sources=",".join(sources),
)
elif ns_parser.source == "feedparser":
d_stock = yf.Ticker(self.ticker).info
feedparser_view.display_news(
term=d_stock["shortName"].replace(" ", "+")
if "shortName" in d_stock
else self.ticker,
sources=" ".join(ns_parser.sources),
limit=ns_parser.limit,
export=ns_parser.export,
)
@log_start_end(log=logger)
def call_disc(self, _):

View File

@@ -1,4 +1,3 @@
news stocks/news [Feedparser/News API]
search search a specific stock ticker for analysis
load load a specific stock ticker and additional info for analysis
@@ -10,7 +9,8 @@ Currency:
[unvl] quote view the current price for a specific stock ticker[/unvl]
[unvl] candle view a candle chart for a specific stock ticker[/unvl]
[unvl] codes FIGI, SIK and SIC codes codes[/unvl] [Polygon]
[unvl] codes FIGI, SIK and SIC codes codes[/unvl] [Polygon]
[unvl] news latest news of the company[/unvl] [Feedparser / NewsApi]
> th trading hours, check open markets
> options options menu, chains, open interest, greeks, parity