The Wayback Machine - https://web.archive.org/web/20240705162740/https://www.geeksforgeeks.org/how-to-build-a-twitter-bot-to-post-latest-stock-update-using-python/
Open In App

How to Build a Twitter Bot to Post Latest Stock Update using Python

Last Updated : 21 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The stock market is volatile and changes rapidly so we are going to create a simple Twitter bot to post the latest stock updates using Python that posts the tweet about the stocks that users have chosen. First, let’s understand the prerequisites of our project:

  • Nsepython: It is a Python library to get publicly available data on the current NSEIndia and NIFTY Indices sites by communicating with their REST APIs.
  • Tweepy: It is an open-source Python package from which you can access Twitter API easily.
  • Python-dotenv: It reads key-value pairs from a .env file and can set them as environment variables.

Required Modules

pip install nsepython
pip install tweepy
pip install python-dotenv

Creating Twitter Developer Account

After getting all the requirements it’s necessary to create a Twitter developer account to access twitter’s API and get our credentials you can use any account for that.

Step 1:  Go to the Twitter Developer Portal https://developer.twitter.com/en 

 

Step 2: Choose an email account and provide information such as country name.

 

Step 3: Choose the use case for making a bot. Click on Let’s do this button.

 

Step 4: Accept the development agreement.

 

Creating and Setting up the Project

Step 1: Choose the Project name.

 

Step 2: Save all the keys for later use in our code.

 

Step 3: Change Project permissions.

 

Step 4: Change the app permission from Read to Read and Write.

 

Step 5: Choose the type of app as Bot and enter the call-back URL as you prefer.

 

Step 6: Save your client keys.

 

File structure

Project_name
    .env
    tweet.py
    main.py

Code Implementation to Build a Twitter Bot to Post Latest Stock Update

Create a project folder, In that folder create a .env file name and save all the keys in it according to the following format.

API_KEY = “<YOUR_API_KEY>”
API_SECRET = “<YOUR_API_SECRET_KEY>”
BEARER_TOKEN = “<YOUR_BEARER_TOKEN>”

CLIENT_KEY = “<YOUR_CLIENT_KEY>”
CLIENT_SECRET = “<YOUR_CLIENT_SECRET>”

ACCESS_TOKEN = “<YOUR_ACCESS_TOKEN>”
ACCESS_TOKEN_SECRET = “<YOUR_ACCESS_TOKEN_SECRET>”

Step 1: Create a new file in the same folder named tweet.py and import all the libraries.

Python3




import tweepy 
from dotenv import load_dotenv
import os


Step 2: The load_dotenv() import the .env file from the folder. After that save the keys in the respective variables.

Python3




load_dotenv()
  
api_key = os.getenv('API_KEY')
api_secret = os.getenv('API_SECRET')
access_token = os.getenv('ACCESS_TOKEN')
access_token_secret = os.getenv('ACCESS_TOKEN_SECRET')
bearer_token = os.getenv('BEARER_TOKEN')


Step 3: Create the client which will be responsible for sending requests and receiving responses from Twitter API. Tweepy contains a function called Client which accepts keys as parameters.

Python3




client = tweepy.Client(bearer_token, 
                       api_key,api_secret,
                       access_token, 
                       access_token_secret)


Step 4: Now that we have written the code for posting the tweet we will write the code for getting the stock information and automating the process for posting the tweet.

This tweet function accepts params that contain the stock information from our main program (main.py: We will create later) and posts the tweet using the create_tweet() function.

Python3




import tweepy 
from dotenv import load_dotenv
import os
  
load_dotenv()
  
api_key = os.getenv('API_KEY')
api_secret = os.getenv('API_SECRET')
access_token = os.getenv('ACCESS_TOKEN')
access_token_secret = os.getenv
                ('ACCESS_TOKEN_SECRET')
bearer_token = os.getenv('BEARER_TOKEN')
  
client = tweepy.Client(bearer_token, api_key,api_secret, access_token, access_token_secret)
  
def tweet(params):
    tweetVal = ""
    for stock in params:
        tweetVal += stock + "\n"
          
    client.create_tweet(text=tweetVal, user_auth=True)
    print("tweet Successful!")


Step 5: Create a file called main.py in <project_name> folder and import the following libraries. Here, the time module is used for stopping the program after each tweet, and the tweet is the Python file(tweet.py) that we created above where we wrote the code for posting tweets.

Python3




from nsetools import Nse
import time
import tweet


Step 6: In the run function first, we created the object for the nse which will send the request to nse API and accept the response from it. Next, we will create the Python list for the stock name from where we want the information. 

Note: We have used the stock code for the company you can get the stock code by using the comment line below the code. See here for more information. You can also add more stocks according to requirements.

def run():
    nse = Nse()
    stockList = ['INFY', 'HCLTECH', 'WIPRO']
    # get all stock codes
    # all_stock_codes = nse.get_stock_codes() 
    i=0
    size = len(stockList)

Step 7: Next, we initialized i variable which will be our iterator, and next, we have taken the size of our stock list. In Python, while loop we have taken each stock from our stock list according to the index and iterator variable value the modulo operation between size and i helps to traverse the list circularly.

