Spaces:
Sleeping
Sleeping
| 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}" | |