|
| 1 | +# import tweepy library for twitter api access and textblob libary for sentiment analysis |
| 2 | +import csv |
| 3 | +import tweepy |
| 4 | +import numpy as np |
| 5 | +from textblob import TextBlob |
| 6 | +import datetime |
| 7 | +import time |
| 8 | + |
| 9 | +def main(): |
| 10 | + |
| 11 | + # set twitter api credentials |
| 12 | + consumer_key= 'MOe623rxcqck6x8y5XhzK8MJT' |
| 13 | + consumer_secret= 'mcBq9Km1f3OYERRD6vKmOfWSgCjsqzXAreIsn8klxAtPIo40E7' |
| 14 | + access_token='913787859630460928-RXF8NVN3gGbxD64NCZ7wBma5M2WPwlv' |
| 15 | + access_token_secret='P4UU9I2DimdnUown2EM6p4WZ0ftdPNsysDNW6xGh0Ts4f' |
| 16 | + |
| 17 | + # set path of csv file to save sentiment stats |
| 18 | + path = 'live_tweet.csv' |
| 19 | + f = open(path,"a") |
| 20 | + f1 = open('tweet_data','a') |
| 21 | + # access twitter api via tweepy methods |
| 22 | + auth = tweepy.OAuthHandler(consumer_key, consumer_secret) |
| 23 | + auth.set_access_token(access_token, access_token_secret) |
| 24 | + twitter_api = tweepy.API(auth) |
| 25 | + |
| 26 | + while True: |
| 27 | + |
| 28 | + # fetch tweets by keywords |
| 29 | + tweets = twitter_api.search(q=['bitcoin, price, crypto'], count=100) |
| 30 | + |
| 31 | + # get polarity |
| 32 | + polarity = get_polarity(tweets,f1) |
| 33 | + sentiment = np.mean(polarity) |
| 34 | + |
| 35 | + # save sentiment data to csv file |
| 36 | + f.write(str(sentiment)) |
| 37 | + f.write(","+datetime.datetime.now().strftime("%y-%m-%d-%H-%M")) |
| 38 | + f.write("\n") |
| 39 | + f.flush() |
| 40 | + time.sleep(60) |
| 41 | + |
| 42 | + |
| 43 | +def get_polarity(tweets,f): |
| 44 | + # run polarity analysis on tweets |
| 45 | + |
| 46 | + tweet_polarity = [] |
| 47 | + |
| 48 | + for tweet in tweets: |
| 49 | + f.write(tweet.text+'\n') |
| 50 | + analysis = TextBlob(tweet.text) |
| 51 | + tweet_polarity.append(analysis.sentiment.polarity) |
| 52 | + |
| 53 | + return tweet_polarity |
| 54 | + |
| 55 | +main() |
0 commit comments