-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
119 lines (94 loc) · 4.26 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
from config import TICKERS
from utils import get_token
from analysis import analyze_stock
from ml_forecast import predict_stock_price
from chart import send_stock_chart
from trend_classifier import classify_trend
import telebot
import logging
import yfinance as yf
import matplotlib.pyplot as plt
import tempfile
# Настройка логирования
logging.basicConfig(level=logging.INFO)
bot = telebot.TeleBot(get_token())
@bot.message_handler(commands=['start'])
def send_welcome(message):
chat_id = message.chat.id
keyboard = telebot.types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True)
buttons = [telebot.types.KeyboardButton(ticker) for ticker in TICKERS]
keyboard.add(*buttons)
bot.send_message(chat_id, 'Выберите тикер:', reply_markup=keyboard)
@bot.message_handler(commands=['help'])
def send_help(message):
chat_id = message.chat.id
help_text = """
📌 Доступные команды:
/start - выбрать тикер
/chart - показать график
/forecast - прогноз цены
/trend - анализ тренда
"""
bot.send_message(chat_id, help_text)
@bot.message_handler(func=lambda message: message.text in TICKERS)
def select_ticker(message):
chat_id = message.chat.id
selected_ticker = message.text
bot.send_message(chat_id, f'📊 Тикер {selected_ticker} выбран. Ожидайте анализ...')
keyboard = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add(telebot.types.KeyboardButton("Назад"))
bot.send_message(chat_id, "Выберите действие:", reply_markup=keyboard)
try:
data = analyze_stock(selected_ticker)
last_price = float(data["Close"].iloc[-1])
signal_text = f'📌 Анализ {selected_ticker}:\nПоследняя цена: {last_price:.2f}\n'
bot.send_message(chat_id, signal_text)
predicted_price = predict_stock_price(selected_ticker)
bot.send_message(chat_id, f'🔮 Прогноз цены на завтра: ${predicted_price:.2f}')
trend = classify_trend(selected_ticker)
bot.send_message(chat_id, f'📊 {trend}')
send_stock_chart(selected_ticker, chat_id)
except Exception as e:
logging.exception("Ошибка при обработке запроса")
bot.send_message(chat_id, f'Ошибка: {str(e)}')
@bot.message_handler(commands=['chart'])
def send_chart_options(message):
chat_id = message.chat.id
keyboard = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add(telebot.types.KeyboardButton("1 месяц"))
keyboard.add(telebot.types.KeyboardButton("6 месяцев"))
keyboard.add(telebot.types.KeyboardButton("1 год"))
bot.send_message(chat_id, "Выберите период для графика:", reply_markup=keyboard)
@bot.message_handler(func=lambda message: message.text in ["1 месяц", "6 месяцев", "1 год"])
def send_selected_chart(message):
chat_id = message.chat.id
period_map = {"1 месяц": "1mo", "6 месяцев": "6mo", "1 год": "1y"}
period = period_map[message.text]
send_stock_chart(message.text, chat_id, period)
@bot.message_handler(func=lambda message: message.text == "Назад")
def go_back(message):
send_welcome(message)
# Обновленный модуль chart.py
def send_stock_chart(ticker, chat_id, period="1d"):
data = yf.download(ticker, period=period, interval="1d")
if data.empty:
bot.send_message(chat_id, f'Не удалось получить данные для построения графика {ticker}.')
return
plt.figure(figsize=(10, 5))
plt.plot(data.index, data['Close'], label=f'{ticker} Price', color='blue')
plt.title(f'{ticker} - Динамика за {period}')
plt.xlabel('Дата')
plt.ylabel('Цена')
plt.legend()
plt.grid()
plt.tight_layout()
with tempfile.NamedTemporaryFile(suffix=".png") as tmpfile:
plt.savefig(tmpfile.name)
plt.close()
tmpfile.seek(0)
bot.send_photo(chat_id, tmpfile)
if __name__ == '__main__':
try:
bot.polling(none_stop=True)
except Exception as e:
logging.exception("Ошибка в основном цикле polling")