Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in and Co-Creator of Algomojo (Algorithmic Trading Platform for DIY Traders)

Twitter Based Sentiment Analysis using Natural Language Processing (NLP) – Python Code

4 min read

In this tutorial, we will be fetching REDBOXINDIA Twitter timeline and we will be doing NLP-based text sentiment analysis based on that. And give a rating of -10 to +10 where -10 being extreme negative sentiment and +10 being extreme positive sentiment and 0 being neutral sentiment (nonmarket impacting)

Natural Language Processing, or NLP, is a way for computers to understand and interpret human language. It’s a branch of artificial intelligence that helps computers communicate with us in a way that’s more natural and easier for us to understand.

One way that NLP is used is in language translation. For example, if you speak English and want to communicate with someone who speaks Spanish, you can use a language translation app that uses NLP to translate your words into Spanish and vice versa. This can make it easier to communicate with people who speak different languages.

Another way that NLP is used is in text classification. This is when a computer reads a piece of text and then categorizes it into a specific group or category. For example, a computer might be trained to classify news articles as being about politics, sports, or entertainment. This can help people find articles that are relevant to their interests more easily.

NLP is also used in sentiment analysis, which is when a computer reads a piece of text and tries to understand the emotion or attitude behind it. For example, if you wrote a review of a movie and said that it was “awful,” a sentiment analysis tool might classify your review as being negative. This can be useful for companies that want to know what people are saying about their products on social media or online reviews.

What is RedBoxGlobal India?

RedboxGlobal India is a platform that utilizes a network of traders, brokers, journalists, and analysts to deliver the earliest possible alerts of real-time, market-moving news. Financial professionals can use RedboxIndia twitter timeline to access all relevant financial news in one place. By consolidating information from multiple sources, Redbox helps users to trade more intelligently and to have a deeper understanding of market movements. RedboxIndia provides an Economical, Political, Earnings Announcement, Government Policies, Sector specific news, Market Impacting news on Twitter timeline around the clock which helps traders to get themselves to take informed trading decisions

Installing Python Libraries

Tweepy is a Python library for accessing the Twitter API. It makes it easy to authenticate with the API, search for tweets, post updates, and perform other actions with Twitter.

TextBlob is a Python library for working with human language data (text). It provides a simple API for common natural language processing tasks such as part-of-speech tagging, noun phrase extraction, sentiment analysis, classification, and more. TextBlob is built on top of the Natural Language Toolkit (NLTK), a library with a large collection of tools for working with human language data.

Both tweepy and textblob are widely used in the Python community and have a large user base. They are both well-documented and have a friendly API, making them easy to use even for those who are new to natural language processing.

To install the tweepy and textblob libraries using pip, the Python package manager, you can use the following commands:

For tweepy:

pip install tweepy

For textblob:

pip install textblob

Tweepy is often used in combination with textblob or other NLP libraries to perform analysis on tweets or other forms of social media data. For example, you might use tweepy to fetch a user’s timeline, and then use textblob to perform sentiment analysis on the tweets. You could also use tweepy to search for tweets containing certain keywords or hashtags, and then use textblob to classify the sentiment of those tweets. There are many other ways to use these libraries together or separately, depending on your needs.

To obtain a Twitter developer account and create a new app, follow these steps:

  1. Go to the Twitter Developer website (https://developer.twitter.com/).
  2. Click the “Apply” button in the top right corner of the page.
  3. Create a new developer account by following the prompts. You will need to provide your name, email address, and a brief description of how you plan to use the Twitter API.
  4. Once your developer account has been approved, log in to the developer portal.
  5. Click the “Apps” tab in the top menu.
  6. Click the “Create an app” button.
  7. Fill out the form with the necessary information about your app. This includes the app’s name, a brief description, and a website URL (if applicable). You will also need to agree to the Twitter Developer Agreement and the Developer Policy.
  8. Once you have completed the form, click the “Create” button.
  9. Your app will now be created and you will be taken to the app’s dashboard.

Creating Twitter Project

To obtain the consumer key, consumer secret, access token, and access secret key for your app, follow these steps:

  1. Go to the app’s dashboard.
  2. Click the “Keys and Tokens” tab.
  3. The consumer key and consumer secret will be listed under the “API Keys” section.
  4. Click the “Generate” button next to “Access token and secret” to generate a new access token and secret.
  5. The access token and secret will be displayed. Make sure to copy and save these values, as they will not be shown again.
Creating Consumer Keys and Access Token

That’s it! You now have the necessary keys and tokens to authenticate with the Twitter API using your app.

Twitter Sentiment Analytics Based on REDBOXINDIA Twitter timeline – Python Code


import tweepy
import textblob

# Fill in your own API keys, access tokens, and secrets
consumer_key = "<enter consumer key>"
consumer_secret = "<enter consumer secret>"
access_token = "<enter access token>"
access_token_secret = "<enter access token secret>"


# Authenticate your API keys
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)


# Fetch the @REDBOXINDIA tweets
timeline = api.user_timeline(screen_name="REDBOXINDIA")

# Analyze the sentiment of each tweet
for tweet in timeline:
    text = tweet.text
    # Perform sentiment analysis on the tweet
    analysis = textblob.TextBlob(text)
    
    # Assign a rating based on the polarity
    rating = analysis.sentiment.polarity*10
        
    print(f"Tweet: {text}")
    print(f"Sentiment score: {rating}\n")

Sample Output from Twitter Sentimental Analysis over REDBOXGLOBAL INDIA timeline

Tweet: NSE INDEX PROVISIONALLY ENDS DOWN 0.24% OR -42.75 POINTS AT 18,000.20

@NSEIndia
Sentiment score: -1.5555555555555558

Tweet: *Rustomjee in Focus - Keystone Realtors enters Mumbai eastern suburbs with Rs 1,000-crore project (Current Market C… https://t.co/p16hMROSxt
Sentiment score: 0.0

Tweet: KL Rahul not part of T20 team in future

: BCCI Official
#Breaking_News 

@BCCI 

@klrahul
Sentiment score: 0.0

Tweet: RAGHAV PRODUCTIVITY: INVESTOR MUKUL AGRAWAL AND ASHISH KACHOLIA NAME APPEAR IN SHARE HOLDING WITH STAKE OF 1.64% AND 2.13% RESPECTIVELY
Sentiment score: 0.0

Tweet: RELAXO FOOTWEARS: Rs 34.42cr NSE Block Trade; for ~392447 shares, at Rs 877

#BIGBLOCK
Sentiment score: 0.0

Tweet: JANUARY CRITICAL IN TERMS OF COVID-19 SPREAD AS NEW VARIANTS BEING FOUND: INDIA HEALTH MINISTRY SOURCES

NEW VARIAN… https://t.co/FhpJl3yTOS
Sentiment score: 0.909090909090909

Tweet: SURYODAY SMALL FINANCE BANK LTD -  Q3 GROSS ADVANCES 54.09 BLN RUPEES, UP 11% Y/Y

SURYODAY SMALL FINANCE BANK LTD… https://t.co/o7apsSHU53
Sentiment score: -1.6666666666666665

Tweet: UJJIVAN SMALL FINANCE BANK LTD -  DEC-QTR TOTAL DEPOSITS 231.54 BLN RUPEES, UP 49% Y/Y https://t.co/eHvpflDt9h
Sentiment score: -1.25

Tweet: FINOLEX: CO ANNOUNCE LAUNCH OF 'ELECTRIC IRONS' IN SMALL DOMESTIC APPLIANCE CATEGORY
Sentiment score: -1.25

Tweet: MARICO Q3 INDIA BUSINESS HAD MID-SINGLE-DIGIT VOLUME GROWTH

POOR SHOW
Sentiment score: -4.0

Tweet: FORTIS HEALTHCARE: Rs 42.98cr BSE Block Trade; for ~1500000 shares, at Rs 286.5

#BIGBLOCK
Sentiment score: 0.0

Tweet: ABB INDIA: Rs 43.74cr BSE Block Trade; for ~158465 shares, at Rs 2760

#BIGBLOCK
Sentiment score: 0.0

Tweet: LUPIN: CO LAUNCHES NOVEL FIXED-DOSE TRIPLE DRUG COMBINATION DIFIZMA DPI TO TREAT INADEQUATELY CONTROLLED ASTHMA
Sentiment score: 0.0
Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in and Co-Creator of Algomojo (Algorithmic Trading Platform for DIY Traders)

Twitter Based Sentiment Analysis using Natural Language Processing (NLP)…

In this tutorial, we will be fetching REDBOXINDIA Twitter timeline and we will be doing NLP-based text sentiment analysis based on that. And give...
Rajandran R
4 min read

How to Retrieve Opening Balance, Total Turnover, Realized and…

This tutorial explores how to access the limits API functionality in Algomojo using python to retrieve the Account Balance, Total Turnover, Realized, UnRealized PNL,...
Rajandran R
1 min read

Introduction to Backtrader – Creating your First Trading Strategy…

Backtrader is an open-source python framework for backtesting, optimizing, and deploying live algorithmic trading strategies.
Rajandran R
54 sec read

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More