Then get_quote() function takes a stock value and returns the information about the specific stock and returns several values but we only need specific values which are stored in a list called keyValues. The params we have gotten as the response will be a dictionary so we will traverse through it and store the required values in the list called values according to our keyValues.
In last, The tweet function from the tweet file we have imported along with the values updates out the iterator variable and stops the program for 20 seconds you can also modify this value.

Python3




def run():
    nse = Nse()
    stockList = ['INFY', 'HCLTECH', 'WIPRO']
    # get all stock codes
    # all_stock_codes = nse.get_stock_codes() 
    i=0
    size = len(stockList)
        
    while(1):
        stock = stockList[i%size]
        params = nse.get_quote(stock)
        keyValues = ["companyName", "dayHigh", "basePrice",
                     "dayLow", "buyPrice1", "lastPrice"]
          
        values = []
        for key,value in params.items():
            if key in keyValues:
                values.append(key + ":" + str(value))
          
        tweet.tweet(values)
          
        i = i+1
        time.sleep(20)


Step 8: After running the program your bot should be running.

Python3




from nsetools import Nse
import time
import tweet
  
def run():
    nse = Nse()
    stockList = ['INFY', 'HCLTECH', 'WIPRO']
    # get all stock codes
    # all_stock_codes = nse.get_stock_codes()
    i=0
    size = len(stockList)
        
    while(1):
        stock = stockList[i%size]
        params = nse.get_quote(stock)
        keyValues = ["companyName", "dayHigh", 
                     "basePrice", "dayLow", "buyPrice1",
                     "lastPrice"]
          
        values = []
        for key,value in params.items():
            if key in keyValues:
                values.append(key + ":" + str(value))
          
        tweet.tweet(values)
          
        i = i+1
        time.sleep(20)
  
if __name__ == '__main__':
    run()


Output:

 



Similar Reads

How to make a Twitter Bot in Python?
Twitter is an American microblogging and social networking service on which users post and interact with messages known as "tweets". In this article we will make a Twitter Bot using Python. Python as well as Javascript can be used to develop an automatic Twitter bot that can do many tasks by its own such as: Retweets the tweets with particular #has
3 min read
How to Build a Simple Auto-Login Bot with Python
In this article, we are going to see how to built a simple auto-login bot using python. In this present scenario, every website uses authentication and we have to log in by entering proper credentials. But sometimes it becomes very hectic to login again and again to a particular website. So, to come out of this problem lets, built our own auto logi
3 min read
How to Build Web scraping bot in Python
In this article, we are going to see how to build a web scraping bot in Python. Web Scraping is a process of extracting data from websites. A Bot is a piece of code that will automate our task. Therefore, A web scraping bot is a program that will automatically scrape a website for data, based on our requirements. Module neededbs4: Beautiful Soup(bs
8 min read
Build a GUI Application to Get Live Stock Price using Python
The stock price is the highest amount someone is willing to pay for the stock. In this article, we are going to write code for getting live share prices for each company and bind it with GUI Application. Module Needed Yahoo_fin: This module is used to scrape historical stock price data, as well as to provide current information on market caps, divi
3 min read
How to Build a Stock Market News Android App using Retrofit?
Building a stock market news app can be a great way to stay informed about the latest developments in the financial world. This article will explore how to build a simple news app using Kotlin and Retrofit. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.org/wp-cont
12 min read
Update Jupyter Notebook to the Latest Python Version
To take advantage of the latest features and improvements in Python, it is important to keep your Jupyter Notebook updated with the latest Python version. This article will guide you through the process of updating Jupyter Notebook to the latest Python version. Note: Let's say if we want to Download Install from Python 3.7 to 3.11: Checking the Cur
3 min read
Update Dash to Latest Version
Dash, a popular Python web framework for building interactive web applications, is continuously evolving with new features, enhancements, and bug fixes. To ensure you are leveraging the latest improvements, updating Dash to the most recent version is crucial. In this article, we'll walk through the steps to update Dash in your Python environment. I
4 min read
Google Chrome Dino Bot using Image Recognition | Python
What would you see in your Chrome browser when there is no internet connection? Yes, everybody knows that dinosaur game that comes on screen. So, in this article, we are going to build a simple python bot that plays Chrome Dino Game without user interaction. Here we are not using any machine learning or artificial intelligence to counter this probl
4 min read
Instagram Bot using Python and InstaPy
In this article, we will design a simple fun project “Instagram Bot” using Python and InstaPy. As beginners want to do some extra and learning small projects so that it will help in building big future projects. Now, this is the time to learn some new projects and a better future. This python project gives the functionality of Instagram bot to like
3 min read
Create a Telegram Bot using Python
In this article, we are going to see how to create a telegram bot using Python. In recent times Telegram has become one of the most used messaging and content sharing platforms, it has no file sharing limit like Whatsapp and it comes with some preinstalled bots one can use in any channels (groups in case of whatsapp) to control the behavior or filt
6 min read
three90RightbarBannerImg