Open In App

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

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:

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.




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.




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.




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.




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.




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.




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.




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:

 


Article Tags :