tg / app /bot_utils.py
rabiyulfahim's picture
Update app/bot_utils.py
122aadc verified
import requests
import yfinance as yf
from sklearn.linear_model import LinearRegression
import pandas as pd
import os
from dotenv import load_dotenv
load_dotenv() # Loads from .env file
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
def format_number(n):
if isinstance(n, (int, float)):
return f"{n:,.2f}"
return "N/A"
def predict_future_price(ticker: str, days_ahead=1) -> float:
try:
df = yf.Ticker(ticker).history(period="6mo")
df['Target'] = df['Close'].shift(-days_ahead)
df['MA5'] = df['Close'].rolling(5).mean()
df['MA10'] = df['Close'].rolling(10).mean()
df.dropna(inplace=True)
X = df[['Close', 'MA5', 'MA10']]
y = df['Target']
model = LinearRegression()
model.fit(X, y)
latest_features = pd.DataFrame([X.iloc[-1]], columns=X.columns)
# latest_features = X.iloc[-1].values.reshape(1, -1)
predicted_price = model.predict(latest_features)[0]
return round(predicted_price, 2)
except Exception as e:
print(f"โŒ Prediction error: {e}")
return None
def fetch_stock_summary(ticker: str) -> str:
try:
stock = yf.Ticker(ticker)
info = stock.info
name = info.get("shortName", "N/A")
current_price = info.get("currentPrice", None)
pe_ratio = info.get("trailingPE", None)
eps = info.get("trailingEps", None)
sector = info.get("sector", "N/A")
market_cap = info.get("marketCap", None)
week_high = info.get("fiftyTwoWeekHigh", None)
week_low = info.get("fiftyTwoWeekLow", None)
buy_price = current_price * 0.97 if current_price else None
future_price = predict_future_price(ticker)
summary = (
f"๐Ÿ“Š *{name}* (`{ticker}`)\n"
f"๐Ÿข Sector: {sector}\n"
f"๐Ÿ’ฐ Current Price: โ‚น{format_number(current_price)}\n"
f"๐Ÿ“ˆ 52W High: โ‚น{format_number(week_high)} | ๐Ÿ“‰ Low: โ‚น{format_number(week_low)}\n"
f"๐Ÿ“Š PE Ratio: {format_number(pe_ratio)} | ๐Ÿงฎ EPS: {format_number(eps)}\n"
f"๐Ÿ’ผ Market Cap: โ‚น{format_number(market_cap)}\n\n"
f"๐Ÿ›’ Suggested Buy Price: โ‚น{format_number(buy_price)}\n"
f"๐Ÿš€ Predicted Future Price: โ‚น{format_number(future_price)}\n")
return summary
except Exception as e:
return f"โš ๏ธ Failed to fetch stock data for {ticker}. Error: {e}"
def send_telegram_message(message: str, chat_id=CHAT_ID):
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
payload = {'chat_id': chat_id, 'text': message, 'parse_mode': 'Markdown'}
response = requests.post(url, data=payload)
print(response.status_code)
print(response.content)
if response.status_code == 200:
return "โœ… Message sent successfully!"
else:
return f"โŒ Failed to send message. Status: {response.status_code}, Response: {response.text}"