mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-11-28 12:13:11 +00:00
* Update api.py * Updated forex menu * refactor ycrv command * refactor ycrv command black * refactor ecocal command * Minh changes * Adding space to test pushing * title fix ecocal df * get economic calendar annotation * fix investingcom tests * refactor index command * refactor overview command * give defaults to wsj view function args * rename date args investincom * refacto bigmac command * fix ecocal typo * refactor rtps command * alphavantage gdp * alphavantage gdp per capita * alphavantage cpi * alphavantage tyld * alphavantage inf * refactor macro command * refactor macro command w helpers * refactor treasury command * fix macro on terminal * treasury labels * refactor maturities * update treasury maturities doc strings * refactor get economic calendar finhub * refactor map command api * display map filter choices * route economy api to performance map * route economy api to performance map * display group choices on valuation command * refactor performance and valuation commands * refactor spectrum model and view * add choices to spectrum controller * delete image after view * fix model tests finviz * fix finciz view tests * refactor futures * fix some tests * fix more tests * fix controller test * refactor fred series notes * update fred notes docstring * refacto fred series ids * fix pred and qa when empty datasets * refactor fred * uncomment stuff * refacto get series data * fix some tests * set defaults on args * refactor fred yield curve * black * fix spell and remove ecocal names * fix linting * linting * pylint fix * change dangerous defaults * Working through crypto fixes (#2256) * Working through crypto fixes * Continued adding crypto stuff * Added crypto overview * Added test fixes * Added fixtures * Fixed tests * Fixed charting issue * Removed broken APIs * Final adjustments * Added test fixes * map get groups and get ycrv countries into old api * exposed econdb helper funcs * remove helpers * refactor search indices * linting * refactor arg currency * pylint from currency * Started switching crpyto ascending to ascend * Merging * Portfolio model arguements, params, and docstring * Refactored for etf commands (#2292) * Refactored for etf commands * Fixed tests * Added load command * Fixed menu * Portfolio logic fixes * Added econometrics (#2260) * Added econometrics * Fixed tests * Simplified API * Added test fixes * Added test csv * Allowed examples to be loaded * Fund refactor (#2291) * Fund refactor * Changed fund_name and fund to name * Changed ascending to ascend * Stock menu refactoring for easier API usage (#2194) * Stocks refactoring for easier API usage * Linting * Refactor newly added features * Linting * Fixing tests * Refactor common files used by stocks menu * Fixing flake8 * Fix linting and tests * Linting * Fix flake8 * refactor insider_data * refactor mentions * refactor watchlist * refactor sentiment * refactor sentiment * fix yahoofinance tests * refactor load and candle * refactor get_news and display_news * refactor stocks.ins.act * candle default matplotlib * fix yahoofinance_view tests * fix ark model tests * fix ark view tests * fix business insider model * fix business insider view * refactor csimarket model * fix tests csi market model * update dd controller * fix get suppliers tests * fix dd controller tests * fix finhub tests * fix finviz tests * fix fmp tests * fix marketwatch tests * corrected argument keywords in test_bt_model * corrected argument keywords in test_bt_view * refactor fa controller * refactor marketwatch view * refactor gov controller * fix tests fa av * fix tests elect * fix dcf tests * fix polygon tests * fix fmp tests * fix quiverquant tests * fix yahoofinance fa tests * fix more fa tests * fix insider tests * fix more tests * fix more tests * fix options tests * fix stock gov tests * fix tests test_ba_controller * fix tests for test_finviz_compare_model.py * fixed 2 tests * fixed tests * fixed tests * fixed tests * fixed tests * fixed tests * fixed tests * fixed tests * fixed tests * fixed tests * fixed tests * fix final tests * fixed tests * fixed tests * Fix tests * black * forgot to black tests * fixed tests * fixed tests * fixed tests * fixed tests * flakefix * Tests + code : Stocks / Discovery * fix tests * added recorder * fixed tests * fixed tests * black * black * remove unused imports * refactor display raw * sia dicts fix * pylint * linting * remove dangerous default * fix tests * fix beta model test * black * skip screener qa test * change sector path to sectors * update tests readme * fix metric defaults * black * substitute lost ticker * defaults cpic * another round on sia * refactor cramer * reduce default tweets on sentiment * refactor yf hist, corr, volume * arkorders default * refactor income, balance, cashflow * refacto scorr, screener, getfinnhub * refactor stockgrid * ibkr refactor * another round on stockgrid * add dividens end point * refactor discovery endpoints * update docstrings with similar input * refactor messages * refactor ba * refactor regioons * refactor twitter sentiment * refactor hist * refactor regions * give default to timeframe * refactor bunch of defaults and arg names * remove leftover imports * refactor vwap * let tests run * fix tests * fix stock tests * fix stockanalysis tests * flake * MYPY * Made important changes * added fixes * Fixed big issue * Added fixes to tests * fix qa tests * fix tests * fix 1 more test * last stocks failing * fix crypto test Co-authored-by: Chavithra PARANA <chavithra@gmail.com> Co-authored-by: montezdesousa <montezdesousa@gmail.com> Co-authored-by: hjoaquim <h.joaquim@campus.fct.unl.pt> Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: colin99d <colin99delahunty@gmail.com> * fix portfolio tests * change period to window * update ca docstrings * refactor get_similar_companies func * Fixed * Update CI * Update CI 2 * Update CI 3 * Update dependencies Co-authored-by: colin99d <colin99delahunty@gmail.com> Co-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Co-authored-by: montezdesousa <montezdesousa@gmail.com> Co-authored-by: James Simmons <simmonsj330@gmail.com> Co-authored-by: Theodore Aptekarev <aptekarev@gmail.com> Co-authored-by: minhhoang1023 <40023817+minhhoang1023@users.noreply.github.com> Co-authored-by: jose-donato <43375532+jose-donato@users.noreply.github.com> Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: northern-64bit <75195383+northern-64bit@users.noreply.github.com> Co-authored-by: hjoaquim <h.joaquim@campus.fct.unl.pt>
203 lines
5.7 KiB
Python
203 lines
5.7 KiB
Python
"""Twitter Model"""
|
|
__docformat__ = "numpy"
|
|
|
|
from datetime import datetime, timedelta
|
|
import logging
|
|
from typing import Optional
|
|
|
|
import pandas as pd
|
|
import requests
|
|
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
|
|
|
from openbb_terminal import config_terminal as cfg
|
|
from openbb_terminal.decorators import log_start_end
|
|
from openbb_terminal.helper_funcs import clean_tweet, get_data
|
|
from openbb_terminal.rich_config import console
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
analyzer = SentimentIntensityAnalyzer()
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def load_analyze_tweets(
|
|
symbol: str,
|
|
limit: int = 100,
|
|
start_date: Optional[str] = "",
|
|
end_date: Optional[str] = "",
|
|
) -> pd.DataFrame:
|
|
"""Load tweets from twitter API and analyzes using VADER
|
|
|
|
Parameters
|
|
----------
|
|
symbol: str
|
|
Ticker symbol to search twitter for
|
|
limit: int
|
|
Number of tweets to analyze
|
|
start_date: Optional[str]
|
|
If given, the start time to get tweets from
|
|
end_date: Optional[str]
|
|
If given, the end time to get tweets from
|
|
|
|
Returns
|
|
-------
|
|
df_tweet: pd.DataFrame
|
|
Dataframe of tweets and sentiment
|
|
"""
|
|
params = {
|
|
"query": rf"(\${symbol}) (lang:en)",
|
|
"max_results": str(limit),
|
|
"tweet.fields": "created_at,lang",
|
|
}
|
|
|
|
if start_date:
|
|
# Assign from and to datetime parameters for the API
|
|
params["start_time"] = start_date
|
|
if end_date:
|
|
params["end_time"] = end_date
|
|
|
|
# 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:
|
|
tweets = []
|
|
for tweet in response.json()["data"]:
|
|
row = get_data(tweet)
|
|
tweets.append(row)
|
|
df_tweets = pd.DataFrame(tweets)
|
|
elif response.status_code == 401:
|
|
console.print("Twitter API Key provided is incorrect\n")
|
|
return pd.DataFrame()
|
|
elif response.status_code == 400:
|
|
console.print(
|
|
"""
|
|
Status Code 400.
|
|
This means you are requesting data from beyond the API's 7 day limit"""
|
|
)
|
|
return pd.DataFrame()
|
|
elif response.status_code == 403:
|
|
console.print(
|
|
f"""
|
|
Status code 403.
|
|
It seems you're twitter credentials are invalid - {response.text}
|
|
"""
|
|
)
|
|
return pd.DataFrame()
|
|
else:
|
|
console.print(
|
|
f"""
|
|
Status code {response.status_code}.
|
|
Something went wrong - {response.text}
|
|
"""
|
|
)
|
|
return pd.DataFrame()
|
|
|
|
sentiments = []
|
|
pos = []
|
|
neg = []
|
|
neu = []
|
|
|
|
for s_tweet in df_tweets["text"].to_list():
|
|
tweet = clean_tweet(s_tweet, symbol)
|
|
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
|
|
|
|
|
|
@log_start_end(log=logger)
|
|
def get_sentiment(
|
|
symbol: str,
|
|
n_tweets: int = 15,
|
|
n_days_past: int = 2,
|
|
):
|
|
"""Get sentiments from symbol
|
|
|
|
Parameters
|
|
----------
|
|
symbol: str
|
|
Stock ticker symbol 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
|
|
"""
|
|
# Date format string required by twitter
|
|
dt_format = "%Y-%m-%dT%H:%M:%SZ"
|
|
|
|
# Algorithm to extract
|
|
dt_recent = datetime.utcnow() - timedelta(seconds=20)
|
|
dt_old = dt_recent - timedelta(days=n_days_past)
|
|
console.print(
|
|
f"From {dt_recent.date()} retrieving {n_tweets*24} tweets ({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(
|
|
symbol,
|
|
n_tweets,
|
|
start_date=dt_past.strftime(dt_format),
|
|
end_date=dt_recent.strftime(dt_format),
|
|
)
|
|
|
|
if temp.empty:
|
|
return pd.DataFrame()
|
|
|
|
df_tweets = pd.concat([df_tweets, temp])
|
|
|
|
if dt_past.day < dt_recent.day:
|
|
console.print(
|
|
f"From {dt_past.date()} retrieving {n_tweets*24} tweets ({n_tweets} tweets/hour)"
|
|
)
|
|
|
|
# Update recent datetime
|
|
dt_recent = dt_past
|
|
|
|
# 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()
|
|
|
|
return df_tweets
|