Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deprecate reddit commands taking too long to connect to PushshiftAPI #3999

Merged
merged 26 commits into from
Jan 24, 2023
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
94ae277
fix tk
montezdesousa Jan 17, 2023
32adeef
fix newsletters
montezdesousa Jan 17, 2023
a353790
fix lt
montezdesousa Jan 17, 2023
5402200
exception on pir
montezdesousa Jan 17, 2023
6d4a465
fix attrib bug and remove warning
montezdesousa Jan 17, 2023
736d7a9
fix earnings
montezdesousa Jan 17, 2023
0bbfb3d
fix ins, lt, whatif
montezdesousa Jan 17, 2023
acd0d62
fillna
montezdesousa Jan 17, 2023
c2a445b
fix vis
montezdesousa Jan 17, 2023
ed024b7
timeout reddit func
montezdesousa Jan 17, 2023
7bb981d
fix interest
montezdesousa Jan 17, 2023
cf61e71
black
montezdesousa Jan 17, 2023
406edd6
pylint
montezdesousa Jan 17, 2023
5aca673
Merge branch 'develop' into hotfix/reddit
montezdesousa Jan 17, 2023
ec130f7
Merge branch 'develop' into hotfix/reddit
montezdesousa Jan 17, 2023
fd7fbff
pylint again
montezdesousa Jan 17, 2023
9181c6a
Merge branch 'hotfix/reddit' of github.com:OpenBB-finance/OpenBBTermi…
montezdesousa Jan 17, 2023
2558811
back to timeout
montezdesousa Jan 17, 2023
dc93948
Merge branch 'develop' into hotfix/reddit
jmaslek Jan 22, 2023
8f3deeb
Merge branch 'develop' into hotfix/reddit
montezdesousa Jan 23, 2023
d1418c9
rewind
montezdesousa Jan 23, 2023
29d05f9
deprecate pushshift api commands
montezdesousa Jan 23, 2023
9aa5043
Merge branch 'develop' into hotfix/reddit
jmaslek Jan 24, 2023
b3aae2a
rewrite expected
montezdesousa Jan 24, 2023
fb8674b
Merge branch 'hotfix/reddit' of github.com:OpenBB-finance/OpenBBTermi…
montezdesousa Jan 24, 2023
843f2b4
Merge branch 'develop' into hotfix/reddit
jmaslek Jan 24, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions openbb_terminal/common/behavioural_analysis/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from openbb_terminal.rich_config import console


class APITimeoutError(Exception):
"""API Timeout Error"""

def __init__(self):
super().__init__()
console.print("[red]API is not responding - timeout.[/red]\n")
2 changes: 2 additions & 0 deletions openbb_terminal/common/behavioural_analysis/google_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ def display_correlation_interest(
colors = theme.get_colors()[1:]
for idx, word in enumerate(words):
df_interest = google_model.get_mentions(word)
if df_interest.empty:
continue
ax[1].plot(df_interest.index, df_interest[word], "-", color=colors[idx])

ax[1].set_ylabel("Interest [%]")
Expand Down
90 changes: 86 additions & 4 deletions openbb_terminal/common/behavioural_analysis/reddit_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@

import logging
from datetime import datetime, timedelta
from os import environ
from typing import List, Tuple
import warnings
from multiprocessing import Process, Queue
import time

import finviz
import pandas as pd
Expand All @@ -18,6 +21,7 @@
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

from openbb_terminal import config_terminal as cfg
from openbb_terminal.common.behavioural_analysis.exceptions import APITimeoutError
from openbb_terminal.common.behavioural_analysis.reddit_helpers import find_tickers
from openbb_terminal.decorators import check_api_key, log_start_end
from openbb_terminal.rich_config import console
Expand All @@ -35,6 +39,49 @@
"wallstreetbets",
]

if environ.get("DEBUG_MODE", "false") != "true":
warnings.filterwarnings("ignore", category=UserWarning, module="psaw")


