Created
September 9, 2021 00:39
-
-
Save marcosan93/e305eca2c4f77c86f2ae2550a0f7a9cc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def sentimentAndPrice(ticker, start, end, numtweets=20): | |
| """ | |
| Visually compares sentiment with the closing price of a given stock ticker. | |
| """ | |
| # Creating a DF that contains daily tweets between two dates | |
| df = tweetByDay(start, end, pd.DataFrame(), search="$"+ticker, limit=numtweets) | |
| # Analyzing the sentiment of each tweet | |
| sent_df = getSentiment( | |
| df, | |
| measurement='compound' | |
| ) | |
| # Getting stock price history | |
| stock_df = getStockPrices( | |
| ticker, | |
| start, | |
| end | |
| ) | |
| # Merging the two DF | |
| comb_df = sent_df.merge(stock_df, how='outer', sort=True) | |
| # Shifting the sentiment scores 1 day to compensate for lookahead bias | |
| comb_df['sentiment'] = comb_df['sentiment'].shift(1) | |
| # How often sentiment matched return | |
| # Dropping NAs so they are not compared | |
| drop_df = comb_df.dropna() | |
| # Comparing matches | |
| match = (drop_df['sentiment'].apply(lambda x: x>0)==drop_df['returns'].apply(lambda x: x>0)) | |
| # Counting instances where they match | |
| match = match.value_counts().rename({False: "Didn't predict return", | |
| True: "Successfully predicted return"}).to_frame() | |
| # Visualizing matches in sentiment and return | |
| fig = px.bar( | |
| match, | |
| x=0, | |
| y=match.index, | |
| color=match.index, | |
| title="Instances when Sentiment predicts Return", | |
| labels={"index": "Prediction", | |
| "0": "Count"} | |
| ) | |
| fig.show() | |
| # Visualizing the sentiment and price | |
| fig = px.bar( | |
| comb_df, | |
| x='date', | |
| y=['returns', 'sentiment'], | |
| barmode='group', | |
| title=f"Returns & Sentiment over Time for {ticker}" | |
| ) | |
| return fig.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment