DEV Community

Cover image for Connecting a Telegram Bot with Yahoo Finance using Python
Damilare Abogunrin
Damilare Abogunrin

Posted on • Updated on

Connecting a Telegram Bot with Yahoo Finance using Python

Python is a popular programming language for creating chatbots, and Telegram is a widely used messaging platform for building chatbots. One useful application of Python and Telegram chatbots is to connect them with financial data sources like Yahoo Finance to create a stock market monitoring bot. By integrating Yahoo Finance's API with Python and Telegram, users can easily get real-time stock prices and other relevant financial data without leaving the messaging app.

In this way, the bot can help users make informed decisions about their investment portfolios. In this project, we will explore how to use Python and Telegram to build a chatbot that fetches stock data from Yahoo Finance's API and delivers it to users in real-time.

Packages Needed

  • Windows CMD
  • API TOKEN from BotFather
  • telegram.ext and requests libraries

Guide

  1. Head over to Telegram and search for BotFather. Tap on Start
  2. Type in '/newbot' in the new field to create a new bot. Pick a username for your bot. Ensure it ends with 'bot'. For our bot, we'll pick yf_data_grabber_bot.
  3. Grab your API TOKEN from the HTTP API section in the displayed field.
  4. Head over to your Command Panel. On a WINDOWS machine, that'd be CMD, or Windows PowerShell if you fancy.
  5. If you haven't already, install the telegram package with the pip installer. Use the command:
pip install python.telegram-bot.
Enter fullscreen mode Exit fullscreen mode

6 Create a new folder(preferably) to host your project in. We'll name ours: YF DATA GRABBER BOT. Use mkdir YF_DATABOT to shorten the whole process.
7 Create a python file to host your code in. Ours would be: datagrabber.py.
8 Import the installed library, and the requests library, with the command:

import telegram.ext
import requests
Enter fullscreen mode Exit fullscreen mode

9 Store your API KEY in a relevant variable. Ours would simply be 'token' i.e
token = 'xxxxx';
10 Here's the full code.

import telegram.ext
import requests
token="xxxxx";

# Define a command handler for the /stock command
def stock_handler(update, context):
    # Get the argument passed to the /stock command
    stock_symbol = context.args[0]

    # Fetch the stock data from Yahoo Finance API
    api_url = f"https://query1.finance.yahoo.com/v10/finance/quoteSummary/{stock_symbol}?modules=price"
    response = requests.get(api_url)
    if response.status_code != 200:
        update.message.reply_text("Sorry, something went wrong while fetching the stock data.")
        return
    stock_info = response.json()["quoteSummary"]["result"][0]["price"]

    # Format the stock data as a message
    message = f"Symbol: {stock_info['symbol']}\nName: {stock_info['longName']}\nCurrent Price: {stock_info['regularMarketPrice']['fmt']}"

    # Send the message back to the user
    update.message.reply_text(message)

# Set up the Telegram bot using telegram.ext
updater = telegram.ext.Updater("YOUR_BOT_TOKEN")
dispatcher = updater.dispatcher

# Register the stock_handler function as the handler for the /stock command
dispatcher.add_handler(telegram.ext.CommandHandler("stock", stock_handler))

# Start polling for updates from Telegram
updater.start_polling()
updater.idle()
Enter fullscreen mode Exit fullscreen mode

Conclusion

Connecting a Telegram bot with Yahoo Finance using Python can be a powerful tool for investors and traders looking to keep track of real-time market data. With the integration of Yahoo Finance's API and Python, users can easily access relevant financial data and receive personalized updates on their investment portfolio right within their Telegram chat.

This project demonstrates how to create a chatbot that can fetch stock data from Yahoo Finance's API and deliver it to users through Telegram, enabling them to make informed decisions about their investments. With the right tools and knowledge, building a stock monitoring bot that utilizes the power of Python and Telegram is a straightforward and effective way to stay up-to-date with the latest market trends.

Top comments (0)