mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-11-24 18:22:43 +00:00
Refactor BA Menu (#768)
* Finnhub and finbrain fns * Twitter menu (forex/ba adjusted) * Google menu * Reddit menu pt1 * Reddit commands * Stocktwits commands * Sentimentinvestor commands * Update crypto-dd * Review pt 1 * Hugo server * Review comments - get rid of all prints/errors in model...
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
"""FinBrain Model"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import pandas as pd
|
||||
import requests
|
||||
|
||||
|
||||
def get_sentiment(ticker: str) -> pd.DataFrame:
|
||||
"""Gets Sentiment analysis provided by FinBrain's API [Source: finbrain]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Ticker to get the sentiment analysis from
|
||||
|
||||
Returns
|
||||
-------
|
||||
DataFrame()
|
||||
Empty if there was an issue with data retrieval
|
||||
"""
|
||||
result = requests.get(f"https://api.finbrain.tech/v0/sentiments/{ticker}")
|
||||
sentiment = pd.DataFrame()
|
||||
if result.status_code == 200:
|
||||
if "sentimentAnalysis" in result.json():
|
||||
sentiment = pd.DataFrame.from_dict(
|
||||
result.json()["sentimentAnalysis"], orient="index"
|
||||
)
|
||||
sentiment.index = pd.to_datetime(sentiment.index).to_pydatetime()
|
||||
sentiment.index.name = "date"
|
||||
sentiment.columns = ["Sentiment Analysis"]
|
||||
return sentiment
|
||||
@@ -1,20 +1,16 @@
|
||||
"""FinBrain View Module"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import argparse
|
||||
from typing import List
|
||||
import requests
|
||||
import os
|
||||
from matplotlib import pyplot as plt
|
||||
import matplotlib.dates as mdates
|
||||
import pandas as pd
|
||||
from pandas.plotting import register_matplotlib_converters
|
||||
import numpy as np
|
||||
from colorama import Fore, Style
|
||||
|
||||
from gamestonk_terminal.helper_funcs import (
|
||||
parse_known_args_and_warn,
|
||||
plot_autoscale,
|
||||
)
|
||||
from tabulate import tabulate
|
||||
from gamestonk_terminal.helper_funcs import plot_autoscale, export_data
|
||||
from gamestonk_terminal.common.behavioural_analysis import finbrain_model
|
||||
from gamestonk_terminal.config_plot import PLOT_DPI
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
|
||||
@@ -23,44 +19,10 @@ register_matplotlib_converters()
|
||||
|
||||
|
||||
def sentiment_coloring(val: float, last_val: float) -> str:
|
||||
if float(val) > last_val:
|
||||
color = Fore.GREEN
|
||||
else:
|
||||
color = Fore.RED
|
||||
color = Fore.GREEN if float(val) > last_val else Fore.RED
|
||||
return f"{color}{val}{Style.RESET_ALL}"
|
||||
|
||||
|
||||
def get_sentiment(ticker: str) -> pd.DataFrame:
|
||||
"""Gets Sentiment analysis provided by FinBrain's API
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Ticker to get the sentiment analysis from
|
||||
|
||||
Returns
|
||||
-------
|
||||
DataFrame()
|
||||
Empty if there was an issue with data retrieval
|
||||
"""
|
||||
result = requests.get(f"https://api.finbrain.tech/v0/sentiments/{ticker}")
|
||||
sentiment = pd.DataFrame()
|
||||
if result.status_code == 200:
|
||||
if "sentimentAnalysis" in result.json():
|
||||
sentiment = pd.DataFrame.from_dict(
|
||||
result.json()["sentimentAnalysis"], orient="index"
|
||||
)
|
||||
sentiment.index = pd.to_datetime(sentiment.index).to_pydatetime()
|
||||
sentiment.index.name = "date"
|
||||
sentiment.columns = ["Sentiment Analysis"]
|
||||
else:
|
||||
print("Unexpected data format from FinBrain API")
|
||||
else:
|
||||
print("Request error in retrieving sentiment from FinBrain API")
|
||||
|
||||
return sentiment
|
||||
|
||||
|
||||
def plot_sentiment(sentiment: pd.DataFrame, ticker: str):
|
||||
"""Plot Sentiment analysis provided by FinBrain's API
|
||||
|
||||
@@ -71,27 +33,29 @@ def plot_sentiment(sentiment: pd.DataFrame, ticker: str):
|
||||
ticker : str
|
||||
Ticker to get the sentiment analysis from
|
||||
"""
|
||||
plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
for index, row in sentiment.iterrows():
|
||||
if float(row["Sentiment Analysis"]) >= 0:
|
||||
plt.scatter(index, float(row["Sentiment Analysis"]), s=100, c="green")
|
||||
ax.scatter(index, float(row["Sentiment Analysis"]), s=100, c="green")
|
||||
else:
|
||||
plt.scatter(index, float(row["Sentiment Analysis"]), s=100, c="red")
|
||||
plt.axhline(y=0, color="k", linestyle="--", lw=2)
|
||||
plt.xlabel("Time")
|
||||
plt.ylabel("Sentiment")
|
||||
plt.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
plt.minorticks_on()
|
||||
plt.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
ax.scatter(index, float(row["Sentiment Analysis"]), s=100, c="red")
|
||||
ax.axhline(y=0, color="k", linestyle="--", lw=2)
|
||||
ax.set_xlabel("Time")
|
||||
ax.set_ylabel("Sentiment")
|
||||
ax.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
ax.minorticks_on()
|
||||
ax.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
start_date = sentiment.index[-1].strftime("%Y/%m/%d")
|
||||
plt.title(f"FinBrain's Sentiment Analysis for {ticker.upper()} since {start_date}")
|
||||
ax.set_title(
|
||||
f"FinBrain's Sentiment Analysis for {ticker.upper()} since {start_date}"
|
||||
)
|
||||
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y/%m/%d"))
|
||||
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=1))
|
||||
plt.gcf().autofmt_xdate()
|
||||
plt.ylim([-1.1, 1.1])
|
||||
ax.set_ylim([-1.1, 1.1])
|
||||
senValues = np.array(pd.to_numeric(sentiment["Sentiment Analysis"].values))
|
||||
senNone = np.array(0 * len(sentiment))
|
||||
plt.fill_between(
|
||||
ax.fill_between(
|
||||
sentiment.index,
|
||||
pd.to_numeric(sentiment["Sentiment Analysis"].values),
|
||||
0,
|
||||
@@ -100,7 +64,7 @@ def plot_sentiment(sentiment: pd.DataFrame, ticker: str):
|
||||
color="red",
|
||||
interpolate=True,
|
||||
)
|
||||
plt.fill_between(
|
||||
ax.fill_between(
|
||||
sentiment.index,
|
||||
pd.to_numeric(sentiment["Sentiment Analysis"].values),
|
||||
0,
|
||||
@@ -111,53 +75,57 @@ def plot_sentiment(sentiment: pd.DataFrame, ticker: str):
|
||||
)
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
fig.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
def sentiment_analysis(other_args: List[str], ticker: str):
|
||||
def display_sentiment_analysis(ticker: str, export: str = ""):
|
||||
"""Sentiment analysis from FinBrain
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : List[str]
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker to get the sentiment analysis from
|
||||
export : str
|
||||
Format to export data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="finbrain",
|
||||
description="""FinBrain collects the news headlines from 15+ major financial news
|
||||
sources on a daily basis and analyzes them to generate sentiment scores
|
||||
for more than 4500 US stocks.FinBrain Technologies develops deep learning
|
||||
algorithms for financial analysis and prediction, which currently serves
|
||||
traders from more than 150 countries all around the world.
|
||||
[Source: https://finbrain.tech]""",
|
||||
)
|
||||
df_sentiment = finbrain_model.get_sentiment(ticker)
|
||||
if df_sentiment.empty:
|
||||
print("No sentiment data found.\n")
|
||||
return
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
plot_sentiment(df_sentiment, ticker)
|
||||
|
||||
df_sentiment = get_sentiment(ticker)
|
||||
df_sentiment.sort_index(ascending=True, inplace=True)
|
||||
|
||||
if not df_sentiment.empty:
|
||||
plot_sentiment(df_sentiment, ticker)
|
||||
|
||||
df_sentiment.sort_index(ascending=True, inplace=True)
|
||||
|
||||
if gtff.USE_COLOR:
|
||||
print(
|
||||
df_sentiment["Sentiment Analysis"]
|
||||
.apply(sentiment_coloring, last_val=0)
|
||||
.to_string()
|
||||
if gtff.USE_COLOR:
|
||||
color_df = df_sentiment["Sentiment Analysis"].apply(
|
||||
sentiment_coloring, last_val=0
|
||||
)
|
||||
if gtff.USE_TABULATE_DF:
|
||||
color_df = pd.DataFrame(
|
||||
data=color_df.values,
|
||||
index=pd.to_datetime(df_sentiment.index).strftime("%Y-%m-%d"),
|
||||
)
|
||||
print(tabulate(color_df, headers=["Sentiment"], tablefmt="fancy_grid"))
|
||||
else:
|
||||
print(color_df.to_string())
|
||||
else:
|
||||
if gtff.USE_TABULATE_DF:
|
||||
print(
|
||||
tabulate(
|
||||
pd.DataFrame(
|
||||
data=df_sentiment.values,
|
||||
index=pd.to_datetime(df_sentiment.index).strftime("%Y-%m-%d"),
|
||||
),
|
||||
headers=["Sentiment"],
|
||||
tablefmt="fancy_grid",
|
||||
)
|
||||
)
|
||||
|
||||
else:
|
||||
print(df_sentiment.to_string())
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
print("")
|
||||
print("")
|
||||
export_data(
|
||||
export, os.path.dirname(os.path.abspath(__file__)), "headlines", df_sentiment
|
||||
)
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Finnhub Model"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
from typing import Dict
|
||||
import requests
|
||||
from gamestonk_terminal import config_terminal as cfg
|
||||
|
||||
|
||||
def get_sentiment_stats(ticker: str) -> Dict:
|
||||
"""Get sentiment stats [Source: finnhub]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Ticker to get sentiment stats
|
||||
|
||||
Returns
|
||||
-------
|
||||
Dict
|
||||
Get sentiment stats
|
||||
"""
|
||||
response = requests.get(
|
||||
f"https://finnhub.io/api/v1/news-sentiment?symbol={ticker}&token={cfg.API_FINNHUB_KEY}"
|
||||
)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
|
||||
return {}
|
||||
@@ -1,83 +1,50 @@
|
||||
import argparse
|
||||
from typing import List, Dict
|
||||
import requests
|
||||
from gamestonk_terminal import config_terminal as cfg
|
||||
from gamestonk_terminal.helper_funcs import (
|
||||
parse_known_args_and_warn,
|
||||
)
|
||||
"""Finnhub View"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import os
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from gamestonk_terminal.helper_funcs import export_data
|
||||
from gamestonk_terminal.common.behavioural_analysis import finnhub_model
|
||||
|
||||
|
||||
def get_sentiment_stats(ticker: str) -> Dict:
|
||||
"""Get sentiment stats
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Ticker to get sentiment stats
|
||||
|
||||
Returns
|
||||
-------
|
||||
Dict
|
||||
Get sentiment stats
|
||||
"""
|
||||
response = requests.get(
|
||||
f"https://finnhub.io/api/v1/news-sentiment?symbol={ticker}&token={cfg.API_FINNHUB_KEY}"
|
||||
)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
def sentiment_stats(other_args: List[str], ticker: str):
|
||||
def display_sentiment_stats(ticker: str, export: str = ""):
|
||||
"""
|
||||
Sentiment stats which displays buzz, news score, articles last week, articles weekly average,
|
||||
bullish vs bearish percentages, sector average bullish percentage, and sector average news score
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : List[str]
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker to get sentiment stats
|
||||
export : str
|
||||
Format to export data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="stats",
|
||||
description="""
|
||||
Sentiment stats which displays buzz, news score, articles last week, articles weekly average,
|
||||
bullish vs bearish percentages, sector average bullish percentage, and sector average news score.
|
||||
[Source: https://finnhub.io]
|
||||
""",
|
||||
)
|
||||
d_stats = finnhub_model.get_sentiment_stats(ticker)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
if d_stats:
|
||||
print(
|
||||
f"""
|
||||
Buzz: {round(100*d_stats['buzz']['buzz'],2)} %
|
||||
News Score: {round(100*d_stats['companyNewsScore'],2)} %
|
||||
|
||||
d_stats = get_sentiment_stats(ticker)
|
||||
Articles Last Week: {d_stats['buzz']['articlesInLastWeek']}
|
||||
Articles Weekly Average: {d_stats['buzz']['weeklyAverage']}
|
||||
|
||||
if d_stats:
|
||||
print(f"Buzz: {round(100*d_stats['buzz']['buzz'],2)} %")
|
||||
print(f"News Score: {round(100*d_stats['companyNewsScore'],2)} %")
|
||||
print("")
|
||||
print(f"Articles Last Week: {d_stats['buzz']['articlesInLastWeek']}")
|
||||
print(f"Articles Weekly Average: {d_stats['buzz']['weeklyAverage']}")
|
||||
print("")
|
||||
print(f"Bullish: {round(100*d_stats['sentiment']['bullishPercent'],2)} %")
|
||||
print(f"Bearish: {round(100*d_stats['sentiment']['bearishPercent'],2)} %")
|
||||
print("")
|
||||
print(
|
||||
f"Sector Average Bullish: {round(100*d_stats['sectorAverageBullishPercent'],2)} %"
|
||||
)
|
||||
print(
|
||||
f"Sector Average News Score: {round(100*d_stats['sectorAverageNewsScore'],2)} %"
|
||||
)
|
||||
else:
|
||||
print("No sentiment stats found.")
|
||||
print("")
|
||||
Bullish: {round(100*d_stats['sentiment']['bullishPercent'],2)} %
|
||||
Bearish: {round(100*d_stats['sentiment']['bearishPercent'],2)} %
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
Sector Average Bullish: {round(100*d_stats['sectorAverageBullishPercent'],2)}
|
||||
Sector Average News Score: {round(100*d_stats['sectorAverageNewsScore'],2)} %"""
|
||||
)
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)),
|
||||
"stats",
|
||||
pd.DataFrame(d_stats),
|
||||
)
|
||||
|
||||
else:
|
||||
print("No sentiment stats found.")
|
||||
print("")
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Google Model"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import pandas as pd
|
||||
from pytrends.request import TrendReq
|
||||
|
||||
|
||||
def get_mentions(ticker: str) -> pd.DataFrame:
|
||||
"""Get interest over time from google api [Source: google]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Stock ticker
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
Dataframe of interest over time
|
||||
"""
|
||||
pytrend = TrendReq()
|
||||
pytrend.build_payload(kw_list=[ticker])
|
||||
return pytrend.interest_over_time()
|
||||
|
||||
|
||||
def get_regions(ticker: str) -> pd.DataFrame:
|
||||
"""Get interest by region from google api [Source: google]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Ticker to look at
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
Dataframe of interest by region
|
||||
"""
|
||||
pytrend = TrendReq()
|
||||
pytrend.build_payload(kw_list=[ticker])
|
||||
return pytrend.interest_by_region()
|
||||
|
||||
|
||||
def get_queries(ticker: str) -> pd.DataFrame:
|
||||
"""Get related queries from google api [Source: google]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Stock ticker to compare
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
Dataframe of related queries
|
||||
"""
|
||||
pytrend = TrendReq()
|
||||
pytrend.build_payload(kw_list=[ticker])
|
||||
return pytrend.related_queries()
|
||||
|
||||
|
||||
def get_rise(ticker: str) -> pd.DataFrame:
|
||||
"""Get top rising related queries with this stock's query [Source: google]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Stock ticker
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
Dataframe containing rising related queries
|
||||
"""
|
||||
pytrend = TrendReq()
|
||||
pytrend.build_payload(kw_list=[ticker])
|
||||
df_related_queries = pytrend.related_queries()
|
||||
return df_related_queries[ticker]["rising"]
|
||||
@@ -1,217 +1,160 @@
|
||||
import argparse
|
||||
from typing import List
|
||||
"""Google View"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pytrends.request import TrendReq
|
||||
|
||||
from tabulate import tabulate
|
||||
import matplotlib.pyplot as plt
|
||||
from gamestonk_terminal.helper_funcs import (
|
||||
check_positive,
|
||||
valid_date,
|
||||
parse_known_args_and_warn,
|
||||
)
|
||||
|
||||
from gamestonk_terminal.helper_funcs import plot_autoscale, export_data
|
||||
from gamestonk_terminal.common.behavioural_analysis import google_model
|
||||
from gamestonk_terminal import config_plot as cfp, feature_flags as gtff
|
||||
|
||||
|
||||
def mentions(other_args: List[str], ticker: str, start: datetime):
|
||||
def display_mentions(ticker: str, start: datetime, export: str = ""):
|
||||
"""Plot weekly bars of stock's interest over time. other users watchlist. [Source: Google]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : List[str]
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker
|
||||
start : str
|
||||
start : datetime
|
||||
Start date
|
||||
export: str
|
||||
Format to export data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="mentions",
|
||||
description="""
|
||||
Plot weekly bars of stock's interest over time. other users watchlist. [Source: Google]
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s",
|
||||
"--start",
|
||||
type=valid_date,
|
||||
dest="start",
|
||||
default=start,
|
||||
help="starting date (format YYYY-MM-DD) from when we are interested in stock's mentions.",
|
||||
df_interest = google_model.get_mentions(ticker)
|
||||
|
||||
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfp.PLOT_DPI)
|
||||
ax.set_title(f"Interest over time on {ticker}")
|
||||
if start:
|
||||
df_interest = df_interest[start:] # type: ignore
|
||||
ax.bar(df_interest.index, df_interest[ticker], width=2)
|
||||
ax.bar(
|
||||
df_interest.index[-1],
|
||||
df_interest[ticker].values[-1],
|
||||
color="tab:orange",
|
||||
width=2,
|
||||
)
|
||||
else:
|
||||
ax.bar(df_interest.index, df_interest[ticker], width=1)
|
||||
ax.bar(
|
||||
df_interest.index[-1],
|
||||
df_interest[ticker].values[-1],
|
||||
color="tab:orange",
|
||||
width=1,
|
||||
)
|
||||
|
||||
ax.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
ax.set_ylabel("Interest [%]")
|
||||
ax.set_xlabel("Time")
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
fig.tight_layout()
|
||||
plt.show()
|
||||
print("")
|
||||
export_data(
|
||||
export, os.path.dirname(os.path.abspath(__file__)), "mentions", df_interest
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
pytrend = TrendReq()
|
||||
pytrend.build_payload(kw_list=[ticker])
|
||||
df_interest = pytrend.interest_over_time()
|
||||
|
||||
plt.title(f"Interest over time on {ticker}")
|
||||
if ns_parser.start:
|
||||
df_interest = df_interest[ns_parser.start :]
|
||||
plt.bar(df_interest.index, df_interest[ticker], width=2)
|
||||
plt.bar(
|
||||
df_interest.index[-1],
|
||||
df_interest[ticker].values[-1],
|
||||
color="tab:orange",
|
||||
width=2,
|
||||
)
|
||||
else:
|
||||
plt.bar(df_interest.index, df_interest[ticker], width=1)
|
||||
plt.bar(
|
||||
df_interest.index[-1],
|
||||
df_interest[ticker].values[-1],
|
||||
color="tab:orange",
|
||||
width=1,
|
||||
)
|
||||
|
||||
plt.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
plt.ylabel("Interest [%]")
|
||||
plt.xlabel("Time")
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
|
||||
def regions(other_args: List[str], ticker: str):
|
||||
def display_regions(ticker: str, num: int = 5, export: str = ""):
|
||||
"""Plot bars of regions based on stock's interest. [Source: Google]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : List[str]
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker
|
||||
num: int
|
||||
Number of regions to show
|
||||
export: str
|
||||
Format to export data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="regions",
|
||||
description="""Plot bars of regions based on stock's interest. [Source: Google]""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-n",
|
||||
"--num",
|
||||
action="store",
|
||||
dest="n_num",
|
||||
type=check_positive,
|
||||
default=10,
|
||||
help="number of regions to plot that show highest interest.",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
pytrend = TrendReq()
|
||||
pytrend.build_payload(kw_list=[ticker])
|
||||
df_interest_region = pytrend.interest_by_region()
|
||||
df_interest_region = google_model.get_regions(ticker)
|
||||
if not df_interest_region.empty:
|
||||
df_interest_region = df_interest_region.sort_values(
|
||||
[ticker], ascending=False
|
||||
).head(ns_parser.n_num)
|
||||
|
||||
plt.figure(figsize=(25, 5))
|
||||
plt.title(f"Top's regions interest on {ticker}")
|
||||
plt.bar(df_interest_region.index, df_interest_region[ticker], width=0.8)
|
||||
plt.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
plt.ylabel("Interest [%]")
|
||||
plt.xlabel("Region")
|
||||
).head(num)
|
||||
df = df_interest_region.copy()
|
||||
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=cfp.PLOT_DPI)
|
||||
ax.set_title(f"Top's regions interest on {ticker}")
|
||||
ax.bar(df_interest_region.index, df_interest_region[ticker], width=0.8)
|
||||
ax.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
ax.set_ylabel("Interest [%]")
|
||||
ax.set_xlabel("Region")
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
fig.tight_layout()
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
else:
|
||||
print("No region data found.")
|
||||
print("")
|
||||
export_data(export, os.path.dirname(os.path.abspath(__file__)), "regions", df)
|
||||
|
||||
|
||||
def queries(other_args: List[str], ticker: str):
|
||||
def display_queries(ticker: str, num: int = 5, export: str = ""):
|
||||
"""Print top related queries with this stock's query. [Source: Google]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : List[str]
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker
|
||||
num: int
|
||||
Number of regions to show
|
||||
export: str
|
||||
Format to export data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="queries",
|
||||
description="""Print top related queries with this stock's query. [Source: Google]""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-n",
|
||||
"--num",
|
||||
action="store",
|
||||
dest="n_num",
|
||||
type=check_positive,
|
||||
default=10,
|
||||
help="number of top related queries to print.",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
pytrend = TrendReq()
|
||||
pytrend.build_payload(kw_list=[ticker])
|
||||
df_related_queries = pytrend.related_queries()
|
||||
df_related_queries = df_related_queries[ticker]["top"].head(ns_parser.n_num)
|
||||
df_related_queries["value"] = df_related_queries["value"].apply(
|
||||
lambda x: str(x) + "%"
|
||||
df_related_queries = google_model.get_queries(ticker)
|
||||
df = df_related_queries.copy()
|
||||
df_related_queries = df_related_queries[ticker]["top"].head(num)
|
||||
df_related_queries["value"] = df_related_queries["value"].apply(
|
||||
lambda x: str(x) + "%"
|
||||
)
|
||||
print(f"Top {ticker}'s related queries")
|
||||
if gtff.USE_TABULATE_DF:
|
||||
print(
|
||||
tabulate(
|
||||
df_related_queries,
|
||||
headers=df_related_queries.columns,
|
||||
tablefmt="fancy_grid",
|
||||
)
|
||||
)
|
||||
print(f"Top {ticker}'s related queries")
|
||||
else:
|
||||
print(df_related_queries.to_string(index=False))
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
print("")
|
||||
export_data(export, os.path.dirname(os.path.abspath(__file__)), "queries", df)
|
||||
|
||||
|
||||
def rise(other_args: List[str], ticker: str):
|
||||
def display_rise(ticker: str, num: int, export: str = ""):
|
||||
"""Print top rising related queries with this stock's query. [Source: Google]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : List[str]
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker
|
||||
num: int
|
||||
Number of regions to show
|
||||
export: str
|
||||
Format to export data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="rise",
|
||||
description="""Print top rising related queries with this stock's query. [Source: Google]""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-n",
|
||||
"--num",
|
||||
action="store",
|
||||
dest="n_num",
|
||||
type=check_positive,
|
||||
default=10,
|
||||
help="number of top rising related queries to print.",
|
||||
)
|
||||
df_related_queries = google_model.get_rise(ticker)
|
||||
df = df_related_queries.copy()
|
||||
df_related_queries = df_related_queries.head(num)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
print(f"Top rising {ticker}'s related queries")
|
||||
|
||||
pytrend = TrendReq()
|
||||
pytrend.build_payload(kw_list=[ticker])
|
||||
df_related_queries = pytrend.related_queries()
|
||||
df_related_queries = df_related_queries[ticker]["rising"].head(ns_parser.n_num)
|
||||
print(f"Top rising {ticker}'s related queries")
|
||||
if gtff.USE_TABULATE_DF:
|
||||
print(
|
||||
tabulate(
|
||||
df_related_queries,
|
||||
headers=df_related_queries.columns,
|
||||
tablefmt="fancy_grid",
|
||||
)
|
||||
)
|
||||
else:
|
||||
print(df_related_queries.to_string(index=False))
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
print("")
|
||||
export_data(export, os.path.dirname(os.path.abspath(__file__)), "rise", df)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Reddit Helpers"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
from typing import List
|
||||
import re
|
||||
|
||||
import praw
|
||||
|
||||
|
||||
def find_tickers(submission: praw.models.reddit.submission.Submission) -> List[str]:
|
||||
"""Extracts potential tickers from reddit submission
|
||||
|
||||
Parameters
|
||||
----------
|
||||
submission : praw.models.reddit.submission.Submission
|
||||
Reddit post to scan
|
||||
|
||||
Returns
|
||||
-------
|
||||
List[str]
|
||||
List of potential tickers
|
||||
"""
|
||||
ls_text = [submission.selftext, submission.title]
|
||||
submission.comments.replace_more(limit=0)
|
||||
for comment in submission.comments.list():
|
||||
ls_text.append(comment.body)
|
||||
|
||||
l_tickers_found = []
|
||||
for s_text in ls_text:
|
||||
for s_ticker in set(re.findall(r"([A-Z]{3,5} )", s_text)):
|
||||
l_tickers_found.append(s_ticker.strip())
|
||||
|
||||
return l_tickers_found
|
||||
500
gamestonk_terminal/common/behavioural_analysis/reddit_model.py
Normal file
500
gamestonk_terminal/common/behavioural_analysis/reddit_model.py
Normal file
@@ -0,0 +1,500 @@
|
||||
"""Reddit Model"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
from typing import List, Dict, Tuple
|
||||
from datetime import datetime, timedelta
|
||||
import pandas as pd
|
||||
from prawcore.exceptions import ResponseException
|
||||
from requests import HTTPError
|
||||
from psaw import PushshiftAPI
|
||||
import praw
|
||||
import finviz
|
||||
from gamestonk_terminal import config_terminal as cfg
|
||||
|
||||
from gamestonk_terminal.common.behavioural_analysis.reddit_helpers import find_tickers
|
||||
|
||||
l_sub_reddits = [
|
||||
"Superstonk",
|
||||
"pennystocks",
|
||||
"RobinHoodPennyStocks",
|
||||
"Daytrading",
|
||||
"StockMarket",
|
||||
"stocks",
|
||||
"investing",
|
||||
"wallstreetbets",
|
||||
]
|
||||
|
||||
# pylint:disable=inconsistent-return-statements
|
||||
|
||||
|
||||
def get_watchlists(
|
||||
n_to_get: int,
|
||||
) -> Tuple[List[praw.models.reddit.submission.Submission], Dict, int]:
|
||||
"""Get reddit users watchlists [Source: reddit]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
n_to_get : int
|
||||
Number of posts to look through
|
||||
|
||||
Returns
|
||||
-------
|
||||
List[praw.models.reddit.submission.Submission]:
|
||||
List of reddit submissions
|
||||
Dict:
|
||||
Dictionary of tickers and counts
|
||||
int
|
||||
Count of how many posts were analyzed
|
||||
"""
|
||||
d_watchlist_tickers: Dict = {}
|
||||
l_watchlist_author = []
|
||||
subs = []
|
||||
|
||||
praw_api = praw.Reddit(
|
||||
client_id=cfg.API_REDDIT_CLIENT_ID,
|
||||
client_secret=cfg.API_REDDIT_CLIENT_SECRET,
|
||||
username=cfg.API_REDDIT_USERNAME,
|
||||
user_agent=cfg.API_REDDIT_USER_AGENT,
|
||||
password=cfg.API_REDDIT_PASSWORD,
|
||||
)
|
||||
psaw_api = PushshiftAPI()
|
||||
submissions = psaw_api.search_submissions(
|
||||
subreddit=l_sub_reddits,
|
||||
q="WATCHLIST|Watchlist|watchlist",
|
||||
filter=["id"],
|
||||
)
|
||||
n_flair_posts_found = 0
|
||||
for sub in submissions:
|
||||
submission = praw_api.submission(id=sub.id)
|
||||
if (
|
||||
not submission.removed_by_category
|
||||
and submission.selftext
|
||||
and submission.link_flair_text not in ["Yolo", "Meme"]
|
||||
and submission.author.name not in l_watchlist_author
|
||||
):
|
||||
l_tickers_found = find_tickers(submission)
|
||||
|
||||
if l_tickers_found:
|
||||
# Add another author's name to the parsed watchlists
|
||||
l_watchlist_author.append(submission.author.name)
|
||||
|
||||
# Lookup stock tickers within a watchlist
|
||||
for key in l_tickers_found:
|
||||
if key in d_watchlist_tickers:
|
||||
# Increment stock ticker found
|
||||
d_watchlist_tickers[key] += 1
|
||||
else:
|
||||
# Initialize stock ticker found
|
||||
d_watchlist_tickers[key] = 1
|
||||
|
||||
# Increment count of valid posts found
|
||||
n_flair_posts_found += 1
|
||||
subs.append(submission)
|
||||
if n_flair_posts_found > n_to_get - 1:
|
||||
break
|
||||
return subs, d_watchlist_tickers, n_flair_posts_found
|
||||
|
||||
|
||||
def get_popular_tickers(
|
||||
n_top: int, posts_to_look_at: int, subreddits: str = ""
|
||||
) -> pd.DataFrame:
|
||||
"""Get popular tickers from list of subreddits [Source: reddit]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
n_top : int
|
||||
Number of top tickers to get
|
||||
posts_to_look_at : int
|
||||
How many posts to analyze in each subreddit
|
||||
subreddits : str, optional
|
||||
String of comma separated subreddits.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
DataFrame of top tickers from supplied subreddits
|
||||
"""
|
||||
if subreddits:
|
||||
sub_reddit_list = subreddits.split(",") if "," in subreddits else [subreddits]
|
||||
else:
|
||||
sub_reddit_list = l_sub_reddits
|
||||
d_watchlist_tickers: Dict = {}
|
||||
l_watchlist_author = []
|
||||
|
||||
praw_api = praw.Reddit(
|
||||
client_id=cfg.API_REDDIT_CLIENT_ID,
|
||||
client_secret=cfg.API_REDDIT_CLIENT_SECRET,
|
||||
username=cfg.API_REDDIT_USERNAME,
|
||||
user_agent=cfg.API_REDDIT_USER_AGENT,
|
||||
password=cfg.API_REDDIT_PASSWORD,
|
||||
)
|
||||
|
||||
psaw_api = PushshiftAPI()
|
||||
for s_sub_reddit in sub_reddit_list:
|
||||
print(
|
||||
f"Search for latest tickers for {posts_to_look_at} '{s_sub_reddit}' posts"
|
||||
)
|
||||
submissions = psaw_api.search_submissions(
|
||||
subreddit=s_sub_reddit,
|
||||
limit=posts_to_look_at,
|
||||
filter=["id"],
|
||||
)
|
||||
|
||||
n_tickers = 0
|
||||
for submission in submissions:
|
||||
try:
|
||||
# Get more information about post using PRAW api
|
||||
submission = praw_api.submission(id=submission.id)
|
||||
|
||||
# Ensure that the post hasn't been removed by moderator in the meanwhile,
|
||||
# that there is a description and it's not just an image, that the flair is
|
||||
# meaningful, and that we aren't re-considering same author's content
|
||||
if (
|
||||
not submission.removed_by_category
|
||||
and (submission.selftext or submission.title)
|
||||
and submission.author.name not in l_watchlist_author
|
||||
):
|
||||
l_tickers_found = find_tickers(submission)
|
||||
|
||||
if l_tickers_found:
|
||||
n_tickers += len(l_tickers_found)
|
||||
|
||||
# Add another author's name to the parsed watchlists
|
||||
l_watchlist_author.append(submission.author.name)
|
||||
|
||||
# Lookup stock tickers within a watchlist
|
||||
for key in l_tickers_found:
|
||||
if key in d_watchlist_tickers:
|
||||
# Increment stock ticker found
|
||||
d_watchlist_tickers[key] += 1
|
||||
else:
|
||||
# Initialize stock ticker found
|
||||
d_watchlist_tickers[key] = 1
|
||||
|
||||
except ResponseException:
|
||||
print(
|
||||
"Received a response from Reddit with an authorization error. check your token.\n"
|
||||
)
|
||||
return pd.DataFrame()
|
||||
|
||||
print(f" {n_tickers} potential tickers found.")
|
||||
lt_watchlist_sorted = sorted(
|
||||
d_watchlist_tickers.items(), key=lambda item: item[1], reverse=True
|
||||
)
|
||||
|
||||
if lt_watchlist_sorted:
|
||||
n_top_stocks = 0
|
||||
# pylint: disable=redefined-outer-name
|
||||
popular_tickers = []
|
||||
for t_ticker in lt_watchlist_sorted:
|
||||
if n_top_stocks > n_top:
|
||||
break
|
||||
try:
|
||||
# If try doesn't trigger exception, it means that this stock exists on finviz
|
||||
# thus we can print it.
|
||||
stock_info = finviz.get_stock(t_ticker[0])
|
||||
popular_tickers.append(
|
||||
(
|
||||
t_ticker[1],
|
||||
t_ticker[0],
|
||||
stock_info["Company"],
|
||||
stock_info["Sector"],
|
||||
stock_info["Price"],
|
||||
stock_info["Change"],
|
||||
stock_info["Perf Month"],
|
||||
f"https://finviz.com/quote.ashx?t={t_ticker[0]}",
|
||||
)
|
||||
)
|
||||
n_top_stocks += 1
|
||||
except HTTPError as e:
|
||||
if e.response.status_code != 404:
|
||||
print(f"Unexpected exception from Finviz: {e}")
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
popular_tickers_df = pd.DataFrame(
|
||||
popular_tickers,
|
||||
columns=[
|
||||
"Mentions",
|
||||
"Ticker",
|
||||
"Company",
|
||||
"Sector",
|
||||
"Price",
|
||||
"Change",
|
||||
"Perf Month",
|
||||
"URL",
|
||||
],
|
||||
)
|
||||
return popular_tickers_df
|
||||
|
||||
|
||||
def get_spac_community(
|
||||
limit: int, popular: bool
|
||||
) -> Tuple[List[praw.models.reddit.submission.Submission], Dict]:
|
||||
"""Get top tickers from r/SPACs [Source: reddit]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
limit : int
|
||||
Number of posts to look at
|
||||
popular : bool
|
||||
Search by hot instead of new
|
||||
|
||||
Returns
|
||||
-------
|
||||
List[praw.models.reddit.submission.Submission]:
|
||||
List of reddit submission
|
||||
Dict:
|
||||
Dictionary of tickers and number of mentions
|
||||
"""
|
||||
praw_api = praw.Reddit(
|
||||
client_id=cfg.API_REDDIT_CLIENT_ID,
|
||||
client_secret=cfg.API_REDDIT_CLIENT_SECRET,
|
||||
username=cfg.API_REDDIT_USERNAME,
|
||||
user_agent=cfg.API_REDDIT_USER_AGENT,
|
||||
password=cfg.API_REDDIT_PASSWORD,
|
||||
)
|
||||
|
||||
d_watchlist_tickers: Dict = {}
|
||||
l_watchlist_author = []
|
||||
|
||||
if popular:
|
||||
submissions = praw_api.subreddit("SPACs").hot(limit=limit)
|
||||
else:
|
||||
submissions = praw_api.subreddit("SPACs").new(limit=limit)
|
||||
|
||||
subs = []
|
||||
for sub in submissions:
|
||||
if not sub:
|
||||
break
|
||||
|
||||
# Get more information about post using PRAW api
|
||||
submission = praw_api.submission(id=sub.id)
|
||||
|
||||
# Ensure that the post hasn't been removed by moderator in the meanwhile,
|
||||
# that there is a description and it's not just an image, that the flair is
|
||||
# meaningful, and that we aren't re-considering same author's watchlist
|
||||
if (
|
||||
not submission.removed_by_category
|
||||
and submission.selftext
|
||||
and submission.link_flair_text not in ["Yolo", "Meme"]
|
||||
and submission.author.name not in l_watchlist_author
|
||||
):
|
||||
l_tickers_found = find_tickers(submission)
|
||||
|
||||
if l_tickers_found:
|
||||
# Add another author's name to the parsed watchlists
|
||||
l_watchlist_author.append(submission.author.name)
|
||||
subs.append(submission)
|
||||
# Lookup stock tickers within a watchlist
|
||||
for key in l_tickers_found:
|
||||
if key in d_watchlist_tickers:
|
||||
# Increment stock ticker found
|
||||
d_watchlist_tickers[key] += 1
|
||||
else:
|
||||
# Initialize stock ticker found
|
||||
d_watchlist_tickers[key] = 1
|
||||
return subs, d_watchlist_tickers
|
||||
|
||||
|
||||
def get_spac(
|
||||
limit: int = 5,
|
||||
) -> Tuple[List[praw.models.reddit.submission.Submission], Dict, int]:
|
||||
"""Get posts containing SPAC from top subreddits [Source: reddit]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
limit : int, optional
|
||||
Number of posts to get for each subreddit, by default 5
|
||||
|
||||
Returns
|
||||
-------
|
||||
List[praw.models.reddit.submission.Submission] :
|
||||
List of reddit submissions
|
||||
Dict :
|
||||
Dictionary of tickers and counts
|
||||
int :
|
||||
Number of posts found.
|
||||
"""
|
||||
praw_api = praw.Reddit(
|
||||
client_id=cfg.API_REDDIT_CLIENT_ID,
|
||||
client_secret=cfg.API_REDDIT_CLIENT_SECRET,
|
||||
username=cfg.API_REDDIT_USERNAME,
|
||||
user_agent=cfg.API_REDDIT_USER_AGENT,
|
||||
password=cfg.API_REDDIT_PASSWORD,
|
||||
)
|
||||
|
||||
d_watchlist_tickers: Dict = {}
|
||||
l_watchlist_author = []
|
||||
subs = []
|
||||
psaw_api = PushshiftAPI()
|
||||
submissions = psaw_api.search_submissions(
|
||||
subreddit=l_sub_reddits,
|
||||
q="SPAC|Spac|spac|Spacs|spacs",
|
||||
filter=["id"],
|
||||
)
|
||||
n_flair_posts_found = 0
|
||||
for submission in submissions:
|
||||
|
||||
# Get more information about post using PRAW api
|
||||
submission = praw_api.submission(id=submission.id)
|
||||
|
||||
# Ensure that the post hasn't been removed by moderator in the meanwhile,
|
||||
# that there is a description and it's not just an image, that the flair is
|
||||
# meaningful, and that we aren't re-considering same author's watchlist
|
||||
if (
|
||||
not submission.removed_by_category
|
||||
and submission.selftext
|
||||
and submission.link_flair_text not in ["Yolo", "Meme"]
|
||||
and submission.author.name not in l_watchlist_author
|
||||
):
|
||||
l_tickers_found = find_tickers(submission)
|
||||
subs.append(submission)
|
||||
if l_tickers_found:
|
||||
# Add another author's name to the parsed watchlists
|
||||
l_watchlist_author.append(submission.author.name)
|
||||
|
||||
# Lookup stock tickers within a watchlist
|
||||
for key in l_tickers_found:
|
||||
if key in d_watchlist_tickers:
|
||||
# Increment stock ticker found
|
||||
d_watchlist_tickers[key] += 1
|
||||
else:
|
||||
# Initialize stock ticker found
|
||||
d_watchlist_tickers[key] = 1
|
||||
|
||||
# Increment count of valid posts found
|
||||
n_flair_posts_found += 1
|
||||
|
||||
# Check if number of wanted posts found has been reached
|
||||
if n_flair_posts_found > limit - 1:
|
||||
break
|
||||
|
||||
return subs, d_watchlist_tickers, n_flair_posts_found
|
||||
|
||||
|
||||
def get_wsb_community(
|
||||
limit: int = 10, new: bool = False
|
||||
) -> List[praw.models.reddit.submission.Submission]:
|
||||
"""Get wsb posts [Source: reddit]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
limit : int, optional
|
||||
Number of posts to get, by default 10
|
||||
new : bool, optional
|
||||
Flag to sort by new instead of hot, by default False
|
||||
|
||||
Returns
|
||||
-------
|
||||
List[praw.models.reddit.submission.Submission]
|
||||
List of reddit submissions
|
||||
"""
|
||||
praw_api = praw.Reddit(
|
||||
client_id=cfg.API_REDDIT_CLIENT_ID,
|
||||
client_secret=cfg.API_REDDIT_CLIENT_SECRET,
|
||||
username=cfg.API_REDDIT_USERNAME,
|
||||
user_agent=cfg.API_REDDIT_USER_AGENT,
|
||||
password=cfg.API_REDDIT_PASSWORD,
|
||||
)
|
||||
|
||||
if new:
|
||||
submissions = praw_api.subreddit("wallstreetbets").new(limit=limit)
|
||||
else:
|
||||
submissions = praw_api.subreddit("wallstreetbets").hot(limit=limit)
|
||||
|
||||
subs = []
|
||||
for submission in submissions:
|
||||
submission = praw_api.submission(id=submission.id)
|
||||
# Ensure that the post hasn't been removed by moderator in the meanwhile,
|
||||
# that there is a description and it's not just an image, that the flair is
|
||||
# meaningful, and that we aren't re-considering same author's watchlist
|
||||
if not submission.removed_by_category:
|
||||
subs.append(submission)
|
||||
return subs
|
||||
|
||||
|
||||
def get_due_dilligence(
|
||||
ticker: str, limit: int = 5, n_days: int = 3, show_all_flairs: bool = False
|
||||
) -> List[praw.models.reddit.submission.Submission]:
|
||||
"""Gets due dilligence posts from list of subreddits [Source: reddit]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker: str
|
||||
Stock ticker
|
||||
limit: int
|
||||
Number of posts to get
|
||||
n_days: int
|
||||
Number of days back to get posts
|
||||
show_all_flairs: bool
|
||||
Search through all flairs (apart from Yolo and Meme)
|
||||
|
||||
Returns
|
||||
-------
|
||||
List[praw.models.reddit.submission.Submission]
|
||||
List of submissions
|
||||
"""
|
||||
praw_api = praw.Reddit(
|
||||
client_id=cfg.API_REDDIT_CLIENT_ID,
|
||||
client_secret=cfg.API_REDDIT_CLIENT_SECRET,
|
||||
username=cfg.API_REDDIT_USERNAME,
|
||||
user_agent=cfg.API_REDDIT_USER_AGENT,
|
||||
password=cfg.API_REDDIT_PASSWORD,
|
||||
)
|
||||
|
||||
psaw_api = PushshiftAPI()
|
||||
|
||||
n_ts_after = int((datetime.today() - timedelta(days=n_days)).timestamp())
|
||||
l_flair_text = [
|
||||
"DD",
|
||||
"technical analysis",
|
||||
"Catalyst",
|
||||
"News",
|
||||
"Advice",
|
||||
"Chart",
|
||||
"Charts and Setups",
|
||||
"Fundamental Analysis",
|
||||
"forex",
|
||||
"Trade Idea",
|
||||
]
|
||||
l_sub_reddits_dd = [
|
||||
"pennystocks",
|
||||
"RobinHoodPennyStocks",
|
||||
"Daytrading",
|
||||
"StockMarket",
|
||||
"stocks",
|
||||
"investing",
|
||||
"wallstreetbets",
|
||||
"forex",
|
||||
"Forexstrategy",
|
||||
]
|
||||
|
||||
submissions = psaw_api.search_submissions(
|
||||
after=int(n_ts_after), subreddit=l_sub_reddits_dd, q=ticker, filter=["id"]
|
||||
)
|
||||
n_flair_posts_found = 0
|
||||
subs = []
|
||||
for submission in submissions:
|
||||
# Get more information about post using PRAW api
|
||||
submission = praw_api.submission(id=submission.id)
|
||||
|
||||
# Ensure that the post hasn't been removed in the meanwhile
|
||||
if not submission.removed_by_category:
|
||||
|
||||
# Either just filter out Yolo, and Meme flairs, or focus on DD, based on b_DD flag
|
||||
if (
|
||||
submission.link_flair_text in l_flair_text,
|
||||
submission.link_flair_text not in ["Yolo", "Meme"],
|
||||
)[show_all_flairs]:
|
||||
|
||||
subs.append(submission)
|
||||
# Increment count of valid posts found
|
||||
n_flair_posts_found += 1
|
||||
|
||||
# Check if number of wanted posts found has been reached
|
||||
if n_flair_posts_found > limit - 1:
|
||||
break
|
||||
|
||||
return subs
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,306 @@
|
||||
"""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
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@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]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Stock
|
||||
metric : str
|
||||
Metric to get
|
||||
|
||||
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(),
|
||||
}
|
||||
)
|
||||
|
||||
df.sort_index(ascending=True, inplace=True)
|
||||
return df
|
||||
|
||||
|
||||
def get_top(metric: str, limit: int) -> List[List[Any]]:
|
||||
"""Get top stocks based on metric from sentimentinvestor [Source: sentimentinvestor]
|
||||
|
||||
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
|
||||
@@ -1,28 +1,24 @@
|
||||
import argparse
|
||||
import dataclasses
|
||||
import datetime
|
||||
import logging
|
||||
import multiprocessing
|
||||
import os
|
||||
import statistics
|
||||
import textwrap
|
||||
import time
|
||||
from typing import Union, Optional, List, Tuple, Any
|
||||
"""SentimentInvestor View"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
from typing import List
|
||||
|
||||
import matplotlib.dates as mdates
|
||||
import pandas as pd
|
||||
import seaborn as sns
|
||||
from colorama import Fore, Style
|
||||
import tabulate
|
||||
from colorama import Style
|
||||
from matplotlib import pyplot as plt
|
||||
from sentipy.sentipy import Sentipy
|
||||
import tabulate
|
||||
|
||||
from gamestonk_terminal import config_terminal as cfg
|
||||
from gamestonk_terminal.config_plot import PLOT_DPI
|
||||
from gamestonk_terminal.helper_funcs import (
|
||||
parse_known_args_and_warn,
|
||||
plot_autoscale,
|
||||
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
|
||||
|
||||
sentipy: Sentipy = Sentipy(
|
||||
token=cfg.API_SENTIMENTINVESTOR_TOKEN, key=cfg.API_SENTIMENTINVESTOR_KEY
|
||||
@@ -31,300 +27,26 @@ sentipy: Sentipy = Sentipy(
|
||||
|
||||
pd.plotting.register_matplotlib_converters()
|
||||
|
||||
|
||||
# suppress warning messages for a clean interface
|
||||
logging.getLogger().setLevel(logging.CRITICAL)
|
||||
|
||||
__command_descriptions = {
|
||||
"popularsi": 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.
|
||||
""",
|
||||
"emerging": f"""
|
||||
The {Style.BRIGHT}emerging{Style.RESET_ALL} command prints the stocks with highest Relative Hype 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.
|
||||
""",
|
||||
}
|
||||
# TODO: Make code more consisnet with rest of repository
|
||||
|
||||
|
||||
def sort_sentiment(metric: str, other_args: List[str], command_name: str) -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog=command_name,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description=textwrap.dedent(__command_descriptions[command_name]),
|
||||
)
|
||||
def display_top(metric: str, limit: int):
|
||||
"""Displays top stocks from sentimentinvestor based on metric [Source: sentimentinvestor]
|
||||
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--limit",
|
||||
action="store",
|
||||
dest="limit",
|
||||
type=int,
|
||||
default=10,
|
||||
help="the maximum number of stocks to retrieve",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
data = sentipy.sort(metric, ns_parser.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)])
|
||||
|
||||
print(
|
||||
tabulate.tabulate(table, headers=["Rank", "Ticker", metric], floatfmt=".3f")
|
||||
)
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
print(e, "\n")
|
||||
|
||||
|
||||
@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:
|
||||
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)
|
||||
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"))
|
||||
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",
|
||||
@@ -340,6 +62,7 @@ def _tabulate_metrics(ticker: str, metrics_list: List[_Metric]):
|
||||
|
||||
|
||||
def _customise_plot() -> None:
|
||||
"""Customizes sentimentinvestor plot"""
|
||||
sns.set(
|
||||
font="Arial",
|
||||
style="darkgrid",
|
||||
@@ -371,318 +94,124 @@ def _customise_plot() -> None:
|
||||
plt.legend(frameon=False)
|
||||
|
||||
|
||||
def _parse_args_for_ticker(other_args: List[str], ticker: str, command: str, desc: str):
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog=command,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description=desc,
|
||||
def display_metrics(ticker: str) -> None:
|
||||
"""Display sentiment investor metrics for stock ticker"""
|
||||
if not sentipy.supported(ticker):
|
||||
print("This stock is not supported by the SentimentInvestor API.")
|
||||
return
|
||||
|
||||
metric_values = sentimentinvestor_model.get_metrics(ticker)
|
||||
|
||||
if not metric_values:
|
||||
print("No data available or an error occurred.")
|
||||
return
|
||||
|
||||
print(_tabulate_metrics(ticker, metric_values))
|
||||
print()
|
||||
|
||||
|
||||
def display_social(ticker: str) -> None:
|
||||
"""Display sentiment investor social metrics for ticker"""
|
||||
if not sentipy.supported(ticker):
|
||||
print("This stock is not supported by the SentimentInvestor API.")
|
||||
return
|
||||
|
||||
metric_values = sentimentinvestor_model.get_socials(ticker)
|
||||
|
||||
if not metric_values:
|
||||
print("No data available or an error occurred.")
|
||||
return
|
||||
|
||||
print(_tabulate_metrics(ticker, metric_values))
|
||||
print("")
|
||||
|
||||
|
||||
def display_historical(
|
||||
ticker: str, sort_param: str, sort_dir: str, metric: str
|
||||
) -> None:
|
||||
"""Show historical sentiment from sentimentinvestor [Source: sentimentinvestor]
|
||||
|
||||
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'
|
||||
"""
|
||||
if not sentipy.supported(ticker):
|
||||
print("This stock is not supported by the SentimentInvestor API.")
|
||||
return
|
||||
|
||||
df = sentimentinvestor_model.get_historical(ticker, metric)
|
||||
|
||||
if df.empty:
|
||||
print("The dataset is empty, something must have gone wrong")
|
||||
return
|
||||
|
||||
_customise_plot()
|
||||
|
||||
# use seaborn to lineplot
|
||||
ax = sns.lineplot(
|
||||
data=df,
|
||||
x="date",
|
||||
y=metric,
|
||||
legend=False,
|
||||
label=[metric],
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"ticker",
|
||||
action="store",
|
||||
type=str,
|
||||
nargs="?",
|
||||
default=ticker,
|
||||
help="ticker to use instead of the loaded one",
|
||||
# always show zero on the y-axis
|
||||
plt.ylim(bottom=0)
|
||||
|
||||
# set the x-axis date formatting
|
||||
ax.xaxis.set_major_formatter(mdates.DateFormatter("%x"))
|
||||
|
||||
# scale the plot appropriately
|
||||
plt.gcf().set_size_inches(plot_autoscale())
|
||||
plt.gcf().set_dpi(PLOT_DPI)
|
||||
plt.gcf().autofmt_xdate()
|
||||
|
||||
# fill below the line
|
||||
plt.fill_between(df.date, df[metric], alpha=0.3)
|
||||
|
||||
# add title e.g. AAPL sentiment since 22/07/21
|
||||
plt.title(f"{ticker} {metric} since {min(df.date).strftime('%x')}")
|
||||
|
||||
plt.show()
|
||||
|
||||
###
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
return parse_known_args_and_warn(parser, other_args)
|
||||
# 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]
|
||||
]
|
||||
|
||||
def metrics(ticker: str, other_args: List[str]) -> None:
|
||||
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.
|
||||
"""
|
||||
|
||||
ns_parser = _parse_args_for_ticker(
|
||||
other_args=other_args,
|
||||
ticker=ticker,
|
||||
command="metrics",
|
||||
desc=textwrap.dedent(command_description),
|
||||
print(
|
||||
tabulate.tabulate(
|
||||
aggregated,
|
||||
headers=["Day", f"average {metric}"],
|
||||
tablefmt="psql",
|
||||
floatfmt=".3f",
|
||||
),
|
||||
"\n",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
if not ns_parser:
|
||||
logging.error("There was an error in parsing the command-line arguments.")
|
||||
return
|
||||
|
||||
if not sentipy.supported(ns_parser.ticker):
|
||||
print("This stock is not supported by the SentimentInvestor API.")
|
||||
return
|
||||
|
||||
data = sentipy.parsed(ns_parser.ticker)
|
||||
|
||||
metric_values = _contextualise_metrics(data, ns_parser.ticker, core_metrics)
|
||||
|
||||
if not metric_values:
|
||||
logging.error("No data available or an error occurred.")
|
||||
return
|
||||
|
||||
print(_tabulate_metrics(ns_parser.ticker, metric_values))
|
||||
print()
|
||||
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
print(e, "\n")
|
||||
|
||||
|
||||
def socials(ticker: str, other_args: List[str]) -> None:
|
||||
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.
|
||||
"""
|
||||
|
||||
try:
|
||||
|
||||
ns_parser = _parse_args_for_ticker(
|
||||
other_args=other_args,
|
||||
ticker=ticker,
|
||||
command="social",
|
||||
desc=textwrap.dedent(command_description),
|
||||
)
|
||||
|
||||
if not ns_parser:
|
||||
logging.error("There was an error in parsing the command-line arguments.")
|
||||
return
|
||||
|
||||
if not sentipy.supported(ns_parser.ticker):
|
||||
print("This stock is not supported by the SentimentInvestor API.")
|
||||
return
|
||||
|
||||
data = sentipy.raw(ns_parser.ticker)
|
||||
|
||||
metric_values = _contextualise_metrics(data, ns_parser.ticker, social_metrics)
|
||||
|
||||
if not metric_values:
|
||||
logging.error("No data available or an error occurred.")
|
||||
return
|
||||
|
||||
print(_tabulate_metrics(ns_parser.ticker, metric_values))
|
||||
print()
|
||||
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
print(e, "\n")
|
||||
|
||||
|
||||
def historical(ticker: str, other_args: List[str]) -> None:
|
||||
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(
|
||||
"-t",
|
||||
"--ticker",
|
||||
action="store",
|
||||
dest="ticker",
|
||||
type=str,
|
||||
default=ticker,
|
||||
help="ticker for which to fetch data",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s",
|
||||
"--sort",
|
||||
action="store",
|
||||
type=str,
|
||||
default="date",
|
||||
help="the parameter to sort output table by",
|
||||
dest="sort_param",
|
||||
nargs="?",
|
||||
choices=["date", "value"],
|
||||
)
|
||||
parser.add_argument(
|
||||
"-d",
|
||||
"--direction",
|
||||
action="store",
|
||||
type=str,
|
||||
default="desc",
|
||||
help="the direction to sort the output table",
|
||||
dest="sort_dir",
|
||||
nargs="?",
|
||||
choices=["asc", "desc"],
|
||||
)
|
||||
parser.add_argument(
|
||||
"metric",
|
||||
type=str,
|
||||
action="store",
|
||||
default="sentiment",
|
||||
nargs="?",
|
||||
choices=["sentiment", "AHI", "RHI", "SGP"],
|
||||
help="the metric to plot",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
logging.error("There was an error in parsing the command-line arguments.")
|
||||
return
|
||||
|
||||
if not sentipy.supported(ns_parser.ticker):
|
||||
print("This stock is not supported by the SentimentInvestor API.")
|
||||
return
|
||||
|
||||
data = sentipy.historical(
|
||||
ns_parser.ticker,
|
||||
ns_parser.metric,
|
||||
int(time.time() - 60 * 60 * 24 * 7),
|
||||
int(time.time()),
|
||||
)
|
||||
df = pd.DataFrame.from_dict(
|
||||
{
|
||||
"date": map(datetime.datetime.utcfromtimestamp, data.keys()),
|
||||
ns_parser.metric: data.values(),
|
||||
}
|
||||
)
|
||||
|
||||
df.sort_index(ascending=True, inplace=True)
|
||||
|
||||
if df.empty:
|
||||
logging.error("The dataset is empty, something must have gone wrong")
|
||||
return
|
||||
|
||||
_customise_plot()
|
||||
|
||||
# use seaborn to lineplot
|
||||
ax = sns.lineplot(
|
||||
data=df,
|
||||
x="date",
|
||||
y=ns_parser.metric,
|
||||
legend=False,
|
||||
label=[ns_parser.metric],
|
||||
)
|
||||
|
||||
# always show zero on the y-axis
|
||||
plt.ylim(bottom=0)
|
||||
|
||||
# set the x-axis date formatting
|
||||
ax.xaxis.set_major_formatter(mdates.DateFormatter("%x"))
|
||||
|
||||
# scale the plot appropriately
|
||||
plt.gcf().set_size_inches(plot_autoscale())
|
||||
plt.gcf().set_dpi(PLOT_DPI)
|
||||
plt.gcf().autofmt_xdate()
|
||||
|
||||
# fill below the line
|
||||
plt.fill_between(df.date, df[ns_parser.metric], alpha=0.3)
|
||||
|
||||
# add title e.g. AAPL sentiment since 22/07/21
|
||||
plt.title(
|
||||
f"{ns_parser.ticker} {ns_parser.metric} since {min(df.date).strftime('%x')}"
|
||||
)
|
||||
|
||||
plt.show()
|
||||
|
||||
###
|
||||
|
||||
boundary = _Boundary(
|
||||
0, max(df[ns_parser.metric].max(), 2 * df[ns_parser.metric].mean())
|
||||
)
|
||||
|
||||
# average for each day
|
||||
aggregated = df.resample("D", on="date").mean()
|
||||
|
||||
# reverse the ordering if requested
|
||||
aggregated.sort_values(
|
||||
ns_parser.metric
|
||||
if ns_parser.sort_param == "value"
|
||||
else ns_parser.sort_param,
|
||||
axis=0,
|
||||
ascending=ns_parser.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[ns_parser.metric] = [
|
||||
boundary.categorise(value)[0] + str(value) + Style.RESET_ALL
|
||||
for value in aggregated[ns_parser.metric]
|
||||
]
|
||||
|
||||
print(
|
||||
tabulate.tabulate(
|
||||
aggregated,
|
||||
headers=["Day", f"average {ns_parser.metric}"],
|
||||
tablefmt="psql",
|
||||
floatfmt=".3f",
|
||||
)
|
||||
)
|
||||
print()
|
||||
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
print(e, "\n")
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Stocktwits Model"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
from typing import Tuple, List, Dict
|
||||
|
||||
import pandas as pd
|
||||
import requests
|
||||
|
||||
|
||||
def get_bullbear(ticker: str) -> Tuple[int, int, int, int]:
|
||||
"""Gets bullbear sentiment for ticker [Source: stocktwits]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Ticker to look at
|
||||
|
||||
Returns
|
||||
-------
|
||||
int
|
||||
Watchlist count
|
||||
int
|
||||
Number of cases found for ticker
|
||||
int
|
||||
Number of bullish statements
|
||||
int
|
||||
Number of bearish statements
|
||||
"""
|
||||
result = requests.get(
|
||||
f"https://api.stocktwits.com/api/2/streams/symbol/{ticker}.json"
|
||||
)
|
||||
if result.status_code == 200:
|
||||
watchlist_count = result.json()["symbol"]["watchlist_count"]
|
||||
n_cases = 0
|
||||
n_bull = 0
|
||||
n_bear = 0
|
||||
for message in result.json()["messages"]:
|
||||
if message["entities"]["sentiment"]:
|
||||
n_cases += 1
|
||||
n_bull += message["entities"]["sentiment"]["basic"] == "Bullish"
|
||||
n_bear += message["entities"]["sentiment"]["basic"] == "Bearish"
|
||||
|
||||
return watchlist_count, n_cases, n_bull, n_bear
|
||||
return 0, 0, 0, 0
|
||||
|
||||
|
||||
def get_messages(ticker: str, limit: int = 30) -> List[str]:
|
||||
"""Get last messages for a given ticker [Source: stocktwits]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker : str
|
||||
Stock ticker
|
||||
limit : int
|
||||
Number of messages to get
|
||||
|
||||
Returns
|
||||
-------
|
||||
List[str]
|
||||
List of messages
|
||||
"""
|
||||
result = requests.get(
|
||||
f"https://api.stocktwits.com/api/2/streams/symbol/{ticker}.json"
|
||||
)
|
||||
messages = []
|
||||
if result.status_code == 200:
|
||||
for idx, message in enumerate(result.json()["messages"]):
|
||||
messages.append(message["body"])
|
||||
if idx > limit - 1:
|
||||
break
|
||||
return messages
|
||||
|
||||
|
||||
def get_trending() -> pd.DataFrame:
|
||||
"""Get trending tickers from stocktwits [Source: stocktwits]
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
Dataframe of trending tickers and watchlist count
|
||||
"""
|
||||
result = requests.get("https://api.stocktwits.com/api/2/trending/symbols.json")
|
||||
if result.status_code == 200:
|
||||
l_symbols = []
|
||||
for symbol in result.json()["symbols"]:
|
||||
l_symbols.append(
|
||||
[symbol["symbol"], symbol["watchlist_count"], symbol["title"]]
|
||||
)
|
||||
|
||||
df_trending = pd.DataFrame(
|
||||
l_symbols, columns=["Ticker", "Watchlist Count", "Name"]
|
||||
)
|
||||
return df_trending
|
||||
|
||||
return pd.DataFrame()
|
||||
|
||||
|
||||
def get_stalker(user: str, limit: int = 30) -> List[Dict]:
|
||||
"""Gets messages from given user [Source: stocktwits]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
user : str
|
||||
User to get posts for
|
||||
limit : int, optional
|
||||
Number of posts to get, by default 30
|
||||
"""
|
||||
result = requests.get(f"https://api.stocktwits.com/api/2/streams/user/{user}.json")
|
||||
if result.status_code == 200:
|
||||
messages = []
|
||||
for idx, message in enumerate(result.json()["messages"]):
|
||||
messages.append(message)
|
||||
if idx > limit - 1:
|
||||
break
|
||||
return messages
|
||||
|
||||
return []
|
||||
@@ -1,226 +1,89 @@
|
||||
import argparse
|
||||
from typing import List
|
||||
import requests
|
||||
"""Stocktwits View"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import pandas as pd
|
||||
from gamestonk_terminal.helper_funcs import check_positive, parse_known_args_and_warn
|
||||
|
||||
from tabulate import tabulate
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
from gamestonk_terminal.common.behavioural_analysis import stocktwits_model
|
||||
|
||||
|
||||
def bullbear(other_args: List[str], ticker: str):
|
||||
def display_bullbear(ticker: str):
|
||||
"""
|
||||
Print bullbear sentiment based on last 30 messages on the board.
|
||||
Also prints the watchlist_count. [Source: Stocktwits]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args: List[str]
|
||||
Arguments for argparse
|
||||
ticker: str
|
||||
Stock ticker
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="bullbear",
|
||||
description="""
|
||||
Print bullbear sentiment based on last 30 messages on the board.
|
||||
Also prints the watchlist_count. [Source: Stocktwits]
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t",
|
||||
"--ticker",
|
||||
action="store",
|
||||
dest="ticker",
|
||||
type=str,
|
||||
default=ticker,
|
||||
help="ticker to gather sentiment from.",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
result = requests.get(
|
||||
f"https://api.stocktwits.com/api/2/streams/symbol/{ns_parser.ticker}.json"
|
||||
)
|
||||
if result.status_code == 200:
|
||||
print(f"Watchlist count: {result.json()['symbol']['watchlist_count']}")
|
||||
n_cases = 0
|
||||
n_bull = 0
|
||||
n_bear = 0
|
||||
for message in result.json()["messages"]:
|
||||
if message["entities"]["sentiment"]:
|
||||
n_cases += 1
|
||||
n_bull += message["entities"]["sentiment"]["basic"] == "Bullish"
|
||||
n_bear += message["entities"]["sentiment"]["basic"] == "Bearish"
|
||||
if n_cases > 0:
|
||||
print(f"\nOver {n_cases} sentiment messages:")
|
||||
print(f"Bullish {round(100*n_bull/n_cases, 2)}%")
|
||||
print(f"Bearish {round(100*n_bear/n_cases, 2)}%")
|
||||
else:
|
||||
print("Invalid symbol")
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
watchlist_count, n_cases, n_bull, n_bear = stocktwits_model.get_bullbear(ticker)
|
||||
print(f"Watchlist count: {watchlist_count}")
|
||||
if n_cases > 0:
|
||||
print(f"\nLast {n_cases} sentiment messages:")
|
||||
print(f"Bullish {round(100*n_bull/n_cases, 2)}%")
|
||||
print(f"Bearish {round(100*n_bear/n_cases, 2)}%")
|
||||
else:
|
||||
print("No messages found")
|
||||
print("")
|
||||
|
||||
|
||||
def messages(other_args: List[str], ticker: str):
|
||||
def display_messages(ticker: str, limit: int = 30):
|
||||
"""Print up to 30 of the last messages on the board. [Source: Stocktwits]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args: List[str]
|
||||
Arguments for argparse
|
||||
ticker: str
|
||||
Stock ticker
|
||||
limit: int
|
||||
Number of messages to get
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="messages",
|
||||
description="""Print up to 30 of the last messages on the board. [Source: Stocktwits]""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t",
|
||||
"--ticker",
|
||||
action="store",
|
||||
dest="ticker",
|
||||
type=str,
|
||||
default=ticker,
|
||||
help="get board messages from this ticker.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--limit",
|
||||
action="store",
|
||||
dest="n_lim",
|
||||
type=check_positive,
|
||||
default=30,
|
||||
help="limit messages shown.",
|
||||
)
|
||||
messages = stocktwits_model.get_messages(ticker, limit)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
result = requests.get(
|
||||
f"https://api.stocktwits.com/api/2/streams/symbol/{ns_parser.ticker}.json"
|
||||
)
|
||||
if result.status_code == 200:
|
||||
for idx, message in enumerate(result.json()["messages"]):
|
||||
print(
|
||||
"------------------------------------------------------------------------------"
|
||||
)
|
||||
print(message["body"])
|
||||
if idx > ns_parser.n_lim - 1:
|
||||
break
|
||||
else:
|
||||
print("Invalid symbol")
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
|
||||
def trending(other_args: List[str]):
|
||||
"""Stocks trending. [Source: Stocktwits]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args: List[str]
|
||||
Arguments for argparse
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="trending",
|
||||
description="""Stocks trending. [Source: Stocktwits]""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
result = requests.get("https://api.stocktwits.com/api/2/trending/symbols.json")
|
||||
if result.status_code == 200:
|
||||
l_symbols = []
|
||||
for symbol in result.json()["symbols"]:
|
||||
l_symbols.append(
|
||||
[symbol["symbol"], symbol["watchlist_count"], symbol["title"]]
|
||||
)
|
||||
|
||||
pd.set_option("display.max_colwidth", None)
|
||||
df_trending = pd.DataFrame(
|
||||
l_symbols, columns=["Ticker", "Watchlist Count", "Name"]
|
||||
if gtff.USE_TABULATE_DF:
|
||||
print(
|
||||
tabulate(
|
||||
pd.DataFrame(messages), headers=[], tablefmt="grid", showindex=False
|
||||
)
|
||||
print(df_trending.to_string(index=False))
|
||||
else:
|
||||
print("Error!")
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
)
|
||||
else:
|
||||
for message in messages:
|
||||
print(message, "\n")
|
||||
|
||||
|
||||
def stalker(other_args: List[str]):
|
||||
"""Print up to the last 30 messages of a user. [Source: Stocktwits]
|
||||
def display_trending():
|
||||
"""Show trensing stocks on stocktwits"""
|
||||
df_trending = stocktwits_model.get_trending()
|
||||
if gtff.USE_TABULATE_DF:
|
||||
print(
|
||||
tabulate(
|
||||
df_trending,
|
||||
headers=df_trending.columns,
|
||||
tablefmt="fancy_grid",
|
||||
showindex=False,
|
||||
)
|
||||
)
|
||||
else:
|
||||
print(df_trending.to_string(index=False))
|
||||
print("")
|
||||
|
||||
|
||||
def display_stalker(user: str, limit: int = 10):
|
||||
"""Show last posts for given user
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args: List[str]
|
||||
Arguments for argparse
|
||||
user : str
|
||||
Stocktwits username
|
||||
limit : int, optional
|
||||
Number of messages to show, by default 10
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="stalker",
|
||||
description="""Print up to the last 30 messages of a user. [Source: Stocktwits]""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u",
|
||||
"--user",
|
||||
action="store",
|
||||
dest="s_user",
|
||||
type=str,
|
||||
default="Newsfilter",
|
||||
help="username.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--limit",
|
||||
action="store",
|
||||
dest="n_lim",
|
||||
type=check_positive,
|
||||
default=30,
|
||||
help="limit messages shown.",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
result = requests.get(
|
||||
f"https://api.stocktwits.com/api/2/streams/user/{ns_parser.s_user}.json"
|
||||
messages = stocktwits_model.get_stalker(user, limit)
|
||||
for message in messages:
|
||||
print(
|
||||
"------------------------------------------------------------------------------"
|
||||
)
|
||||
|
||||
if result.status_code == 200:
|
||||
for idx, message in enumerate(result.json()["messages"]):
|
||||
print(
|
||||
"------------------------------------------------------------------------------"
|
||||
)
|
||||
print(message["created_at"].replace("T", " ").replace("Z", ""))
|
||||
print(message["body"])
|
||||
print("")
|
||||
if idx > ns_parser.n_lim - 1:
|
||||
break
|
||||
else:
|
||||
print("Invalid user")
|
||||
print(message["created_at"].replace("T", " ").replace("Z", ""))
|
||||
print(message["body"])
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Twitter Model"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import pandas as pd
|
||||
import requests
|
||||
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
||||
|
||||
from gamestonk_terminal import config_terminal as cfg
|
||||
from gamestonk_terminal.helper_funcs import clean_tweet, get_data
|
||||
|
||||
analyzer = SentimentIntensityAnalyzer()
|
||||
|
||||
|
||||
def load_analyze_tweets(
|
||||
ticker: str,
|
||||
count: int,
|
||||
start_time: Optional[str] = "",
|
||||
end_time: Optional[str] = "",
|
||||
) -> pd.DataFrame:
|
||||
"""Load tweets from twitter API and analyzes using VADER
|
||||
|
||||
Parameters
|
||||
----------
|
||||
ticker: str
|
||||
Ticker to search twitter for
|
||||
count: int
|
||||
Number of tweets to analyze
|
||||
start : Optional[str]
|
||||
If given, the start time to get tweets from
|
||||
end : Optional[str]
|
||||
If given, the end time to get tweets from
|
||||
|
||||
Returns
|
||||
-------
|
||||
df_tweet: pd.DataFrame
|
||||
Dataframe of tweets and sentiment
|
||||
"""
|
||||
params = {
|
||||
"query": fr"(\${ticker}) (lang:en)",
|
||||
"max_results": str(count),
|
||||
"tweet.fields": "created_at,lang",
|
||||
}
|
||||
|
||||
if start_time:
|
||||
# Assign from and to datetime parameters for the API
|
||||
params["start_time"] = start_time
|
||||
if end_time:
|
||||
params["end_time"] = end_time
|
||||
|
||||
# Request Twitter API
|
||||
response = requests.get(
|
||||
"https://api.twitter.com/2/tweets/search/recent",
|
||||
params=params, # type: ignore
|
||||
headers={"authorization": "Bearer " + cfg.API_TWITTER_BEARER_TOKEN},
|
||||
)
|
||||
|
||||
# Create dataframe
|
||||
df_tweets = pd.DataFrame()
|
||||
|
||||
# Check that the API response was successful
|
||||
if response.status_code == 200:
|
||||
for tweet in response.json()["data"]:
|
||||
row = get_data(tweet)
|
||||
df_tweets = df_tweets.append(row, ignore_index=True)
|
||||
elif response.status_code == 401:
|
||||
print("Twitter API Key provided is incorrect\n")
|
||||
return pd.DataFrame()
|
||||
elif response.status_code == 400:
|
||||
print(
|
||||
"Status Code 400. This means you are requesting data from beyond the API's 7 day limit"
|
||||
)
|
||||
return pd.DataFrame()
|
||||
|
||||
sentiments = []
|
||||
pos = []
|
||||
neg = []
|
||||
neu = []
|
||||
|
||||
for s_tweet in df_tweets["text"].to_list():
|
||||
tweet = clean_tweet(s_tweet, ticker)
|
||||
sentiments.append(analyzer.polarity_scores(tweet)["compound"])
|
||||
pos.append(analyzer.polarity_scores(tweet)["pos"])
|
||||
neg.append(analyzer.polarity_scores(tweet)["neg"])
|
||||
neu.append(analyzer.polarity_scores(tweet)["neu"])
|
||||
# Add sentiments to tweets dataframe
|
||||
df_tweets["sentiment"] = sentiments
|
||||
df_tweets["positive"] = pos
|
||||
df_tweets["negative"] = neg
|
||||
df_tweets["neutral"] = neu
|
||||
|
||||
return df_tweets
|
||||
@@ -1,337 +1,182 @@
|
||||
"""Twitter view"""
|
||||
__docformat__ = "numpy"
|
||||
import argparse
|
||||
from typing import List, Optional
|
||||
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
import requests
|
||||
from dateutil import parser as dparse
|
||||
import pandas as pd
|
||||
from pandas.core.frame import DataFrame
|
||||
import numpy as np
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
||||
from gamestonk_terminal import config_terminal as cfg
|
||||
from gamestonk_terminal.helper_funcs import (
|
||||
get_data,
|
||||
clean_tweet,
|
||||
parse_known_args_and_warn,
|
||||
plot_autoscale,
|
||||
check_int_range,
|
||||
)
|
||||
import gamestonk_terminal.config_plot as cfg_plot
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from dateutil import parser as dparse
|
||||
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
|
||||
analyzer = SentimentIntensityAnalyzer()
|
||||
from gamestonk_terminal.common.behavioural_analysis import twitter_model
|
||||
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
|
||||
import gamestonk_terminal.config_plot as cfg_plot
|
||||
|
||||
|
||||
def load_analyze_tweets(
|
||||
ticker: str,
|
||||
count: int,
|
||||
start_time: Optional[str] = "",
|
||||
end_time: Optional[str] = "",
|
||||
) -> DataFrame:
|
||||
"""
|
||||
Load tweets from twitter API and analyzes using VADER
|
||||
Parameters
|
||||
----------
|
||||
ticker: str
|
||||
Ticker to search twitter for
|
||||
count: int
|
||||
Number of tweets to analyze
|
||||
start : Optional[str]
|
||||
If given, the start time to get tweets from
|
||||
end : Optional[str]
|
||||
If given, the end time to get tweets from
|
||||
|
||||
Returns
|
||||
-------
|
||||
de_tweet: pd.DataFrame
|
||||
Dataframe of tweets and sentiment
|
||||
"""
|
||||
params = {
|
||||
"query": fr"(\${ticker}) (lang:en)",
|
||||
"max_results": str(count),
|
||||
"tweet.fields": "created_at,lang",
|
||||
}
|
||||
|
||||
if start_time:
|
||||
# Assign from and to datetime parameters for the API
|
||||
params["start_time"] = start_time
|
||||
if end_time:
|
||||
params["end_time"] = end_time
|
||||
|
||||
# Request Twitter API
|
||||
response = requests.get(
|
||||
"https://api.twitter.com/2/tweets/search/recent",
|
||||
params=params, # type: ignore
|
||||
headers={"authorization": "Bearer " + cfg.API_TWITTER_BEARER_TOKEN},
|
||||
)
|
||||
|
||||
# Create dataframe
|
||||
df_tweets = pd.DataFrame()
|
||||
|
||||
# Check that the API response was successful
|
||||
if response.status_code == 200:
|
||||
for tweet in response.json()["data"]:
|
||||
row = get_data(tweet)
|
||||
df_tweets = df_tweets.append(row, ignore_index=True)
|
||||
elif response.status_code == 401:
|
||||
print("Twitter API Key provided is incorrect\n")
|
||||
return pd.DataFrame()
|
||||
elif response.status_code == 400:
|
||||
print(
|
||||
"Status Code 400. This means you are requesting data from beyond the API's 7 day limit"
|
||||
)
|
||||
return pd.DataFrame()
|
||||
|
||||
sentiments = []
|
||||
pos = []
|
||||
neg = []
|
||||
neu = []
|
||||
|
||||
for s_tweet in df_tweets["text"].to_list():
|
||||
tweet = clean_tweet(s_tweet, ticker)
|
||||
sentiments.append(analyzer.polarity_scores(tweet)["compound"])
|
||||
pos.append(analyzer.polarity_scores(tweet)["pos"])
|
||||
neg.append(analyzer.polarity_scores(tweet)["neg"])
|
||||
neu.append(analyzer.polarity_scores(tweet)["neu"])
|
||||
# Add sentiments to tweets dataframe
|
||||
df_tweets["sentiment"] = sentiments
|
||||
df_tweets["positive"] = pos
|
||||
df_tweets["negative"] = neg
|
||||
df_tweets["neutral"] = neu
|
||||
|
||||
return df_tweets
|
||||
|
||||
|
||||
def inference(other_args: List[str], ticker: str):
|
||||
def display_inference(ticker: str, num: int, export: str = ""):
|
||||
"""Infer sentiment from past n tweets
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args: List[str]
|
||||
Arguments for argparse
|
||||
ticker: str
|
||||
Stock ticker
|
||||
num: int
|
||||
Number of tweets to analyze
|
||||
export: str
|
||||
Format to export tweet dataframe
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="infer",
|
||||
description="""
|
||||
Print quick sentiment inference from last tweets that contain the ticker.
|
||||
This model splits the text into character-level tokens and uses vader sentiment analysis.
|
||||
[Source: Twitter]
|
||||
""",
|
||||
df_tweets = twitter_model.load_analyze_tweets(ticker, num)
|
||||
|
||||
if df_tweets.empty:
|
||||
return
|
||||
|
||||
# Parse tweets
|
||||
dt_from = dparse.parse(df_tweets["created_at"].values[-1])
|
||||
dt_to = dparse.parse(df_tweets["created_at"].values[0])
|
||||
print(f"From: {dt_from.strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
print(f"To: {dt_to.strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
|
||||
print(f"{len(df_tweets)} tweets were analyzed.")
|
||||
dt_delta = dt_to - dt_from
|
||||
n_freq = dt_delta.total_seconds() / len(df_tweets)
|
||||
print(f"Frequency of approx 1 tweet every {round(n_freq)} seconds.")
|
||||
|
||||
pos = df_tweets["positive"]
|
||||
neg = df_tweets["negative"]
|
||||
|
||||
percent_pos = len(np.where(pos > neg)[0]) / len(df_tweets)
|
||||
percent_neg = len(np.where(pos < neg)[0]) / len(df_tweets)
|
||||
total_sent = np.round(np.sum(df_tweets["sentiment"]), 2)
|
||||
mean_sent = np.round(np.mean(df_tweets["sentiment"]), 2)
|
||||
print(f"The summed compound sentiment of {ticker} is: {total_sent}")
|
||||
print(f"The average compound sentiment of {ticker} is: {mean_sent}")
|
||||
print(
|
||||
f"Of the last {len(df_tweets)} tweets, {100*percent_pos:.2f} % had a higher positive sentiment"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-n",
|
||||
"--num",
|
||||
action="store",
|
||||
dest="n_num",
|
||||
type=check_int_range(10, 100),
|
||||
default=100,
|
||||
help="num of latest tweets to infer from.",
|
||||
print(
|
||||
f"Of the last {len(df_tweets)} tweets, {100*percent_neg:.2f} % had a higher negative sentiment"
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
df_tweets = load_analyze_tweets(ticker, ns_parser.n_num)
|
||||
|
||||
if df_tweets.empty:
|
||||
return
|
||||
|
||||
# Parse tweets
|
||||
dt_from = dparse.parse(df_tweets["created_at"].values[-1])
|
||||
dt_to = dparse.parse(df_tweets["created_at"].values[0])
|
||||
print(f"From: {dt_from.strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
print(f"To: {dt_to.strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
|
||||
print(f"{len(df_tweets)} tweets were analyzed.")
|
||||
dt_delta = dt_to - dt_from
|
||||
n_freq = dt_delta.total_seconds() / len(df_tweets)
|
||||
print(f"Frequency of approx 1 tweet every {round(n_freq)} seconds.")
|
||||
|
||||
pos = df_tweets["positive"]
|
||||
neg = df_tweets["negative"]
|
||||
|
||||
percent_pos = len(np.where(pos > neg)[0]) / len(df_tweets)
|
||||
percent_neg = len(np.where(pos < neg)[0]) / len(df_tweets)
|
||||
total_sent = np.round(np.sum(df_tweets["sentiment"]), 2)
|
||||
mean_sent = np.round(np.mean(df_tweets["sentiment"]), 2)
|
||||
print(f"The summed compound sentiment of {ticker} is: {total_sent}")
|
||||
print(f"The average compound sentiment of {ticker} is: {mean_sent}")
|
||||
print(
|
||||
f"Of the last {len(df_tweets)} tweets, {100*percent_pos:.2f} % had a higher positive sentiment"
|
||||
)
|
||||
print(
|
||||
f"Of the last {len(df_tweets)} tweets, {100*percent_neg:.2f} % had a higher negative sentiment"
|
||||
)
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
print("")
|
||||
export_data(export, os.path.dirname(os.path.abspath(__file__)), "infer", df_tweets)
|
||||
|
||||
|
||||
def sentiment(other_args: List[str], ticker: str):
|
||||
def display_sentiment(ticker: str, n_tweets: int, n_days_past: int, export: str = ""):
|
||||
"""Plot sentiments from ticker
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args: List[str]
|
||||
Argparse arguments
|
||||
ticker: str
|
||||
Stock to get sentiment for
|
||||
n_tweets: int
|
||||
Number of tweets to get per hour
|
||||
n_days_past: int
|
||||
Number of days to extract tweets for
|
||||
export: str
|
||||
Format to export tweet dataframe
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="sentiment",
|
||||
description="""
|
||||
Plot in-depth sentiment predicted from tweets from last days
|
||||
that contain pre-defined ticker. [Source: Twitter]
|
||||
""",
|
||||
)
|
||||
# in reality this argument could be 100, but after testing it takes too long
|
||||
# to compute which may not be acceptable
|
||||
parser.add_argument(
|
||||
"-n",
|
||||
"--num",
|
||||
action="store",
|
||||
dest="n_tweets",
|
||||
type=check_int_range(10, 62),
|
||||
default=15,
|
||||
help="number of tweets to extract per hour.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-d",
|
||||
"--days",
|
||||
action="store",
|
||||
dest="n_days_past",
|
||||
type=check_int_range(1, 6),
|
||||
default=6,
|
||||
help="number of days in the past to extract tweets.",
|
||||
# Date format string required by twitter
|
||||
dtformat = "%Y-%m-%dT%H:%M:%SZ"
|
||||
|
||||
# Algorithm to extract
|
||||
dt_recent = datetime.now() - timedelta(seconds=20)
|
||||
dt_old = dt_recent - timedelta(days=n_days_past)
|
||||
print(
|
||||
f"From {dt_recent.date()} retrieving {n_tweets*24} tweets ({n_tweets} tweets/hour)"
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
df_tweets = pd.DataFrame(
|
||||
columns=[
|
||||
"created_at",
|
||||
"text",
|
||||
"sentiment",
|
||||
"positive",
|
||||
"negative",
|
||||
"neutral",
|
||||
]
|
||||
)
|
||||
while True:
|
||||
# Iterate until we haven't passed the old number of days
|
||||
if dt_recent < dt_old:
|
||||
break
|
||||
# Update past datetime
|
||||
dt_past = dt_recent - timedelta(minutes=60)
|
||||
|
||||
temp = twitter_model.load_analyze_tweets(
|
||||
ticker,
|
||||
n_tweets,
|
||||
start_time=dt_past.strftime(dtformat),
|
||||
end_time=dt_recent.strftime(dtformat),
|
||||
)
|
||||
|
||||
if temp.empty:
|
||||
return
|
||||
|
||||
# Date format string required by twitter
|
||||
dtformat = "%Y-%m-%dT%H:%M:%SZ"
|
||||
df_tweets = pd.concat([df_tweets, temp])
|
||||
|
||||
# Algorithm to extract
|
||||
dt_recent = datetime.now() - timedelta(seconds=20)
|
||||
dt_old = dt_recent - timedelta(days=ns_parser.n_days_past)
|
||||
print(
|
||||
f"From {dt_recent.date()} retrieving {ns_parser.n_tweets*24} tweets ({ns_parser.n_tweets} tweets/hour)"
|
||||
)
|
||||
|
||||
df_tweets = pd.DataFrame(
|
||||
columns=[
|
||||
"created_at",
|
||||
"text",
|
||||
"sentiment",
|
||||
"positive",
|
||||
"negative",
|
||||
"neutral",
|
||||
]
|
||||
)
|
||||
while True:
|
||||
# Iterate until we haven't passed the old number of days
|
||||
if dt_recent < dt_old:
|
||||
break
|
||||
# Update past datetime
|
||||
dt_past = dt_recent - timedelta(minutes=60)
|
||||
|
||||
temp = load_analyze_tweets(
|
||||
ticker,
|
||||
ns_parser.n_tweets,
|
||||
start_time=dt_past.strftime(dtformat),
|
||||
end_time=dt_recent.strftime(dtformat),
|
||||
if dt_past.day < dt_recent.day:
|
||||
print(
|
||||
f"From {dt_past.date()} retrieving {n_tweets*24} tweets ({n_tweets} tweets/hour)"
|
||||
)
|
||||
|
||||
if temp.empty:
|
||||
return
|
||||
# Update recent datetime
|
||||
dt_recent = dt_past
|
||||
|
||||
df_tweets = pd.concat([df_tweets, temp])
|
||||
# Sort tweets per date
|
||||
df_tweets.sort_index(ascending=False, inplace=True)
|
||||
df_tweets["cumulative_compound"] = df_tweets["sentiment"].cumsum()
|
||||
df_tweets["prob_sen"] = 1
|
||||
|
||||
if dt_past.day < dt_recent.day:
|
||||
print(
|
||||
f"From {dt_past.date()} retrieving {ns_parser.n_tweets*24} tweets ({ns_parser.n_tweets} tweets/hour)"
|
||||
)
|
||||
# df_tweets.to_csv(r'notebooks/tweets.csv', index=False)
|
||||
df_tweets.reset_index(inplace=True)
|
||||
df_tweets["Month"] = pd.to_datetime(df_tweets["created_at"]).apply(
|
||||
lambda x: x.month
|
||||
)
|
||||
df_tweets["Day"] = pd.to_datetime(df_tweets["created_at"]).apply(lambda x: x.day)
|
||||
df_tweets["date"] = pd.to_datetime(df_tweets["created_at"])
|
||||
df_tweets = df_tweets.sort_values(by="date")
|
||||
df_tweets["cumulative_compound"] = df_tweets["sentiment"].cumsum()
|
||||
_, ax = plt.subplots(2, 1, figsize=plot_autoscale(), dpi=cfg_plot.PLOT_DPI)
|
||||
ax[0].plot(
|
||||
pd.to_datetime(df_tweets["created_at"]),
|
||||
df_tweets["cumulative_compound"].values,
|
||||
lw=3,
|
||||
c="cyan",
|
||||
)
|
||||
ax[0].set_ylabel("Cumulative VADER Sentiment")
|
||||
xlocations = []
|
||||
xlabels = []
|
||||
for _, day_df in df_tweets.groupby(by="Day"):
|
||||
day_df["time"] = pd.to_datetime(day_df["created_at"])
|
||||
day_df = day_df.sort_values(by="time")
|
||||
ax[0].plot(day_df["time"], day_df["sentiment"].cumsum(), c="tab:blue")
|
||||
xlocations.append(day_df.time.values[0])
|
||||
xlabels.append(day_df["time"].apply(lambda x: x.strftime("%m-%d")).values[0])
|
||||
|
||||
# Update recent datetime
|
||||
dt_recent = dt_past
|
||||
ax[1].bar(df_tweets["date"], df_tweets["positive"], color="green", width=0.02)
|
||||
ax[1].bar(df_tweets["date"], -1 * df_tweets["negative"], color="red", width=0.02)
|
||||
ax[0].grid(b=True, which="major", color="#666666", linestyle="-", lw=1.5, alpha=0.5)
|
||||
ax[0].minorticks_on()
|
||||
ax[0].grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
ax[0].set_xticks(xlocations)
|
||||
ax[0].set_xticklabels(xlabels)
|
||||
|
||||
# Sort tweets per date
|
||||
df_tweets.sort_index(ascending=False, inplace=True)
|
||||
df_tweets["cumulative_compound"] = df_tweets["sentiment"].cumsum()
|
||||
df_tweets["prob_sen"] = 1
|
||||
|
||||
# df_tweets.to_csv(r'notebooks/tweets.csv', index=False)
|
||||
df_tweets.reset_index(inplace=True)
|
||||
df_tweets["Month"] = pd.to_datetime(df_tweets["created_at"]).apply(
|
||||
lambda x: x.month
|
||||
)
|
||||
df_tweets["Day"] = pd.to_datetime(df_tweets["created_at"]).apply(
|
||||
lambda x: x.day
|
||||
)
|
||||
df_tweets["date"] = pd.to_datetime(df_tweets["created_at"])
|
||||
df_tweets = df_tweets.sort_values(by="date")
|
||||
df_tweets["cumulative_compound"] = df_tweets["sentiment"].cumsum()
|
||||
_, ax = plt.subplots(2, 1, figsize=plot_autoscale(), dpi=cfg_plot.PLOT_DPI)
|
||||
ax[0].plot(
|
||||
pd.to_datetime(df_tweets["created_at"]),
|
||||
df_tweets["cumulative_compound"].values,
|
||||
lw=3,
|
||||
c="cyan",
|
||||
)
|
||||
ax[0].set_ylabel("Cumulative VADER Sentiment")
|
||||
xlocations = []
|
||||
xlabels = []
|
||||
for _, day_df in df_tweets.groupby(by="Day"):
|
||||
day_df["time"] = pd.to_datetime(day_df["created_at"])
|
||||
day_df = day_df.sort_values(by="time")
|
||||
ax[0].plot(day_df["time"], day_df["sentiment"].cumsum(), c="tab:blue")
|
||||
xlocations.append(day_df.time.values[0])
|
||||
xlabels.append(
|
||||
day_df["time"].apply(lambda x: x.strftime("%m-%d")).values[0]
|
||||
)
|
||||
|
||||
ax[1].bar(
|
||||
df_tweets["date"], df_tweets["positive"], color="green", width=0.02
|
||||
)
|
||||
ax[1].bar(
|
||||
df_tweets["date"], -1 * df_tweets["negative"], color="red", width=0.02
|
||||
)
|
||||
ax[0].grid(
|
||||
b=True, which="major", color="#666666", linestyle="-", lw=1.5, alpha=0.5
|
||||
)
|
||||
ax[0].minorticks_on()
|
||||
ax[0].grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
ax[0].set_xticks(xlocations)
|
||||
ax[0].set_xticklabels(xlabels)
|
||||
|
||||
ax[1].grid(
|
||||
b=True, which="major", color="#666666", linestyle="-", lw=1.5, alpha=0.5
|
||||
)
|
||||
ax[1].minorticks_on()
|
||||
ax[1].grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
ax[1].set_ylabel("VADER Polarity Scores")
|
||||
ax[1].set_xticks(xlocations)
|
||||
ax[1].set_xticklabels(xlabels)
|
||||
plt.suptitle(
|
||||
f"Twitter's {ticker} total compound sentiment over time is {np.sum(df_tweets['sentiment'])}"
|
||||
)
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
ax[1].grid(b=True, which="major", color="#666666", linestyle="-", lw=1.5, alpha=0.5)
|
||||
ax[1].minorticks_on()
|
||||
ax[1].grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
ax[1].set_ylabel("VADER Polarity Scores")
|
||||
ax[1].set_xticks(xlocations)
|
||||
ax[1].set_xticklabels(xlabels)
|
||||
plt.suptitle(
|
||||
f"Twitter's {ticker} total compound sentiment over time is {np.sum(df_tweets['sentiment'])}"
|
||||
)
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
plt.show()
|
||||
print("")
|
||||
export_data(
|
||||
export, os.path.dirname(os.path.abspath(__file__)), "sentiment", df_tweets
|
||||
)
|
||||
|
||||
@@ -5,10 +5,10 @@ import os
|
||||
import pandas as pd
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
from gamestonk_terminal.common.behavioural_analysis.finbrain_view import (
|
||||
get_sentiment,
|
||||
plot_sentiment,
|
||||
sentiment_coloring,
|
||||
)
|
||||
from gamestonk_terminal.common.behavioural_analysis.finbrain_model import get_sentiment
|
||||
from gamestonk_terminal.helper_funcs import export_data
|
||||
|
||||
PATH = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,7 @@
|
||||
"""Helper functions"""
|
||||
__docformat__ = "numpy"
|
||||
import argparse
|
||||
from argparse import ArgumentError
|
||||
from typing import List
|
||||
from datetime import datetime, timedelta, time as Time
|
||||
import os
|
||||
@@ -9,7 +10,6 @@ import re
|
||||
import sys
|
||||
import pandas as pd
|
||||
from pytz import timezone
|
||||
from prettytable import PrettyTable
|
||||
import iso8601
|
||||
import matplotlib
|
||||
import matplotlib.pyplot as plt
|
||||
@@ -315,6 +315,7 @@ def long_number_format(num) -> str:
|
||||
|
||||
|
||||
def clean_data_values_to_float(val: str) -> float:
|
||||
"""Cleans data to float based on string ending"""
|
||||
# Remove any leading or trailing parentheses and spaces
|
||||
val = val.strip("( )")
|
||||
if val == "-":
|
||||
@@ -322,19 +323,14 @@ def clean_data_values_to_float(val: str) -> float:
|
||||
|
||||
# Convert percentage to decimal
|
||||
if val.endswith("%"):
|
||||
val_as_float = float(val[:-1]) / 100.0
|
||||
# Convert from billions
|
||||
elif val.endswith("B"):
|
||||
val_as_float = float(val[:-1]) * 1_000_000_000
|
||||
# Convert from millions
|
||||
elif val.endswith("M"):
|
||||
val_as_float = float(val[:-1]) * 1_000_000
|
||||
# Convert from thousands
|
||||
elif val.endswith("K"):
|
||||
val_as_float = float(val[:-1]) * 1000
|
||||
else:
|
||||
val_as_float = float(val)
|
||||
return val_as_float
|
||||
return float(val[:-1]) / 100.0
|
||||
if val.endswith("B"):
|
||||
return float(val[:-1]) * 1_000_000_000
|
||||
if val.endswith("M"):
|
||||
return float(val[:-1]) * 1_000_000
|
||||
if val.endswith("K"):
|
||||
return float(val[:-1]) * 1000
|
||||
return float(val)
|
||||
|
||||
|
||||
def int_or_round_float(x) -> str:
|
||||
@@ -361,7 +357,7 @@ def get_next_stock_market_days(last_stock_day, n_next_days) -> list:
|
||||
year = last_stock_day.date().year
|
||||
if year not in years:
|
||||
years.append(year)
|
||||
holidays = holidays + us_market_holidays(year)
|
||||
holidays += us_market_holidays(year)
|
||||
# Check if it is a weekend
|
||||
if last_stock_day.date().weekday() > 4:
|
||||
continue
|
||||
@@ -384,13 +380,8 @@ def get_data(tweet):
|
||||
"%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
|
||||
if "full_text" in tweet.keys():
|
||||
s_text = tweet["full_text"]
|
||||
else:
|
||||
s_text = tweet["text"]
|
||||
|
||||
data = {"created_at": s_datetime, "text": s_text}
|
||||
return data
|
||||
s_text = tweet["full_text"] if "full_text" in tweet.keys() else tweet["text"]
|
||||
return {"created_at": s_datetime, "text": s_text}
|
||||
|
||||
|
||||
def clean_tweet(tweet: str, s_ticker: str) -> str:
|
||||
@@ -509,7 +500,17 @@ def parse_known_args_and_warn(parser: argparse.ArgumentParser, other_args: List[
|
||||
parser.add_argument(
|
||||
"-h", "--help", action="store_true", help="show this help message"
|
||||
)
|
||||
|
||||
try:
|
||||
parser.add_argument(
|
||||
"--export",
|
||||
choices=["png", "jpg", "pdf", "svg", "csv", "json", "xlsx"],
|
||||
default="",
|
||||
type=str,
|
||||
dest="export",
|
||||
help="Export plot to png,jpg,pdf,svg file or export dataframe to csv,json,xlsx",
|
||||
)
|
||||
except ArgumentError:
|
||||
pass
|
||||
if gtff.USE_CLEAR_AFTER_CMD:
|
||||
os.system("cls||clear")
|
||||
|
||||
@@ -530,14 +531,10 @@ def financials_colored_values(val: str) -> str:
|
||||
if val == "N/A" or str(val) == "nan":
|
||||
val = f"{Fore.YELLOW}N/A{Style.RESET_ALL}"
|
||||
elif sum(c.isalpha() for c in val) < 2:
|
||||
if "%" in val:
|
||||
if "-" in val:
|
||||
val = f"{Fore.RED}{val}{Style.RESET_ALL}"
|
||||
else:
|
||||
val = f"{Fore.GREEN}{val}{Style.RESET_ALL}"
|
||||
elif "(" in val:
|
||||
if "%" in val and "-" in val or "%" not in val and "(" in val:
|
||||
val = f"{Fore.RED}{val}{Style.RESET_ALL}"
|
||||
|
||||
elif "%" in val:
|
||||
val = f"{Fore.GREEN}{val}{Style.RESET_ALL}"
|
||||
return val
|
||||
|
||||
|
||||
@@ -626,48 +623,6 @@ def plot_autoscale():
|
||||
return x, y
|
||||
|
||||
|
||||
def print_and_record_reddit_post(submissions_dict, submission):
|
||||
# Refactor data
|
||||
s_datetime = datetime.utcfromtimestamp(submission.created_utc).strftime(
|
||||
"%d/%m/%Y %H:%M:%S"
|
||||
)
|
||||
s_link = f"https://old.reddit.com{submission.permalink}"
|
||||
s_all_awards = ""
|
||||
for award in submission.all_awardings:
|
||||
s_all_awards += f"{award['count']} {award['name']}\n"
|
||||
s_all_awards = s_all_awards[:-2]
|
||||
# Create dictionary with data to construct dataframe allows to save data
|
||||
submissions_dict[submission.id] = {
|
||||
"created_utc": s_datetime,
|
||||
"subreddit": submission.subreddit,
|
||||
"link_flair_text": submission.link_flair_text,
|
||||
"title": submission.title,
|
||||
"score": submission.score,
|
||||
"link": s_link,
|
||||
"num_comments": submission.num_comments,
|
||||
"upvote_ratio": submission.upvote_ratio,
|
||||
"awards": s_all_awards,
|
||||
}
|
||||
# Print post data collected so far
|
||||
print(f"{s_datetime} - {submission.title}")
|
||||
print(f"{s_link}")
|
||||
t_post = PrettyTable(
|
||||
["Subreddit", "Flair", "Score", "# Comments", "Upvote %", "Awards"]
|
||||
)
|
||||
t_post.add_row(
|
||||
[
|
||||
submission.subreddit,
|
||||
submission.link_flair_text,
|
||||
submission.score,
|
||||
submission.num_comments,
|
||||
f"{round(100 * submission.upvote_ratio)}%",
|
||||
s_all_awards,
|
||||
]
|
||||
)
|
||||
print(t_post)
|
||||
print("\n")
|
||||
|
||||
|
||||
def get_last_time_market_was_open(dt):
|
||||
# Check if it is a weekend
|
||||
if dt.date().weekday() > 4:
|
||||
@@ -682,23 +637,6 @@ def get_last_time_market_was_open(dt):
|
||||
return dt
|
||||
|
||||
|
||||
def find_tickers(submission):
|
||||
ls_text = []
|
||||
ls_text.append(submission.selftext)
|
||||
ls_text.append(submission.title)
|
||||
|
||||
submission.comments.replace_more(limit=0)
|
||||
for comment in submission.comments.list():
|
||||
ls_text.append(comment.body)
|
||||
|
||||
l_tickers_found = []
|
||||
for s_text in ls_text:
|
||||
for s_ticker in set(re.findall(r"([A-Z]{3,5} )", s_text)):
|
||||
l_tickers_found.append(s_ticker.strip())
|
||||
|
||||
return l_tickers_found
|
||||
|
||||
|
||||
def export_data(
|
||||
export_type: str, dir_path: str, func_name: str, df: pd.DataFrame = pd.DataFrame()
|
||||
):
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -105,7 +105,8 @@ class StocksController:
|
||||
stock_text = f"{s_intraday} Stock: {self.ticker} (from {self.start.strftime('%Y-%m-%d')})"
|
||||
else:
|
||||
stock_text = f"{s_intraday} Stock: {self.ticker}"
|
||||
|
||||
dim_if_no_ticker = Style.DIM if not self.ticker else ""
|
||||
reset_style_if_no_ticker = Style.RESET_ALL if not self.ticker else ""
|
||||
help_text = f"""
|
||||
|
||||
>> STOCKS <<
|
||||
@@ -120,11 +121,11 @@ What do you want to do?
|
||||
|
||||
{stock_text}
|
||||
Market {('CLOSED', 'OPEN')[b_is_stock_market_open()]}
|
||||
{Style.DIM if not self.ticker else ''}
|
||||
{dim_if_no_ticker}
|
||||
quote view the current price for a specific stock ticker
|
||||
candle view a candle chart for a specific stock ticker
|
||||
news latest news of the company [News API]
|
||||
{Style.RESET_ALL if not self.ticker else ''}
|
||||
{reset_style_if_no_ticker}
|
||||
>> options go into options context {'with ' if self.ticker else ''}{self.ticker}
|
||||
|
||||
> disc discover trending stocks, \t e.g. map, sectors, high short interest
|
||||
@@ -132,17 +133,17 @@ Market {('CLOSED', 'OPEN')[b_is_stock_market_open()]}
|
||||
> scr screener stocks, \t\t e.g. overview/performance, using preset filters
|
||||
> ins insider trading, \t e.g.: latest penny stock buys, top officer purchases
|
||||
> gov government menu, \t\t e.g. house trading, contracts, corporate lobbying
|
||||
> report generate automatic report, \t e.g.: dark pool, due diligence{Style.DIM if not self.ticker else ''}
|
||||
> report generate automatic report, \t e.g.: dark pool, due diligence
|
||||
> ba behavioural analysis, \t from: reddit, stocktwits, twitter, google{dim_if_no_ticker}
|
||||
> fa fundamental analysis, \t e.g.: income, balance, cash, earnings
|
||||
> res research web page, \t e.g.: macroaxis, yahoo finance, fool
|
||||
> dd in-depth due-diligence, \t e.g.: news, analyst, shorts, insider, sec
|
||||
> ca comparison analysis, \t e.g.: historical, correlation, financials
|
||||
> bt strategy backtester, \t e.g.: simple ema, ema cross, rsi strategies
|
||||
> ta technical analysis, \t e.g.: ema, macd, rsi, adx, bbands, obv
|
||||
> ba behavioural analysis, \t from: reddit, stocktwits, twitter, google
|
||||
> qa quantitative analysis, \t e.g.: decompose, cusum, residuals analysis
|
||||
> pred prediction techniques, \t e.g.: regression, arima, rnn, lstm
|
||||
{Style.RESET_ALL if not self.ticker else ''}"""
|
||||
{reset_style_if_no_ticker}"""
|
||||
print(help_text)
|
||||
|
||||
def switch(self, an_input: str):
|
||||
@@ -438,10 +439,6 @@ Market {('CLOSED', 'OPEN')[b_is_stock_market_open()]}
|
||||
|
||||
def call_ba(self, _):
|
||||
"""Process ba command"""
|
||||
if not self.ticker:
|
||||
print("Use 'load <ticker>' prior to this command!", "\n")
|
||||
return
|
||||
|
||||
ret = ba_controller.menu(
|
||||
self.ticker,
|
||||
self.start,
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
```
|
||||
usage: bullbear [-t TICKER] [-h]
|
||||
usage: bullbear [-h]
|
||||
```
|
||||
|
||||
Print bullbear sentiment based on last 30 messages on the board. Also prints the watchlist_count. [Source: Stocktwits]
|
||||
|
||||
```
|
||||
optional arguments:
|
||||
-t TICKER, --ticker TICKER
|
||||
ticker to gather sentiment from. (default: AAPL)
|
||||
-h, --help show this help message (default: False)
|
||||
```
|
||||
|
||||
|
||||
@@ -6,15 +6,35 @@ The emerging command prints the stocks with highest Relative Hype Index right no
|
||||
|
||||
RHI (Relative Hype Index)
|
||||
---
|
||||
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 the past week for that stock.
|
||||
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.
|
||||
|
||||
===
|
||||
|
||||
Sentiment Investor 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.
|
||||
Sentiment Investor 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.
|
||||
|
||||
```
|
||||
optional arguments:
|
||||
-l LIMIT, --limit LIMIT
|
||||
the maximum number of stocks to retrieve
|
||||
-h, --help show this help message
|
||||
```
|
||||
```
|
||||
|
||||
```
|
||||
(✨) (stocks)>(ba)> emerging
|
||||
Rank Ticker RHI
|
||||
------ -------- -----
|
||||
1 FINV 6.432
|
||||
2 GOVX 6.282
|
||||
3 JZXN 5.368
|
||||
4 GOGO 5.311
|
||||
5 GWW 4.993
|
||||
6 SHW 4.937
|
||||
7 EYES 4.772
|
||||
8 FSD 4.387
|
||||
9 NUAN 4.019
|
||||
10 JNUG 3.970
|
||||
```
|
||||
|
||||
@@ -10,9 +10,10 @@ optional arguments:
|
||||
limit of posts to retrieve.
|
||||
-d N_DAYS, --days N_DAYS
|
||||
number of prior days to look for.
|
||||
-a, --all search through all flairs (apart from Yolo and Meme), otherwise we focus on specific flairs: DD, technical analysis,
|
||||
Catalyst, News, Advice, Chart
|
||||
-a, --all search through all flairs (apart from Yolo and Meme), otherwise we focus on specific flairs: DD, technical
|
||||
analysis, Catalyst, News, Advice, Chart
|
||||
-h, --help show this help message
|
||||
```
|
||||
|
||||
|
||||
<img width="948" alt="popular" src="https://user-images.githubusercontent.com/25267873/108917846-4dbe0400-7628-11eb-821e-9fda97a6d9cd.png">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
```
|
||||
usage: finbrain [-h]
|
||||
usage: headlines [-h]
|
||||
```
|
||||
|
||||
FinBrain collects the news headlines from 15+ major financial news sources on a daily basis and analyzes them to generate sentiment scores for more than 4500 US stocks. FinBrain Technologies develops deep learning algorithms for financial analysis and prediction, which currently serves traders from more than 150 countries all around the world. [Source: See https://finbrain.tech]
|
||||
@@ -1,5 +1,5 @@
|
||||
```
|
||||
usage: historical [-t TICKER] [-s [{date,value}]] [-d [{asc,desc}]] [-h] [{sentiment,AHI,RHI,SGP}]
|
||||
usage: historical [-s [{date,value}]] [-d [{asc,desc}]] [-h] [{sentiment,AHI,RHI,SGP}]
|
||||
```
|
||||
|
||||
Sentiment Investor 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.
|
||||
@@ -30,8 +30,6 @@ positional arguments:
|
||||
the metric to plot
|
||||
|
||||
optional arguments:
|
||||
-t TICKER, --ticker TICKER
|
||||
ticker for which to fetch data
|
||||
-s [{date,value}], --sort [{date,value}]
|
||||
the parameter to sort output table by
|
||||
-d [{asc,desc}], --direction [{asc,desc}]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
```
|
||||
usage: metrics [-h] [ticker]
|
||||
usage: metrics [-h]
|
||||
```
|
||||
|
||||
Sentiment Investor analyzes data from four major social media platforms to
|
||||
@@ -34,9 +34,6 @@ 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.
|
||||
|
||||
```
|
||||
positional arguments:
|
||||
ticker ticker to use instead of the loaded one
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message
|
||||
```
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
```
|
||||
usage: social [-h] [ticker]
|
||||
usage: social [-h]
|
||||
```
|
||||
|
||||
Sentiment Investor 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.
|
||||
@@ -7,9 +7,6 @@ Sentiment Investor analyzes data from four major social media platforms to gener
|
||||
The social 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.
|
||||
|
||||
```
|
||||
positional arguments:
|
||||
ticker ticker to use instead of the loaded one
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message
|
||||
```
|
||||
|
||||
4
website/data/menu/main.yml
vendored
4
website/data/menu/main.yml
vendored
@@ -420,8 +420,8 @@ main:
|
||||
- name: behavioural analysis
|
||||
ref: "/stocks/behavioural_analysis"
|
||||
sub:
|
||||
- name: finbrain
|
||||
ref: "/stocks/behavioural_analysis/finbrain"
|
||||
- name: headlines
|
||||
ref: "/stocks/behavioural_analysis/headlines"
|
||||
- name: stats
|
||||
ref: "/stocks/behavioural_analysis/stats"
|
||||
- name: wsb
|
||||
|
||||
Reference in New Issue
Block a user