mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-11-27 11:41:32 +00:00
Adding the historical endpoint from sentiment investor (#1175)
* Adding the historical endpoint from sentiment investor * Add option to export raw data * Remove all Sentiment Investor command from auto completion * Fix linting * Fix mispellings * Fixed flake8 * Fixed flake8 * Fix linting * Fix linting * Add typing dict for payload * Forgot to add black formatting * Change import orders * Add tests for call_hist * Add black formatting * Disable pylint * Fix type error bugs & implement required for start and end arguments * fix black linting * fix black linting * Remove unused import Co-authored-by: Minh Hoang <minh@Minhs-MBP.Home>
This commit is contained in:
@@ -1,306 +1,57 @@
|
||||
"""SentimentInvestor Model"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import dataclasses
|
||||
import datetime
|
||||
import logging
|
||||
import multiprocessing
|
||||
import os
|
||||
import statistics
|
||||
import time
|
||||
from typing import Any, List, Optional, Tuple, Union
|
||||
|
||||
from typing import Union, Dict
|
||||
import requests
|
||||
import pandas as pd
|
||||
from colorama import Fore, Style
|
||||
from sentipy.sentipy import Sentipy
|
||||
|
||||
from gamestonk_terminal import config_terminal as cfg
|
||||
|
||||
sentipy: Sentipy = Sentipy(
|
||||
token=cfg.API_SENTIMENTINVESTOR_TOKEN, key=cfg.API_SENTIMENTINVESTOR_KEY
|
||||
)
|
||||
|
||||
# TODO: Make code more consistent with rest of repository.
|
||||
def get_historical(ticker: str, start: str, end: str, number: int) -> pd.DataFrame:
|
||||
"""Get hour-level sentiment data for the chosen ticker
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class _Boundary:
|
||||
"""Represents a strong or weak bounding inequality for categorising a value"""
|
||||
|
||||
min: Union[float, int]
|
||||
"Minimum value that this metric could take"
|
||||
max: Union[float, int]
|
||||
"Maximum value that this metric could take"
|
||||
strong: bool = False
|
||||
"Whether this a strongly bounded inequality"
|
||||
|
||||
def categorise(self, num: Union[float, int]) -> Tuple[str, str]:
|
||||
"""
|
||||
Categorise a given number using this bounding inequality
|
||||
|
||||
Parameters
|
||||
----------
|
||||
num: the number to bucket
|
||||
|
||||
Returns
|
||||
-------
|
||||
A color string and a string with low / medium / high as appropriate
|
||||
|
||||
"""
|
||||
|
||||
if num is None or self.min is None or self.max is None:
|
||||
return Style.DIM + Fore.WHITE, "N/A"
|
||||
|
||||
boundaries = [self.min + (self.max - self.min) / 5 * i for i in range(1, 5)]
|
||||
|
||||
if (num <= self.min or num >= self.max) and self.strong:
|
||||
return Fore.WHITE, "Extreme (anomaly?)"
|
||||
if num < boundaries[0]:
|
||||
return Style.BRIGHT + Fore.RED, "Much Lower"
|
||||
if num < boundaries[1]:
|
||||
return Fore.RED, "Lower"
|
||||
if num < boundaries[2]:
|
||||
return Fore.YELLOW, "Same"
|
||||
if num < boundaries[3]:
|
||||
return Fore.GREEN, "Higher"
|
||||
return Style.BRIGHT + Fore.GREEN, "Much Higher"
|
||||
|
||||
|
||||
def _get_past_week_average(ticker: str, metric: str) -> float:
|
||||
"""Gets last 1 week average"""
|
||||
historical_data = [
|
||||
dp
|
||||
for dp in sentipy.historical(
|
||||
ticker, metric, int(time.time() - 60 * 60 * 24 * 7), int(time.time())
|
||||
).values()
|
||||
if dp is not None
|
||||
]
|
||||
return statistics.mean(historical_data) if historical_data else None
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class _MetricInfo:
|
||||
name: str
|
||||
"""Metric attribute name"""
|
||||
title: str
|
||||
"""Human-friendly attribute name"""
|
||||
description: str
|
||||
"""Metric attribute description"""
|
||||
format: str
|
||||
"""Format string for presenting the value"""
|
||||
|
||||
|
||||
class _Metric(_MetricInfo):
|
||||
boundary: _Boundary
|
||||
"""A contextual range to for this metric"""
|
||||
ticker: str
|
||||
"""Ticker symbol for which this metric relates"""
|
||||
value: Union[float, int]
|
||||
"""Value"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
metric_info: _MetricInfo,
|
||||
ticker: str,
|
||||
value: Union[float, int],
|
||||
boundary: Optional[_Boundary] = None,
|
||||
):
|
||||
super().__init__(**dataclasses.asdict(metric_info))
|
||||
|
||||
weekly_mean = _get_past_week_average(ticker, self.name)
|
||||
self.boundary = (
|
||||
_Boundary(0, None if weekly_mean is None else 2 * weekly_mean)
|
||||
if boundary is None
|
||||
else boundary
|
||||
)
|
||||
self.ticker = ticker
|
||||
self.value = value
|
||||
|
||||
def visualise(self) -> Tuple[str, str, str, str]:
|
||||
color, category = self.boundary.categorise(self.value)
|
||||
return (
|
||||
color + self.title,
|
||||
category,
|
||||
"N/A" if self.value is None else f"{self.value:{self.format}}",
|
||||
self.description + Style.RESET_ALL,
|
||||
)
|
||||
|
||||
|
||||
core_metrics = [
|
||||
_MetricInfo(
|
||||
"sentiment",
|
||||
"Sentiment Score",
|
||||
"the percentage of people that are talking positively about a stock",
|
||||
".0%",
|
||||
),
|
||||
_MetricInfo(
|
||||
"AHI",
|
||||
"Average Hype Index",
|
||||
"how much people are talking about a stock on social media",
|
||||
".3f",
|
||||
),
|
||||
_MetricInfo(
|
||||
"RHI",
|
||||
"Relative Hype Index",
|
||||
"whether people are talking about a stock more or less than usual",
|
||||
".3f",
|
||||
),
|
||||
_MetricInfo(
|
||||
"SGP",
|
||||
"Standard General Perception",
|
||||
"whether people are more or less positive about a stock than usual",
|
||||
".3f",
|
||||
),
|
||||
]
|
||||
|
||||
social_metrics = [
|
||||
_MetricInfo(
|
||||
"reddit_comment_mentions",
|
||||
"Reddit Comment Mentions",
|
||||
"the number of mentions this stock has received in Reddit comments",
|
||||
"n",
|
||||
),
|
||||
_MetricInfo(
|
||||
"reddit_comment_sentiment",
|
||||
"Reddit Comment Sentiment",
|
||||
"percentage of Reddit comments mentioning this stock in a positive light",
|
||||
".0%",
|
||||
),
|
||||
_MetricInfo(
|
||||
"reddit_post_mentions",
|
||||
"Reddit Post Mentions",
|
||||
"the number of mentions this stock has received in Reddit posts",
|
||||
"n",
|
||||
),
|
||||
_MetricInfo(
|
||||
"reddit_post_sentiment",
|
||||
"Reddit Post Sentiment",
|
||||
"percentage of Reddit posts mentioning this stock in a positive light",
|
||||
".0%",
|
||||
),
|
||||
_MetricInfo(
|
||||
"tweet_mentions",
|
||||
"Twitter Mentions",
|
||||
"the number of mentions this stock has received on Twitter",
|
||||
"n",
|
||||
),
|
||||
_MetricInfo(
|
||||
"tweet_sentiment",
|
||||
"Twitter Sentiment",
|
||||
"percentage of tweets mentioning this stock in a positive light",
|
||||
".0%",
|
||||
),
|
||||
_MetricInfo(
|
||||
"stocktwits_post_mentions",
|
||||
"Stocktwits Mentions",
|
||||
"the number of mentions this stock has received in Stocktwits posts",
|
||||
"n",
|
||||
),
|
||||
_MetricInfo(
|
||||
"stocktwits_post_sentiment",
|
||||
"Stocktwits Sentiment",
|
||||
"percentage of Stocktwits posts mentioning this stock in a positive light",
|
||||
".0%",
|
||||
),
|
||||
_MetricInfo(
|
||||
"yahoo_finance_comment_mentions",
|
||||
"Yahoo! Finance Comment Mentions",
|
||||
"the number of mentions this stock has received in Yahoo! Finance comments",
|
||||
"n",
|
||||
),
|
||||
_MetricInfo(
|
||||
"yahoo_finance_comment_sentiment",
|
||||
"Yahoo! Finance Comment Sentiment",
|
||||
"percentage of Yahoo! Finance comments mentioning this stock in a positive light",
|
||||
".0%",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _contextualise_metrics(
|
||||
data: object, ticker: str, metric_infos: List[_MetricInfo]
|
||||
) -> Optional[List[_Metric]]:
|
||||
arguments = []
|
||||
for metric_info in metric_infos:
|
||||
if not hasattr(data, metric_info.name):
|
||||
logging.error(
|
||||
"data for %s stock is incomplete. If you believe this is an error, "
|
||||
"please contact hello@sentimentinvestor.com",
|
||||
ticker,
|
||||
)
|
||||
return None
|
||||
arguments.append((metric_info, ticker, data.__getattribute__(metric_info.name)))
|
||||
|
||||
with multiprocessing.Pool(os.cpu_count()) as pool:
|
||||
return pool.starmap(_Metric, arguments)
|
||||
|
||||
|
||||
def get_metrics(ticker: str) -> Optional[List[_Metric]]:
|
||||
"""Get core metrics for ticker"""
|
||||
data = sentipy.parsed(ticker)
|
||||
return _contextualise_metrics(data, ticker, core_metrics)
|
||||
|
||||
|
||||
def get_socials(ticker: str) -> Optional[List[_Metric]]:
|
||||
"""Get social metrics for ticker"""
|
||||
data = sentipy.raw(ticker)
|
||||
return _contextualise_metrics(data, ticker, social_metrics)
|
||||
|
||||
|
||||
def get_historical(ticker: str, metric: str) -> pd.DataFrame:
|
||||
"""Get historical sentiment data [Source: sentimentinvestor]
|
||||
Source: [Sentiment Investor]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Stock
|
||||
metric : str
|
||||
Metric to get
|
||||
ticker: str
|
||||
Ticker to view sentiment data
|
||||
start: str
|
||||
Initial date like string or unix timestamp (e.g. 12-21-2021)
|
||||
end: str
|
||||
End date like string or unix timestamp (e.g. 12-21-2021)
|
||||
number : int
|
||||
Number of results returned by API call
|
||||
Maximum 250 per api call
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
Dataframe of historical sentiment
|
||||
"""
|
||||
data = sentipy.historical(
|
||||
ticker,
|
||||
metric,
|
||||
int(time.time() - 60 * 60 * 24 * 7),
|
||||
int(time.time()),
|
||||
)
|
||||
df = pd.DataFrame.from_dict(
|
||||
{
|
||||
"date": map(datetime.datetime.utcfromtimestamp, data.keys()),
|
||||
metric: data.values(),
|
||||
}
|
||||
|
||||
payload: Dict[str, Union[int, str]] = {
|
||||
"token": cfg.API_SENTIMENTINVESTOR_TOKEN,
|
||||
"symbol": ticker,
|
||||
"start": str(start),
|
||||
"end": str(end),
|
||||
"limit": number,
|
||||
}
|
||||
|
||||
response = requests.get(
|
||||
"https://api.sentimentinvestor.com/v1/historical", params=payload
|
||||
)
|
||||
|
||||
df.sort_index(ascending=True, inplace=True)
|
||||
return df
|
||||
if response.status_code == 200:
|
||||
result = response.json()["results"]
|
||||
|
||||
# check if result is not empty
|
||||
if result:
|
||||
df = pd.DataFrame(response.json()["results"])
|
||||
df = df.set_index("timestamp_date")
|
||||
df.index = pd.to_datetime(df.index)
|
||||
|
||||
def get_top(metric: str, limit: int) -> List[List[Any]]:
|
||||
"""Get top stocks based on metric from sentimentinvestor [Source: sentimentinvestor]
|
||||
return df
|
||||
|
||||
Parameters
|
||||
----------
|
||||
metric : str
|
||||
Metric to get top tickers for
|
||||
limit : int
|
||||
Number of tickes to get
|
||||
|
||||
Returns
|
||||
-------
|
||||
List[List[Any]]
|
||||
List of tickers and scores
|
||||
"""
|
||||
data = sentipy.sort(metric, limit)
|
||||
|
||||
table: List[List[Any]] = []
|
||||
for index, stock in enumerate(data):
|
||||
if not hasattr(stock, "symbol") or not hasattr(stock, metric):
|
||||
logging.warning("data for stock %s is incomplete, ignoring", index + 1)
|
||||
table.append([])
|
||||
else:
|
||||
table.append([index + 1, stock.symbol, stock.__getattribute__(metric)])
|
||||
return table
|
||||
return pd.DataFrame()
|
||||
|
||||
@@ -1,220 +1,105 @@
|
||||
"""SentimentInvestor View"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
from typing import List
|
||||
|
||||
import os
|
||||
import matplotlib.dates as mdates
|
||||
import pandas as pd
|
||||
import seaborn as sns
|
||||
import tabulate
|
||||
from colorama import Style
|
||||
from matplotlib import pyplot as plt
|
||||
from sentipy.sentipy import Sentipy
|
||||
from tabulate import tabulate
|
||||
|
||||
from gamestonk_terminal import config_terminal as cfg
|
||||
from gamestonk_terminal.common.behavioural_analysis import sentimentinvestor_model
|
||||
from gamestonk_terminal.common.behavioural_analysis.sentimentinvestor_model import (
|
||||
_Boundary,
|
||||
_Metric,
|
||||
)
|
||||
from gamestonk_terminal.config_plot import PLOT_DPI
|
||||
from gamestonk_terminal.helper_funcs import plot_autoscale
|
||||
from gamestonk_terminal.helper_funcs import export_data
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
from gamestonk_terminal.rich_config import console
|
||||
|
||||
sentipy: Sentipy = Sentipy(
|
||||
token=cfg.API_SENTIMENTINVESTOR_TOKEN, key=cfg.API_SENTIMENTINVESTOR_KEY
|
||||
)
|
||||
"""Initialise SentiPy with the user's API token and key"""
|
||||
|
||||
pd.plotting.register_matplotlib_converters()
|
||||
|
||||
# TODO: Make code more consisnet with rest of repository
|
||||
|
||||
|
||||
def display_top(metric: str, limit: int):
|
||||
"""Displays top stocks from sentimentinvestor based on metric [Source: sentimentinvestor]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
metric : str
|
||||
Metric to get top for
|
||||
limit : int
|
||||
Number of tickers to get
|
||||
"""
|
||||
table = sentimentinvestor_model.get_top(metric, limit)
|
||||
print(tabulate.tabulate(table, headers=["Rank", "Ticker", metric], floatfmt=".3f"))
|
||||
console.print("")
|
||||
|
||||
|
||||
def _tabulate_metrics(ticker: str, metrics_list: List[_Metric]):
|
||||
"""Tabulates sentiment investor data"""
|
||||
table_data = []
|
||||
table_headers = [
|
||||
f"{Style.BRIGHT}{ticker}{Style.RESET_ALL} Metrics",
|
||||
"vs Past 7 Days",
|
||||
"Value",
|
||||
"Description",
|
||||
]
|
||||
|
||||
for metric in metrics_list:
|
||||
table_data.append(metric.visualise())
|
||||
|
||||
return tabulate.tabulate(table_data, table_headers, tablefmt="grid")
|
||||
|
||||
|
||||
def _customise_plot() -> None:
|
||||
"""Customizes sentimentinvestor plot"""
|
||||
sns.set(
|
||||
font="Arial",
|
||||
style="darkgrid",
|
||||
rc={
|
||||
"axes.axisbelow": False,
|
||||
"axes.edgecolor": "lightgrey",
|
||||
"axes.facecolor": "None",
|
||||
"axes.grid": False,
|
||||
"axes.labelcolor": "dimgrey",
|
||||
"axes.spines.right": False,
|
||||
"axes.spines.top": False,
|
||||
"figure.facecolor": "white",
|
||||
"lines.solid_capstyle": "round",
|
||||
"patch.edgecolor": "w",
|
||||
"patch.force_edgecolor": True,
|
||||
"text.color": "dimgrey",
|
||||
"xtick.bottom": False,
|
||||
"xtick.color": "dimgrey",
|
||||
"xtick.direction": "out",
|
||||
"xtick.top": False,
|
||||
"ytick.color": "dimgrey",
|
||||
"ytick.direction": "out",
|
||||
"ytick.left": False,
|
||||
"ytick.right": False,
|
||||
},
|
||||
)
|
||||
sns.despine(left=True, bottom=True)
|
||||
sns.color_palette("pastel")
|
||||
plt.legend(frameon=False)
|
||||
|
||||
|
||||
def display_metrics(ticker: str) -> None:
|
||||
"""Display sentiment investor metrics for stock ticker"""
|
||||
if not sentipy.supported(ticker):
|
||||
console.print("This stock is not supported by the SentimentInvestor API.")
|
||||
return
|
||||
|
||||
metric_values = sentimentinvestor_model.get_metrics(ticker)
|
||||
|
||||
if not metric_values:
|
||||
console.print("No data available or an error occurred.")
|
||||
return
|
||||
|
||||
console.print(_tabulate_metrics(ticker, metric_values))
|
||||
console.print()
|
||||
|
||||
|
||||
def display_social(ticker: str) -> None:
|
||||
"""Display sentiment investor social metrics for ticker"""
|
||||
if not sentipy.supported(ticker):
|
||||
console.print("This stock is not supported by the SentimentInvestor API.")
|
||||
return
|
||||
|
||||
metric_values = sentimentinvestor_model.get_socials(ticker)
|
||||
|
||||
if not metric_values:
|
||||
console.print("No data available or an error occurred.")
|
||||
return
|
||||
|
||||
console.print(_tabulate_metrics(ticker, metric_values))
|
||||
console.print("")
|
||||
# pylint: disable=E1101
|
||||
|
||||
|
||||
def display_historical(
|
||||
ticker: str, sort_param: str, sort_dir: str, metric: str
|
||||
) -> None:
|
||||
"""Show historical sentiment from sentimentinvestor [Source: sentimentinvestor]
|
||||
ticker: str,
|
||||
start: str,
|
||||
end: str,
|
||||
export: str,
|
||||
number: int = 100,
|
||||
raw: bool = True,
|
||||
limit: int = 10,
|
||||
):
|
||||
"""Display historical sentiment data of a ticker,
|
||||
and plot a chart with RHI and AHI.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Stock ticker
|
||||
sort_param : str
|
||||
Parameter to sort table by
|
||||
sort_dir : str
|
||||
Direction for sorting
|
||||
metric : str
|
||||
Metric to get data for. Either 'sentiment', 'AHI', 'RHI', 'SGP'
|
||||
ticker: str
|
||||
Ticker to view sentiment data
|
||||
start: str
|
||||
Initial date like string or unix timestamp (e.g. 12-21-2021)
|
||||
end: str
|
||||
End date like string or unix timestamp (e.g. 12-21-2021)
|
||||
number : int
|
||||
Number of results returned by API call
|
||||
Maximum 250 per api call
|
||||
raw: boolean
|
||||
Whether to display raw data, by default True
|
||||
limit: int
|
||||
Number of results display on the terminal
|
||||
Default: 10
|
||||
Returns
|
||||
-------
|
||||
"""
|
||||
if not sentipy.supported(ticker):
|
||||
console.print("This stock is not supported by the SentimentInvestor API.")
|
||||
return
|
||||
|
||||
df = sentimentinvestor_model.get_historical(ticker, metric)
|
||||
df = sentimentinvestor_model.get_historical(ticker, start, end, number)
|
||||
|
||||
if df.empty:
|
||||
console.print("The dataset is empty, something must have gone wrong")
|
||||
return
|
||||
print("Error in Sentiment Investor request")
|
||||
else:
|
||||
_, ax1 = plt.subplots(figsize=(25, 7))
|
||||
ax1.plot(df.index, df["RHI"], c="k")
|
||||
ax2 = ax1.twinx()
|
||||
|
||||
_customise_plot()
|
||||
ax1.grid()
|
||||
ax2.plot(df.index, df["AHI"], c="orange")
|
||||
|
||||
# use seaborn to lineplot
|
||||
ax = sns.lineplot(
|
||||
data=df,
|
||||
x="date",
|
||||
y=metric,
|
||||
legend=False,
|
||||
label=[metric],
|
||||
)
|
||||
ax1.set_ylabel("RHI")
|
||||
ax1.set_xlabel("Time")
|
||||
ax1.set_title("Hourly-level data of RHI and AHI")
|
||||
ax1.set_xlim(df.index[0], df.index[-1])
|
||||
ax2.set_ylabel("AHI")
|
||||
|
||||
# always show zero on the y-axis
|
||||
plt.ylim(bottom=0)
|
||||
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M"))
|
||||
plt.gcf().autofmt_xdate()
|
||||
|
||||
# set the x-axis date formatting
|
||||
ax.xaxis.set_major_formatter(mdates.DateFormatter("%x"))
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
# scale the plot appropriately
|
||||
plt.gcf().set_size_inches(plot_autoscale())
|
||||
plt.gcf().set_dpi(PLOT_DPI)
|
||||
plt.gcf().autofmt_xdate()
|
||||
plt.show()
|
||||
|
||||
# fill below the line
|
||||
plt.fill_between(df.date, df[metric], alpha=0.3)
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
|
||||
"hist",
|
||||
df,
|
||||
)
|
||||
|
||||
# add title e.g. AAPL sentiment since 22/07/21
|
||||
plt.title(f"{ticker} {metric} since {min(df.date).strftime('%x')}")
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
plt.show()
|
||||
RAW_COLS = ["twitter", "stocktwits", "yahoo", "likes", "RHI", "AHI"]
|
||||
|
||||
###
|
||||
if raw:
|
||||
df.index = df.index.strftime("%Y-%m-%d %H:%M")
|
||||
df.index.name = "Time"
|
||||
|
||||
boundary = _Boundary(0, max(df[metric].max(), 2 * df[metric].mean()))
|
||||
|
||||
# average for each day
|
||||
aggregated = df.resample("D", on="date").mean()
|
||||
|
||||
# reverse the ordering if requested
|
||||
aggregated.sort_values(
|
||||
metric if sort_param == "value" else sort_param,
|
||||
axis=0,
|
||||
ascending=sort_dir == "asc",
|
||||
inplace=True,
|
||||
)
|
||||
|
||||
# format the date according to user's locale
|
||||
aggregated.index = aggregated.index.strftime("%x")
|
||||
|
||||
# apply coloring to every value
|
||||
aggregated[metric] = [
|
||||
boundary.categorise(value)[0] + str(value) + Style.RESET_ALL
|
||||
for value in aggregated[metric]
|
||||
]
|
||||
|
||||
print(
|
||||
tabulate.tabulate(
|
||||
aggregated,
|
||||
headers=["Day", f"average {metric}"],
|
||||
tablefmt="psql",
|
||||
floatfmt=".3f",
|
||||
),
|
||||
"\n",
|
||||
)
|
||||
if gtff.USE_TABULATE_DF:
|
||||
print(
|
||||
tabulate(
|
||||
df[RAW_COLS].head(limit),
|
||||
headers=[
|
||||
"Time",
|
||||
"Twitter",
|
||||
"Stocktwits",
|
||||
"Yahoo",
|
||||
"Likes",
|
||||
"RHI",
|
||||
"AHI",
|
||||
],
|
||||
tablefmt="fancy_grid",
|
||||
showindex=True,
|
||||
)
|
||||
)
|
||||
else:
|
||||
print(df[RAW_COLS].head(limit).to_string())
|
||||
|
||||
@@ -58,17 +58,3 @@ from gamestonk_terminal.common.behavioural_analysis.finbrain_view import (
|
||||
from gamestonk_terminal.common.behavioural_analysis.finnhub_view import (
|
||||
display_sentiment_stats as stats,
|
||||
)
|
||||
from gamestonk_terminal.common.behavioural_analysis.sentimentinvestor_view import (
|
||||
display_metrics as metrics,
|
||||
)
|
||||
from gamestonk_terminal.common.behavioural_analysis.sentimentinvestor_view import (
|
||||
display_social as social,
|
||||
)
|
||||
from gamestonk_terminal.common.behavioural_analysis.sentimentinvestor_view import (
|
||||
display_historical as historical,
|
||||
)
|
||||
from gamestonk_terminal.common.behavioural_analysis.sentimentinvestor_view import (
|
||||
display_top as popularsi,
|
||||
)
|
||||
|
||||
emerging = popularsi
|
||||
|
||||
@@ -4,12 +4,11 @@ __docformat__ = "numpy"
|
||||
import argparse
|
||||
from typing import List
|
||||
from datetime import datetime, timedelta
|
||||
import textwrap
|
||||
from prompt_toolkit.completion import NestedCompleter
|
||||
from colorama import Style
|
||||
from gamestonk_terminal.rich_config import console
|
||||
|
||||
from gamestonk_terminal.parent_classes import BaseController
|
||||
from gamestonk_terminal.decorators import try_except
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
from gamestonk_terminal.helper_funcs import (
|
||||
EXPORT_BOTH_RAW_DATA_AND_FIGURES,
|
||||
@@ -27,6 +26,7 @@ from gamestonk_terminal.common.behavioural_analysis import (
|
||||
finbrain_view,
|
||||
finnhub_view,
|
||||
twitter_view,
|
||||
sentimentinvestor_view,
|
||||
)
|
||||
from gamestonk_terminal.stocks import stocks_helper
|
||||
|
||||
@@ -55,13 +55,9 @@ class BehaviouralAnalysisController(BaseController):
|
||||
"rise",
|
||||
"headlines",
|
||||
"stats",
|
||||
"metrics",
|
||||
"social",
|
||||
"historical",
|
||||
"emerging",
|
||||
"popular",
|
||||
"popularsi",
|
||||
"getdd",
|
||||
"hist",
|
||||
]
|
||||
|
||||
historical_sort = ["date", "value"]
|
||||
@@ -78,17 +74,6 @@ class BehaviouralAnalysisController(BaseController):
|
||||
|
||||
if session and gtff.USE_PROMPT_TOOLKIT:
|
||||
choices: dict = {c: {} for c in self.controller_choices}
|
||||
choices["historical"]["-s"] = {c: None for c in self.historical_sort}
|
||||
choices["historical"]["--sort"] = {c: None for c in self.historical_sort}
|
||||
choices["historical"]["-d"] = {c: None for c in self.historical_direction}
|
||||
choices["historical"]["--direction"] = {
|
||||
c: None for c in self.historical_direction
|
||||
}
|
||||
choices["historical"]["-m"] = {c: None for c in self.historical_metric}
|
||||
choices["historical"]["--metric"] = {
|
||||
c: None for c in self.historical_metric
|
||||
}
|
||||
choices["historical"] = {c: None for c in self.historical_metric}
|
||||
self.completer = NestedCompleter.from_nested_dict(choices)
|
||||
|
||||
def print_help(self):
|
||||
@@ -124,14 +109,12 @@ class BehaviouralAnalysisController(BaseController):
|
||||
queries top related queries with this stock
|
||||
rise top rising related queries with stock{has_ticker_end}
|
||||
[src][SentimentInvestor][/src]
|
||||
popularsi show most popular stocks on social media right now
|
||||
emerging show stocks that are being talked about more than usual{has_ticker_start}
|
||||
metrics core social sentiment metrics for this stock
|
||||
social social media figures for stock popularity
|
||||
historical plot the past week of data for a selected metric{has_ticker_end}[/cmds]
|
||||
hist plot historical RHI and AHI data by hour{has_ticker_end}[/cmds]
|
||||
|
||||
"""
|
||||
console.print(text=help_text, menu="Stocks - Behavioural Analysis")
|
||||
|
||||
@try_except
|
||||
def call_load(self, other_args: List[str]):
|
||||
"""Process load command"""
|
||||
parser = argparse.ArgumentParser(
|
||||
@@ -728,246 +711,59 @@ class BehaviouralAnalysisController(BaseController):
|
||||
else:
|
||||
console.print("No ticker loaded. Please load using 'load <ticker>'\n")
|
||||
|
||||
def call_metrics(self, other_args: List[str]):
|
||||
"""Process metrics command"""
|
||||
command_description = f"""
|
||||
{Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to
|
||||
generate hourly metrics on over 2,000 stocks. Sentiment provides volume and
|
||||
sentiment metrics powered by proprietary NLP models.
|
||||
|
||||
The {Style.BRIGHT}metrics{Style.RESET_ALL} command prints the following realtime metrics:
|
||||
|
||||
{Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL}
|
||||
---
|
||||
AHI is a measure of how much people are talking about a stock on social media.
|
||||
It is calculated by dividing the total number of mentions for the chosen stock
|
||||
on a social network by the mean number of mentions any stock receives on that
|
||||
social medium.
|
||||
|
||||
{Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL}
|
||||
---
|
||||
RHI is a measure of whether people are talking about a stock more or less than
|
||||
usual, calculated by dividing the mean AHI for the past day by the mean AHI for
|
||||
for the past week for that stock.
|
||||
|
||||
{Style.BRIGHT}Sentiment Score{Style.RESET_ALL}
|
||||
---
|
||||
Sentiment score is the percentage of people talking positively about the stock.
|
||||
For each social network the number of positive posts/comments is divided by the
|
||||
total number of both positive and negative posts/comments.
|
||||
|
||||
{Style.BRIGHT}SGP (Standard General Perception){Style.RESET_ALL}
|
||||
---
|
||||
SGP is a measure of whether people are more or less positive about a stock than
|
||||
usual. It is calculated by averaging the past day of sentiment values and then
|
||||
dividing it by the average of the past week of sentiment values.
|
||||
"""
|
||||
def call_hist(self, other_args: List[str]):
|
||||
"""Process hist command"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="metrics",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description=textwrap.dedent(command_description),
|
||||
)
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if ns_parser:
|
||||
if self.ticker:
|
||||
console.print(
|
||||
"Currently under maintenance by the new Sentiment Investor team.\n"
|
||||
)
|
||||
# sentimentinvestor_view.display_metrics(ticker=self.ticker)
|
||||
else:
|
||||
console.print("No ticker loaded. Please load using 'load <ticker>'\n")
|
||||
|
||||
def call_social(self, other_args: List[str]):
|
||||
"""Process social command"""
|
||||
command_description = f"""
|
||||
{Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to
|
||||
generate hourly metrics on over 2,000 stocks. Sentiment provides volume and
|
||||
sentiment metrics powered by proprietary NLP models.
|
||||
|
||||
The {Style.BRIGHT}social{Style.RESET_ALL} command prints the raw data for a given stock, including the number
|
||||
of mentions it has received on social media in the last hour and the sentiment
|
||||
score of those comments.
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="social",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description=textwrap.dedent(command_description),
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="hist",
|
||||
description="Plot historical sentiment data of RHI and AHI by hour",
|
||||
)
|
||||
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if ns_parser:
|
||||
if self.ticker:
|
||||
console.print(
|
||||
"Currently under maintenance by the new Sentiment Investor team.\n"
|
||||
)
|
||||
# sentimentinvestor_view.display_social(ticker=self.ticker)
|
||||
else:
|
||||
console.print("No ticker loaded. Please load using 'load <ticker>'\n")
|
||||
|
||||
def call_historical(self, other_args: List[str]):
|
||||
"""Process historical command"""
|
||||
command_description = f"""
|
||||
{Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to
|
||||
generate hourly metrics on over 2,000 stocks. Sentiment provides volume and
|
||||
sentiment metrics powered by proprietary NLP models.
|
||||
|
||||
The {Style.BRIGHT}historical{Style.RESET_ALL} command plots the past week of data for a selected metric, one of:
|
||||
|
||||
{Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL}
|
||||
---
|
||||
AHI is a measure of how much people are talking about a stock on social media.
|
||||
It is calculated by dividing the total number of mentions for the chosen stock
|
||||
on a social network by the mean number of mentions any stock receives on that
|
||||
social medium.
|
||||
|
||||
{Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL}
|
||||
---
|
||||
RHI is a measure of whether people are talking about a stock more or less than
|
||||
usual, calculated by dividing the mean AHI for the past day by the mean AHI for
|
||||
for the past week for that stock.
|
||||
|
||||
{Style.BRIGHT}Sentiment Score{Style.RESET_ALL}
|
||||
---
|
||||
Sentiment score is the percentage of people talking positively about the stock.
|
||||
For each social network the number of positive posts/comments is divided by the
|
||||
total number of both positive and negative posts/comments.
|
||||
|
||||
{Style.BRIGHT}SGP (Standard General Perception){Style.RESET_ALL}
|
||||
---
|
||||
SGP is a measure of whether people are more or less positive about a stock than
|
||||
usual. It is calculated by averaging the past day of sentiment values and then
|
||||
dividing it by the average of the past week of sentiment values.
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="historical",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description=textwrap.dedent(command_description),
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s",
|
||||
"--sort",
|
||||
action="store",
|
||||
type=str,
|
||||
default="date",
|
||||
help="the parameter to sort output table by",
|
||||
dest="sort_param",
|
||||
choices=self.historical_sort,
|
||||
"--start",
|
||||
type=valid_date,
|
||||
default=(datetime.utcnow() - timedelta(days=7)).strftime("%Y-%m-%d"),
|
||||
dest="start",
|
||||
required="--end" in other_args,
|
||||
help="The starting date (format YYYY-MM-DD) of the stock. Default: 7 days ago",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-d",
|
||||
"--direction",
|
||||
action="store",
|
||||
type=str,
|
||||
default="desc",
|
||||
help="the direction to sort the output table",
|
||||
dest="sort_dir",
|
||||
choices=self.historical_direction,
|
||||
"-e",
|
||||
"--end",
|
||||
type=valid_date,
|
||||
default=datetime.utcnow().strftime("%Y-%m-%d"),
|
||||
dest="end",
|
||||
required="--start" in other_args,
|
||||
help="The ending date (format YYYY-MM-DD) of the stock. Default: today",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-m",
|
||||
"--metric",
|
||||
type=str,
|
||||
action="store",
|
||||
default="sentiment",
|
||||
dest="metric",
|
||||
choices=self.historical_metric,
|
||||
help="the metric to plot",
|
||||
"-n",
|
||||
"--number",
|
||||
default=100,
|
||||
type=check_positive,
|
||||
dest="number",
|
||||
help="Number of results returned from Sentiment Investor. Default: 100",
|
||||
)
|
||||
if other_args and "-" not in other_args[0][0]:
|
||||
other_args.insert(0, "-m")
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
|
||||
ns_parser = parse_known_args_and_warn(
|
||||
parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES, raw=True, limit=10
|
||||
)
|
||||
|
||||
if ns_parser:
|
||||
if self.ticker:
|
||||
console.print(
|
||||
"Currently under maintenance by the new Sentiment Investor team.\n"
|
||||
sentimentinvestor_view.display_historical(
|
||||
ticker=self.ticker,
|
||||
start=ns_parser.start,
|
||||
end=ns_parser.end,
|
||||
number=ns_parser.number,
|
||||
export=ns_parser.export,
|
||||
raw=ns_parser.raw,
|
||||
limit=ns_parser.limit,
|
||||
)
|
||||
# sentimentinvestor_view.display_historical(
|
||||
# ticker=self.ticker,
|
||||
# sort_param=ns_parser.sort_param,
|
||||
# metric=ns_parser.metric,
|
||||
# sort_dir=ns_parser.sort_dir,
|
||||
# )
|
||||
|
||||
else:
|
||||
console.print("No ticker loaded. Please load using 'load <ticker>'\n")
|
||||
|
||||
def call_popularsi(self, other_args: List[str]):
|
||||
"""Process popular command"""
|
||||
command_description = f"""
|
||||
The {Style.BRIGHT}popular{Style.RESET_ALL} command prints the stocks with highest Average Hype Index right now.
|
||||
|
||||
{Style.BRIGHT}AHI (Absolute Hype Index){Style.RESET_ALL}
|
||||
---
|
||||
AHI is a measure of how much people are talking about a stock on social media.
|
||||
It is calculated by dividing the total number of mentions for the chosen stock
|
||||
on a social network by the mean number of mentions any stock receives on that
|
||||
social medium.
|
||||
|
||||
===
|
||||
|
||||
{Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to
|
||||
generate hourly metrics on over 2,000 stocks. Sentiment provides volume and
|
||||
sentiment metrics powered by proprietary NLP models.
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="popularsi",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description=textwrap.dedent(command_description),
|
||||
)
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--limit",
|
||||
action="store",
|
||||
dest="limit",
|
||||
type=int,
|
||||
default=10,
|
||||
help="the maximum number of stocks to retrieve",
|
||||
)
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if ns_parser:
|
||||
console.print(
|
||||
"Currently under maintenance by the new Sentiment Investor team.\n"
|
||||
)
|
||||
# sentimentinvestor_view.display_top(metric="AHI", limit=ns_parser.limit)
|
||||
|
||||
def call_emerging(self, other_args: List[str]):
|
||||
"""Process emerging command"""
|
||||
command_description = f"""
|
||||
The {Style.BRIGHT}emerging{Style.RESET_ALL} command prints the stocks with highest Index right now.
|
||||
|
||||
{Style.BRIGHT}RHI (Relative Hype Index){Style.RESET_ALL}
|
||||
---
|
||||
RHI is a measure of whether people are talking about a stock more or less than
|
||||
usual, calculated by dividing the mean AHI for the past day by the mean AHI for
|
||||
for the past week for that stock.
|
||||
|
||||
===
|
||||
|
||||
{Style.BRIGHT}Sentiment Investor{Style.RESET_ALL} analyzes data from four major social media platforms to
|
||||
generate hourly metrics on over 2,000 stocks. Sentiment provides volume and
|
||||
sentiment metrics powered by proprietary NLP models.
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="popular",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description=textwrap.dedent(command_description),
|
||||
)
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--limit",
|
||||
action="store",
|
||||
dest="limit",
|
||||
type=int,
|
||||
default=10,
|
||||
help="the maximum number of stocks to retrieve",
|
||||
)
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if ns_parser:
|
||||
console.print(
|
||||
"Currently under maintenance by the new Sentiment Investor team.\n"
|
||||
)
|
||||
# sentimentinvestor_view.display_top(metric="RHI", limit=ns_parser.limit)
|
||||
print("No ticker loaded. Please load using 'load <ticker>'\n")
|
||||
|
||||
@@ -399,32 +399,26 @@ def test_call_func_expect_queue(expected_queue, queue, func):
|
||||
),
|
||||
),
|
||||
(
|
||||
"call_metrics",
|
||||
"call_hist",
|
||||
[
|
||||
"--start=2020-12-01",
|
||||
"--end=2020-12-07",
|
||||
"--export=csv",
|
||||
"--number=100",
|
||||
"--raw",
|
||||
"--limit=10",
|
||||
],
|
||||
"sentimentinvestor_view.display_historical",
|
||||
[],
|
||||
"",
|
||||
[],
|
||||
dict(),
|
||||
),
|
||||
(
|
||||
"call_social",
|
||||
[],
|
||||
"",
|
||||
[],
|
||||
dict(),
|
||||
),
|
||||
(
|
||||
"call_historical",
|
||||
["--sort=date", "--direction=desc", "--metric=sentiment"],
|
||||
"",
|
||||
[],
|
||||
dict(),
|
||||
),
|
||||
(
|
||||
"call_emerging",
|
||||
["--limit=2"],
|
||||
"",
|
||||
[],
|
||||
dict(),
|
||||
dict(
|
||||
ticker="MOCK_TICKER",
|
||||
start=datetime(2020, 12, 1),
|
||||
end=datetime(2020, 12, 7),
|
||||
number=100,
|
||||
export="csv",
|
||||
raw=True,
|
||||
limit=10,
|
||||
),
|
||||
),
|
||||
(
|
||||
"call_popular",
|
||||
@@ -437,13 +431,6 @@ def test_call_func_expect_queue(expected_queue, queue, func):
|
||||
subreddits="MOCK_SUB",
|
||||
),
|
||||
),
|
||||
(
|
||||
"call_popularsi",
|
||||
["--limit=2"],
|
||||
"",
|
||||
[],
|
||||
dict(),
|
||||
),
|
||||
(
|
||||
"call_getdd",
|
||||
["--limit=1", "--days=2", "--all"],
|
||||
@@ -512,12 +499,8 @@ def test_call_func(
|
||||
"call_rise",
|
||||
"call_headlines",
|
||||
"call_stats",
|
||||
"call_metrics",
|
||||
"call_social",
|
||||
"call_historical",
|
||||
"call_emerging",
|
||||
"call_hist",
|
||||
"call_popular",
|
||||
"call_popularsi",
|
||||
"call_getdd",
|
||||
],
|
||||
)
|
||||
@@ -541,9 +524,7 @@ def test_call_func_no_parser(func, mocker):
|
||||
@pytest.mark.parametrize(
|
||||
"func",
|
||||
[
|
||||
"call_historical",
|
||||
"call_social",
|
||||
"call_metrics",
|
||||
"call_hist",
|
||||
"call_stats",
|
||||
"call_headlines",
|
||||
"call_sentiment",
|
||||
|
||||
@@ -28,9 +28,4 @@ Ticker: TSLA
|
||||
queries top related queries with this stock
|
||||
rise top rising related queries with stock
|
||||
[SentimentInvestor]
|
||||
popularsi show most popular stocks on social media right now
|
||||
emerging show stocks that are being talked about more than usual
|
||||
metrics core social sentiment metrics for this stock
|
||||
social social media figures for stock popularity
|
||||
historical plot the past week of data for a selected metric
|
||||
|
||||
hist plot historical RHI and AHI data by hour
|
||||
|
||||
Reference in New Issue
Block a user