def worker(func, queue):
"""Worker to run in parallel.

Parameters
----------
func : function
Function to run
queue : Queue
Queue to put the return value in
"""
ret = func()
queue.put(ret)


def get_PushshiftAPI(wait: int = 20) -> PushshiftAPI:
"""Get PushshiftAPI.

Parameters
----------
wait : int
Number of seconds to wait for PushshiftAPI to respond

Returns
-------
PushshiftAPI
PushshiftAPI object
"""

queue: Queue = Queue()
p = Process(target=worker, args=(PushshiftAPI, queue))
p.start()
time.sleep(wait)
if p.is_alive():
p.terminate()
p.join()
raise APITimeoutError

return queue.get()


@log_start_end(log=logger)
@check_api_key(
Expand Down Expand Up @@ -92,7 +139,16 @@ def get_watchlists(
console.print("[red]Wrong Reddit API keys[/red]\n")
return [], {}, 0

psaw_api = PushshiftAPI()
try:
console.print("Connecting to API...")
psaw_api = get_PushshiftAPI()
except APITimeoutError:
return [], {}, 0
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pushshift has been down over a month. lets deprecate anything using it


if not psaw_api:
console.print("[red]API is not responding.[/red]\n")
return [], {}, 0

submissions = psaw_api.search_submissions(
subreddit=l_sub_reddits,
q="WATCHLIST|Watchlist|watchlist",
Expand Down Expand Up @@ -202,7 +258,15 @@ def get_popular_tickers(
console.print("[red]Wrong Reddit API keys[/red]\n")
return pd.DataFrame()

psaw_api = PushshiftAPI()
try:
console.print("Connecting to API...")
psaw_api = get_PushshiftAPI()
except APITimeoutError:
return pd.DataFrame()

if not psaw_api:
console.print("[red]API is not responding.[/red]\n")
return pd.DataFrame()

for s_sub_reddit in sub_reddit_list:
console.print(
Expand Down Expand Up @@ -518,7 +582,17 @@ def get_spac(
"Link",
]
subs = pd.DataFrame(columns=columns)
psaw_api = PushshiftAPI()

try:
console.print("Connecting to API...")
psaw_api = get_PushshiftAPI()
except APITimeoutError:
return pd.DataFrame(), {}, 0

if not psaw_api:
console.print("[red]API is not responding.[/red]\n")
return pd.DataFrame(), {}, 0

submissions = psaw_api.search_submissions(
subreddit=l_sub_reddits,
q="SPAC|Spac|spac|Spacs|spacs",
Expand Down Expand Up @@ -763,7 +837,15 @@ def get_due_dilligence(
console.print("[red]Wrong Reddit API keys[/red]\n")
return pd.DataFrame()

psaw_api = PushshiftAPI()
try:
console.print("Connecting to API...")
psaw_api = get_PushshiftAPI()
except APITimeoutError:
return pd.DataFrame()

if not psaw_api:
console.print("[red]API is not responding.[/red]\n")
return pd.DataFrame()

n_ts_after = int((datetime.today() - timedelta(days=n_days)).timestamp())
l_flair_text = [
Expand Down
8 changes: 5 additions & 3 deletions openbb_terminal/portfolio/portfolio_engine.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Portfolio Engine"""
__docformat__ = "numpy"

from os import environ
import warnings
import logging
from typing import Dict, Any
Expand Down Expand Up @@ -193,9 +194,10 @@ def read_transactions(path: str) -> pd.DataFrame:

# Load transactions from file
if path.endswith(".xlsx"):
warnings.filterwarnings(
"ignore", category=UserWarning, module="openpyxl", lineno=312
)
if environ.get("DEBUG_MODE", "false") != "true":
warnings.filterwarnings(
"ignore", category=UserWarning, module="openpyxl"
)
transactions = pd.read_excel(path)
elif path.endswith(".csv"):
transactions = pd.read_csv(path)
Expand Down