Telegram bot yields a ‘null’ output when processing a ticker input; it fails to return a chart. Below is revised code using Flask and yfinance:
import requests
from flask import Flask, request, jsonify
import yfinance as yf
import matplotlib.pyplot as plt
app = Flask(__name__)
BOT_ENDPOINT = 'https://api.telegram.org/botYOURTOKEN/'
def fetch_chat_id(payload):
return payload['message']['chat']['id']
def fetch_text(payload):
return payload['message']['text']
def reply_message(response_data):
requests.post(BOT_ENDPOINT + 'sendMessage', json=response_data)
def create_chart(symbol):
stock = yf.Ticker(symbol)
data = stock.history(period='1y')
plt.figure()
plt.plot(data['Close'])
plt.title('Stock Close Prices')
plt.savefig('chart.png')
return "Chart generated."
@app.route('/', methods=['POST'])
def handle_request():
payload = request.get_json()
result = create_chart(fetch_text(payload))
resp = {"chat_id": fetch_chat_id(payload), "text": result}
reply_message(resp)
return jsonify(success=True)
if __name__ == '__main__':
app.run()
Based on my experience, the null output might be a result of the information being passed to the ticker function not being cleanly parsed or validated before use. I encountered a similar issue in the past where incorrect or extra characters in the user input caused yfinance to return empty data. It is beneficial to include checks after fetching the stock data to ensure that the historical data is valid before attempting to generate the chart. This can also guide you to properly handle exceptions that may arise from misformatted inputs.
My experience with similar issues suggests checking the input value being passed to yfinance closely. Errors can occur if there’s any discrepancy in the ticker symbol format, such as leading or trailing spaces or case mismatches. I had a similar problem where validating and normalizing the input solved the null output issue. Additionally, incorporating logging right before querying the API helped me determine whether the expected data was received at each stage. Ensuring that the bot receives and processes a clean string can greatly improve reliability when generating the chart.
hey, could be your token or file perms. I’ve seen cases where an empty dataset caused null responses. try verifying that your ticker yields data and that chart.png can be saved. also, ensure the bot token is valid and passed correctly.