Python code to perform a sentiment analysis on recent Twitter Tweets about Bitcoin and plot the results into a pie chart

Here is the code ...
#Import libraries
import tweepy
import matplotlib.pyplot as plt
from textblob import TextBlob

#Set up Twitter API credentials
consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXXX'
consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'

access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'

#Authentication with Twitter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

#Create API object
api = tweepy.API(auth)

#Fetch tweets
public_tweets = api.search('Bitcoin')

#Store sentiment scores in a list
sentiment_score = []

#Loop through tweets
for tweet in public_tweets:
    analysis = TextBlob(tweet.text).sentiment
    sentiment_score.append(analysis.polarity)
    
#Calculate average sentiment score
avg_sentiment_score = sum(sentiment_score)/len(sentiment_score)

#Define sentiment polarity
if avg_sentiment_score > 0:
    sentiment = "positive"
elif avg_sentiment_score == 0:
    sentiment = "neutral"
else:
    sentiment = "negative"

#Create labels for pie chart
labels = ['Positive', 'Neutral', 'Negative']

#Data to plot
sizes = [sum([1 for score in sentiment_score if score > 0]),
         sum([1 for score in sentiment_score if score == 0]),
         sum([1 for score in sentiment_score if score < 0])]

#Create pie chart
fig1, ax1 = plt.subplots()
ax1.pie(sizes, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

Posted

in

, , , ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *