Skip to content

Instantly share code, notes, and snippets.

@marcosan93
Created September 9, 2021 00:39
Show Gist options
  • Select an option

  • Save marcosan93/e305eca2c4f77c86f2ae2550a0f7a9cc to your computer and use it in GitHub Desktop.

Select an option

Save marcosan93/e305eca2c4f77c86f2ae2550a0f7a9cc to your computer and use it in GitHub Desktop.
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