Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
314 lines (252 loc) · 12.5 KB
/
Copy pathmain.py
File metadata and controls
314 lines (252 loc) · 12.5 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""
Главный скрипт для анализа котировок акций через CLI
"""
import asyncio
import logging
import yaml
import os
import sys
from pathlib import Path
from datetime import date, datetime
# Настройка кодировки для Windows
if sys.platform == 'win32':
import codecs
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')
# Добавление src в путь
sys.path.insert(0, str(Path(__file__).parent))
from src.data_loader import load_stock_data, DataLoader
from src.database import Database
from src.llm_manager import OpenRouterClient
from src.company_info import CompanyInfoProvider
from src.analyzer import StockAnalyzer
from src.excel_exporter import ExcelExporter
from src.price_fetcher import YahooFinanceFetcher
def setup_logging(config: dict) -> None:
"""
Настройка логирования
Args:
config: Конфигурация
"""
log_config = config.get('logging', {})
log_level = log_config.get('level', 'INFO')
log_format = log_config.get('format', '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Создание директории для логов
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
# Настройка логирования
logging.basicConfig(
level=getattr(logging, log_level),
format=log_format,
handlers=[
logging.FileHandler(log_dir / "analysis.log", encoding='utf-8'),
logging.StreamHandler()
]
)
def load_config() -> dict:
"""
Загрузка конфигурации из структуры config/
Returns:
Словарь с конфигурацией
"""
# Проверка структуры config/
config_dir = Path("config")
api_keys_path = config_dir / "api_keys.yaml"
llm_config_path = config_dir / "llm_config.yaml"
companies_path = config_dir / "companies.json"
# Если есть новая структура - используем её
if api_keys_path.exists() and llm_config_path.exists():
# logger еще не инициализирован на этом этапе
config = {}
# API ключи
with open(api_keys_path, 'r', encoding='utf-8') as f:
api_keys = yaml.safe_load(f)
config['openrouter'] = {
'api_key': api_keys.get('openrouter_api_key', ''),
'base_url': 'https://openrouter.ai/api/v1'
}
# Сохраняем alphavantage_api_key отдельно
saved_alphavantage_key = api_keys.get('alphavantage_api_key', '')
# LLM конфигурация
with open(llm_config_path, 'r', encoding='utf-8') as f:
llm_config = yaml.safe_load(f)
# Сохраняем api_key перед обновлением
saved_api_key = config['openrouter']['api_key']
saved_base_url = config['openrouter']['base_url']
config.update(llm_config)
# Восстанавливаем api_key и обновляем base_url
if 'openrouter' not in config:
config['openrouter'] = {}
config['openrouter']['api_key'] = saved_api_key
if 'openrouter' in llm_config and 'base_url' in llm_config['openrouter']:
config['openrouter']['base_url'] = llm_config['openrouter']['base_url']
else:
config['openrouter']['base_url'] = saved_base_url
# Добавляем alphavantage_api_key в company_info
if 'company_info' not in config:
config['company_info'] = {}
config['company_info']['alphavantage_api_key'] = saved_alphavantage_key
# Путь к списку компаний
if companies_path.exists():
config['input'] = {'excel_file': str(companies_path)}
else:
# logger еще не инициализирован
config['input'] = {'excel_file': ''}
# Переменные окружения имеют приоритет
api_key = os.getenv('OPENROUTER_API_KEY')
if api_key:
config['openrouter']['api_key'] = api_key
return config
# Конфигурация не найдена
raise FileNotFoundError(
"Конфигурация не найдена!\n"
"Создайте файлы:\n"
" - config/api_keys.yaml (API ключи)\n"
" - config/llm_config.yaml (настройки LLM и проекта)\n"
" - config/companies.json (список компаний)\n\n"
"Примеры файлов:\n"
" - config/api_keys.example.yaml\n"
" - config/llm_config.example.yaml\n"
" - config/companies.example.json"
)
def print_banner() -> None:
"""Вывод баннера приложения"""
banner = """
╔═══════════════════════════════════════════════════════════════╗
║ ║
║ 📊 Stock Quotes Analyzer 📊 ║
║ ║
║ Анализ котировок через OpenRouter LLM ║
║ ║
╚═══════════════════════════════════════════════════════════════╝
"""
print(banner)
def print_stats(stats: dict, summary: dict) -> None:
"""
Вывод статистики выполнения
Args:
stats: Статистика выполнения
summary: Сводка по результатам
"""
print("\n" + "="*60)
print("📊 РЕЗУЛЬТАТЫ АНАЛИЗА")
print("="*60)
print(f"\n⏱️ Время выполнения: {stats['execution_time']:.1f} секунд")
print(f"\n✅ Успешно проанализировано: {stats['successful']} акций")
print(f"❌ Ошибок: {stats['failed']} акций")
if stats['errors']:
print(f"\n⚠️ Ошибки:")
for error in stats['errors'][:5]: # Показать первые 5
print(f" • {error['ticker']}: {error['error']}")
if len(stats['errors']) > 5:
print(f" ... и еще {len(stats['errors']) - 5}")
print(f"\n📈 Прогнозы:")
predictions = summary.get('predictions', {})
total = summary.get('total_stocks', 0)
if total > 0:
growing = predictions.get('РАСТЕТ', 0)
falling = predictions.get('ПАДАЕТ', 0)
stable = predictions.get('СТАБИЛЬНА', 0)
print(f" 🟢 Растут: {growing:3d} ({growing/total*100:5.1f}%)")
print(f" 🔴 Падают: {falling:3d} ({falling/total*100:5.1f}%)")
print(f" 🟡 Стабильны: {stable:3d} ({stable/total*100:5.1f}%)")
consensus_rate = summary.get('consensus_rate', 0)
print(f"\n🤝 Консенсус моделей: {consensus_rate:.1f}%")
print("\n" + "="*60)
async def main():
"""Главная функция"""
try:
# Баннер
print_banner()
# Загрузка конфигурации
print("🔧 Загрузка конфигурации...")
config = load_config()
# Настройка логирования
setup_logging(config)
logger = logging.getLogger(__name__)
logger.info("="*60)
logger.info("ЗАПУСК АНАЛИЗА КОТИРОВОК")
logger.info("="*60)
# Поиск Excel файла
excel_file = config.get('input', {}).get('excel_file', 'data/samples/Stock quotes.xlsx')
if not Path(excel_file).exists():
print(f"❌ Файл {excel_file} не найден!")
print(" Проверьте путь к файлу в config/llm_config.yaml (параметр input.excel_file)")
print(f" Или поместите файл по пути: {excel_file}")
return
# Инициализация компонентов
print("\n🔧 Инициализация компонентов...")
# OpenRouter клиент
try:
llm_client = OpenRouterClient(
api_key=config['openrouter']['api_key'],
base_url=config['openrouter']['base_url']
)
print(" ✅ OpenRouter клиент")
except ValueError as e:
print(f" ❌ {e}")
return
# База данных
db = Database(config['database']['path'])
print(f" ✅ База данных: {config['database']['path']}")
# Price Fetcher (v3.0)
price_fetcher = YahooFinanceFetcher()
print(" ✅ Yahoo Finance Fetcher")
# Загрузка данных (используется БД для получения котировок)
print(f"\n📂 Загрузка тикеров из {excel_file}...")
stocks = load_stock_data(excel_file, database=db, price_fetcher=price_fetcher, config=config)
if not stocks:
print("❌ Не удалось загрузить данные из файла!")
return
# Статистика загруженных данных
data_stats = DataLoader.validate_data(stocks)
print(f"✅ Загружено {data_stats['total']} акций")
print(f" • Растут: {data_stats['growing']}")
print(f" • Падают: {data_stats['falling']}")
print(f" • Стабильны: {data_stats['stable']}")
# Провайдер информации о компаниях
alphavantage_key = config['company_info'].get('alphavantage_api_key', '')
company_provider = CompanyInfoProvider(
cache_duration_days=config['company_info']['cache_duration_days'],
fallback_llm_client=llm_client if config['company_info']['fallback_to_llm'] else None,
alphavantage_api_key=alphavantage_key if alphavantage_key else None
)
print(" ✅ Провайдер информации о компаниях")
# Анализатор
analyzer = StockAnalyzer(
llm_client=llm_client,
database=db,
company_provider=company_provider,
config=config
)
print(" ✅ Анализатор")
# Запуск анализа
print(f"\n🚀 Запуск анализа {len(stocks)} акций...")
print(f" Модели: {', '.join([m['name'] for m in config['models']])}")
print()
analysis_date = date.today()
stats = await analyzer.analyze_stocks(stocks, analysis_date)
# Получение сводки
summary = analyzer.get_analysis_summary(analysis_date)
# Вывод статистики
print_stats(stats, summary)
# Экспорт в Excel
print("\n📄 Экспорт результатов в Excel...")
results = db.get_analysis_results(analysis_date=analysis_date)
exporter = ExcelExporter()
export_path = exporter.export(results, analysis_date)
print(f"✅ Отчет сохранен: {export_path}")
# Закрытие БД
db.close()
print("\n✨ Анализ завершен успешно!")
logger.info("Анализ завершен успешно")
except KeyboardInterrupt:
print("\n\n⚠️ Прервано пользователем")
logging.info("Прервано пользователем")
except Exception as e:
print(f"\n❌ Критическая ошибка: {e}")
logging.exception("Критическая ошибка")
raise
if __name__ == "__main__":
# Запуск асинхронной функции
asyncio.run(main())