DEV Community

iamkilroy
iamkilroy

Posted on

First post... Sentiment Scoring in Python with Amazon Comprehend Service

Here is an easy sentiment scoring sample that demonstrates how to calculate sentiment in stock tweets. It's probably not a fast track to stock market riches.

I pulled this code from the Amazon SageMaker Notebook I've been tinkering with. It should be pretty easy to get running using Tweepy for pulling tweets and the Amazon Comprehend NLP service to score.

import boto3
import tweepy

// Get your API keys from your Twitter developer dashboard
api_key = 'twitter-api-key'
api_secret = 'twitter-secret-api-key'
access_token = 'twitter-access-token'
access_token_secret = 'twitter-access-token-secret'

// Twitter Auth
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

# Define the search term and the date_since date as variables
stock_symbol = '$tsla'
since_date = '2020-10-08'

# Get stock tweets
tweets = tweepy.Cursor(api.search,
              q = stock_symbol,
              lang = 'en',
              since = since_date).items(10)

// Get Comprehend client
client = boto3.client('comprehend')

# Score and print tweets
for tweet in tweets:
    response = client.detect_sentiment(Text = tweet.text, LanguageCode = 'en')
    print(response, tweet.text)

Output will likely have mostly neutral scores and the occasional positive, negative, or mixed.

Sample positive output:

{'Sentiment': 'POSITIVE', 'SentimentScore': {'Positive': 0.6346455216407776, 'Negative': 0.022199517115950584, 'Neutral': 0.3431503474712372, 'Mixed': 4.635075583792059e-06}, 'ResponseMetadata': {'RequestId': '676a38f1-9ba3-4276-b883-8eb0f1594962', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '676a38f1-9ba3-4276-b883-8eb0f1594962', 'content-type': 'application/x-amz-json-1.1', 'content-length': '163', 'date': 'Fri, 09 Oct 2020 02:53:41 GMT'}, 'RetryAttempts': 0}} $RH nice setup is brewing, supporting off of the 20 EMA. look for a few more days to support at this level for a m…

Good luck and have fun with some easy sentiment scoring.

Top comments (0)