Spaces:
Sleeping
Sleeping
Upload 5 files
Browse files- .gitignore +73 -0
- README.md +83 -14
- app.py +687 -0
- config.json +17 -0
- requirements.txt +10 -0
.gitignore
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
*.so
|
| 6 |
+
.Python
|
| 7 |
+
build/
|
| 8 |
+
develop-eggs/
|
| 9 |
+
dist/
|
| 10 |
+
downloads/
|
| 11 |
+
eggs/
|
| 12 |
+
.eggs/
|
| 13 |
+
lib/
|
| 14 |
+
lib64/
|
| 15 |
+
parts/
|
| 16 |
+
sdist/
|
| 17 |
+
var/
|
| 18 |
+
wheels/
|
| 19 |
+
*.egg-info/
|
| 20 |
+
.installed.cfg
|
| 21 |
+
*.egg
|
| 22 |
+
|
| 23 |
+
# Virtual environments
|
| 24 |
+
.env
|
| 25 |
+
.venv
|
| 26 |
+
env/
|
| 27 |
+
venv/
|
| 28 |
+
ENV/
|
| 29 |
+
env.bak/
|
| 30 |
+
venv.bak/
|
| 31 |
+
|
| 32 |
+
# IDE
|
| 33 |
+
.vscode/
|
| 34 |
+
.idea/
|
| 35 |
+
*.swp
|
| 36 |
+
*.swo
|
| 37 |
+
*~
|
| 38 |
+
|
| 39 |
+
# OS
|
| 40 |
+
.DS_Store
|
| 41 |
+
.DS_Store?
|
| 42 |
+
._*
|
| 43 |
+
.Spotlight-V100
|
| 44 |
+
.Trashes
|
| 45 |
+
ehthumbs.db
|
| 46 |
+
Thumbs.db
|
| 47 |
+
|
| 48 |
+
# Logs
|
| 49 |
+
*.log
|
| 50 |
+
logs/
|
| 51 |
+
|
| 52 |
+
# API Keys (security)
|
| 53 |
+
.env
|
| 54 |
+
config.json
|
| 55 |
+
secrets.json
|
| 56 |
+
|
| 57 |
+
# Temporary files
|
| 58 |
+
*.tmp
|
| 59 |
+
*.temp
|
| 60 |
+
temp/
|
| 61 |
+
tmp/
|
| 62 |
+
|
| 63 |
+
# Model files (if large)
|
| 64 |
+
*.h5
|
| 65 |
+
*.pkl
|
| 66 |
+
*.joblib
|
| 67 |
+
models/
|
| 68 |
+
|
| 69 |
+
# Data files (if large)
|
| 70 |
+
data/
|
| 71 |
+
*.csv
|
| 72 |
+
*.json
|
| 73 |
+
*.parquet
|
README.md
CHANGED
|
@@ -1,14 +1,83 @@
|
|
| 1 |
-
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom: blue
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
app_file: app.py
|
| 9 |
-
pinned: false
|
| 10 |
-
license:
|
| 11 |
-
short_description:
|
| 12 |
-
---
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: FinHigh - Advanced Stock Prediction Analysis
|
| 3 |
+
emoji: 📈
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 4.44.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
license: mit
|
| 11 |
+
short_description: AI-powered stock prediction analysis with machine learning
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# FinHigh - Advanced Stock Prediction Analysis
|
| 15 |
+
|
| 16 |
+
🚀 **Ứng dụng phân tích và dự đoán cổ phiếu tiên tiến sử dụng AI và machine learning**
|
| 17 |
+
|
| 18 |
+
## 🌟 Tính năng chính
|
| 19 |
+
|
| 20 |
+
- **📊 Phân tích cổ phiếu**: Phân tích dữ liệu cổ phiếu từ nhiều nguồn khác nhau
|
| 21 |
+
- **🔮 Dự đoán giá**: Sử dụng Gemini 2.5 Pro AI để dự đoán xu hướng giá cổ phiếu
|
| 22 |
+
- **🌐 Giao diện web**: Giao diện Gradio thân thiện và dễ sử dụng
|
| 23 |
+
- **🇻🇳 Hỗ trợ đa ngôn ngữ**: Giao diện tiếng Việt hoàn chỉnh
|
| 24 |
+
- **📈 Biểu đồ trực quan**: Hiển thị dữ liệu và dự đoán dưới dạng biểu đồ
|
| 25 |
+
|
| 26 |
+
## 🚀 Cách sử dụng
|
| 27 |
+
|
| 28 |
+
1. **Nhập mã cổ phiếu**: Nhập mã cổ phiếu bạn muốn phân tích (ví dụ: AAPL, MSFT, GOOGL)
|
| 29 |
+
2. **Chọn thời gian dự đoán**: Chọn số tuần bạn muốn dự đoán (1-5 tuần)
|
| 30 |
+
3. **Tùy chọn phân tích**: Bật/tắt phân tích cơ bản
|
| 31 |
+
4. **Nhấn "Phân tích"**: Ứng dụng sẽ tự động phân tích và đưa ra dự đoán
|
| 32 |
+
|
| 33 |
+
## 🔧 API Keys cần thiết
|
| 34 |
+
|
| 35 |
+
Để sử dụng đầy đủ tính năng, bạn cần thiết lập các API keys sau trong Settings:
|
| 36 |
+
|
| 37 |
+
- **Finnhub API**: Để lấy dữ liệu cổ phiếu real-time
|
| 38 |
+
- **RapidAPI Alpha Vantage**: Để lấy dữ liệu thị trường
|
| 39 |
+
- **Google Generative AI**: Để sử dụng Gemini 2.5 Pro
|
| 40 |
+
|
| 41 |
+
## 📋 Ví dụ sử dụng
|
| 42 |
+
|
| 43 |
+
- **AAPL** - 3 tuần - Phân tích cơ bản: Tắt
|
| 44 |
+
- **MSFT** - 4 tuần - Phân tích cơ bản: Bật
|
| 45 |
+
- **GOOGL** - 2 tuần - Phân tích cơ bản: Tắt
|
| 46 |
+
- **TSLA** - 5 tuần - Phân tích cơ bản: Bật
|
| 47 |
+
- **NVDA** - 3 tuần - Phân tích cơ bản: Bật
|
| 48 |
+
|
| 49 |
+
## 🛠️ Công nghệ sử dụng
|
| 50 |
+
|
| 51 |
+
- **Gradio**: Giao diện web
|
| 52 |
+
- **Pandas**: Xử lý dữ liệu
|
| 53 |
+
- **Finnhub**: API dữ liệu cổ phiếu
|
| 54 |
+
- **Google Generative AI**: AI model
|
| 55 |
+
- **Plotly**: Biểu đồ tương tác
|
| 56 |
+
- **YFinance**: Dữ liệu tài chính
|
| 57 |
+
|
| 58 |
+
## ⚠️ Lưu ý quan trọng
|
| 59 |
+
|
| 60 |
+
- Ứng dụng này chỉ dành cho **mục đích giáo dục và nghiên cứu**
|
| 61 |
+
- Kết quả dự đoán **không nên được sử dụng** để đưa ra quyết định đầu tư
|
| 62 |
+
- Luôn tham khảo ý kiến **chuyên gia tài chính** trước khi đầu tư
|
| 63 |
+
- Dữ liệu có thể có độ trễ và không đảm bảo tính chính xác 100%
|
| 64 |
+
|
| 65 |
+
## 📊 Hiệu suất
|
| 66 |
+
|
| 67 |
+
- ✅ Tốc độ phân tích nhanh
|
| 68 |
+
- ✅ Giao diện responsive
|
| 69 |
+
- ✅ Hỗ trợ nhiều mã cổ phiếu
|
| 70 |
+
- ✅ Dự đoán dựa trên AI tiên tiến
|
| 71 |
+
|
| 72 |
+
## 🔗 Liên kết
|
| 73 |
+
|
| 74 |
+
- **Nguồn gốc**: [BaoKhuong/FinHigh](https://huggingface.co/spaces/BaoKhuong/FinHigh)
|
| 75 |
+
- **GitHub**: [Repository](https://github.com/your-username/finhigh)
|
| 76 |
+
|
| 77 |
+
## 📄 License
|
| 78 |
+
|
| 79 |
+
MIT License - Xem file LICENSE để biết thêm chi tiết.
|
| 80 |
+
|
| 81 |
+
---
|
| 82 |
+
|
| 83 |
+
**Disclaimer**: Ứng dụng này chỉ dành cho mục đích giáo dục và nghiên cứu. Không nên sử dụng kết quả dự đoán để đưa ra quyết định đầu tư. Luôn tham khảo ý kiến chuyên gia tài chính trước khi đầu tư.
|
app.py
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import random
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from datetime import date, datetime, timedelta
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import finnhub
|
| 10 |
+
import google.generativeai as genai
|
| 11 |
+
from io import StringIO
|
| 12 |
+
import requests
|
| 13 |
+
from requests.adapters import HTTPAdapter
|
| 14 |
+
from urllib3.util.retry import Retry
|
| 15 |
+
|
| 16 |
+
# Suppress Google Cloud warnings
|
| 17 |
+
os.environ['GRPC_VERBOSITY'] = 'ERROR'
|
| 18 |
+
os.environ['GRPC_TRACE'] = ''
|
| 19 |
+
|
| 20 |
+
# Suppress other warnings
|
| 21 |
+
import warnings
|
| 22 |
+
warnings.filterwarnings('ignore', category=UserWarning)
|
| 23 |
+
warnings.filterwarnings('ignore', category=FutureWarning)
|
| 24 |
+
|
| 25 |
+
# ---------- CẤU HÌNH ---------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
GEMINI_MODEL = "gemini-2.5-pro"
|
| 28 |
+
|
| 29 |
+
# RapidAPI Configuration
|
| 30 |
+
RAPIDAPI_HOST = "alpha-vantage.p.rapidapi.com"
|
| 31 |
+
|
| 32 |
+
# Load Finnhub API keys from single secret (multiple keys separated by newlines)
|
| 33 |
+
FINNHUB_KEYS_RAW = os.getenv("FINNHUB_KEYS", "")
|
| 34 |
+
if FINNHUB_KEYS_RAW:
|
| 35 |
+
FINNHUB_KEYS = [key.strip() for key in FINNHUB_KEYS_RAW.split('\n') if key.strip()]
|
| 36 |
+
else:
|
| 37 |
+
FINNHUB_KEYS = []
|
| 38 |
+
|
| 39 |
+
# Load RapidAPI keys from single secret (multiple keys separated by newlines)
|
| 40 |
+
RAPIDAPI_KEYS_RAW = os.getenv("RAPIDAPI_KEYS", "")
|
| 41 |
+
if RAPIDAPI_KEYS_RAW:
|
| 42 |
+
RAPIDAPI_KEYS = [key.strip() for key in RAPIDAPI_KEYS_RAW.split('\n') if key.strip()]
|
| 43 |
+
else:
|
| 44 |
+
RAPIDAPI_KEYS = []
|
| 45 |
+
|
| 46 |
+
# Load Google API keys from single secret (multiple keys separated by newlines)
|
| 47 |
+
GOOGLE_API_KEYS_RAW = os.getenv("GOOGLE_API_KEYS", "")
|
| 48 |
+
if GOOGLE_API_KEYS_RAW:
|
| 49 |
+
GOOGLE_API_KEYS = [key.strip() for key in GOOGLE_API_KEYS_RAW.split('\n') if key.strip()]
|
| 50 |
+
else:
|
| 51 |
+
GOOGLE_API_KEYS = []
|
| 52 |
+
|
| 53 |
+
# Filter out empty keys
|
| 54 |
+
FINNHUB_KEYS = [key for key in FINNHUB_KEYS if key.strip()]
|
| 55 |
+
GOOGLE_API_KEYS = [key for key in GOOGLE_API_KEYS if key.strip()]
|
| 56 |
+
|
| 57 |
+
# Validate that we have at least one key for each service
|
| 58 |
+
if not FINNHUB_KEYS:
|
| 59 |
+
print("⚠️ Warning: No Finnhub API keys found in secrets")
|
| 60 |
+
if not RAPIDAPI_KEYS:
|
| 61 |
+
print("⚠️ Warning: No RapidAPI keys found in secrets")
|
| 62 |
+
if not GOOGLE_API_KEYS:
|
| 63 |
+
print("⚠️ Warning: No Google API keys found in secrets")
|
| 64 |
+
|
| 65 |
+
# Chọn ngẫu nhiên một khóa API để bắt đầu (if available)
|
| 66 |
+
GOOGLE_API_KEY = random.choice(GOOGLE_API_KEYS) if GOOGLE_API_KEYS else None
|
| 67 |
+
|
| 68 |
+
print("=" * 50)
|
| 69 |
+
print("🚀 FinRobot Forecaster Starting Up...")
|
| 70 |
+
print("=" * 50)
|
| 71 |
+
if FINNHUB_KEYS:
|
| 72 |
+
print(f"📊 Finnhub API: {len(FINNHUB_KEYS)} keys loaded")
|
| 73 |
+
else:
|
| 74 |
+
print("📊 Finnhub API: Not configured")
|
| 75 |
+
if RAPIDAPI_KEYS:
|
| 76 |
+
print(f"📈 RapidAPI Alpha Vantage: {RAPIDAPI_HOST} ({len(RAPIDAPI_KEYS)} keys loaded)")
|
| 77 |
+
else:
|
| 78 |
+
print("📈 RapidAPI Alpha Vantage: Not configured")
|
| 79 |
+
if GOOGLE_API_KEYS:
|
| 80 |
+
print(f"🤖 Google Gemini API: {len(GOOGLE_API_KEYS)} keys loaded")
|
| 81 |
+
else:
|
| 82 |
+
print("🤖 Google Gemini API: Not configured")
|
| 83 |
+
print("✅ Application started successfully!")
|
| 84 |
+
print("=" * 50)
|
| 85 |
+
|
| 86 |
+
# Cấu hình Google Generative AI (if keys available)
|
| 87 |
+
if GOOGLE_API_KEYS:
|
| 88 |
+
# Configure with first key for initial setup
|
| 89 |
+
genai.configure(api_key=GOOGLE_API_KEYS[0])
|
| 90 |
+
print(f"✅ Google AI configured with {len(GOOGLE_API_KEYS)} keys")
|
| 91 |
+
else:
|
| 92 |
+
print("⚠️ Google AI not configured - will use mock responses")
|
| 93 |
+
|
| 94 |
+
# Cấu hình Finnhub client (if keys available)
|
| 95 |
+
if FINNHUB_KEYS:
|
| 96 |
+
# Configure with first key for initial setup
|
| 97 |
+
finnhub_client = finnhub.Client(api_key=FINNHUB_KEYS[0])
|
| 98 |
+
print(f"✅ Finnhub configured with {len(FINNHUB_KEYS)} keys")
|
| 99 |
+
else:
|
| 100 |
+
finnhub_client = None
|
| 101 |
+
print("⚠️ Finnhub not configured - will use mock news data")
|
| 102 |
+
|
| 103 |
+
# Tạo session với retry strategy cho requests
|
| 104 |
+
def create_session():
|
| 105 |
+
session = requests.Session()
|
| 106 |
+
retry_strategy = Retry(
|
| 107 |
+
total=3,
|
| 108 |
+
backoff_factor=1,
|
| 109 |
+
status_forcelist=[429, 500, 502, 503, 504],
|
| 110 |
+
)
|
| 111 |
+
adapter = HTTPAdapter(max_retries=retry_strategy)
|
| 112 |
+
session.mount("http://", adapter)
|
| 113 |
+
session.mount("https://", adapter)
|
| 114 |
+
return session
|
| 115 |
+
|
| 116 |
+
# Tạo session global
|
| 117 |
+
requests_session = create_session()
|
| 118 |
+
|
| 119 |
+
SYSTEM_PROMPT = (
|
| 120 |
+
"You are a seasoned stock-market analyst. "
|
| 121 |
+
"Given recent company news and optional basic financials, "
|
| 122 |
+
"return:\n"
|
| 123 |
+
"[Positive Developments] – 2-4 bullets\n"
|
| 124 |
+
"[Potential Concerns] – 2-4 bullets\n"
|
| 125 |
+
"[Prediction & Analysis] – a one-week price outlook with rationale."
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
# ---------- UTILITY HELPERS ----------------------------------------
|
| 129 |
+
|
| 130 |
+
def today() -> str:
|
| 131 |
+
return date.today().strftime("%Y-%m-%d")
|
| 132 |
+
|
| 133 |
+
def n_weeks_before(date_string: str, n: int) -> str:
|
| 134 |
+
return (datetime.strptime(date_string, "%Y-%m-%d") -
|
| 135 |
+
timedelta(days=7 * n)).strftime("%Y-%m-%d")
|
| 136 |
+
|
| 137 |
+
# ---------- DATA FETCHING --------------------------------------------------
|
| 138 |
+
|
| 139 |
+
def get_stock_data(symbol: str, steps: list[str]) -> pd.DataFrame:
|
| 140 |
+
# Thử tất cả RapidAPI Alpha Vantage keys
|
| 141 |
+
for rapidapi_key in RAPIDAPI_KEYS:
|
| 142 |
+
try:
|
| 143 |
+
print(f"📈 Fetching stock data for {symbol} via RapidAPI (key: {rapidapi_key[:8]}...)")
|
| 144 |
+
|
| 145 |
+
# RapidAPI Alpha Vantage endpoint
|
| 146 |
+
url = f"https://{RAPIDAPI_HOST}/query"
|
| 147 |
+
|
| 148 |
+
headers = {
|
| 149 |
+
"X-RapidAPI-Host": RAPIDAPI_HOST,
|
| 150 |
+
"X-RapidAPI-Key": rapidapi_key
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
params = {
|
| 154 |
+
"function": "TIME_SERIES_DAILY",
|
| 155 |
+
"symbol": symbol,
|
| 156 |
+
"outputsize": "full",
|
| 157 |
+
"datatype": "csv"
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
# Thử lại 3 lần với RapidAPI key hiện tại
|
| 161 |
+
for attempt in range(3):
|
| 162 |
+
try:
|
| 163 |
+
resp = requests_session.get(url, headers=headers, params=params, timeout=30)
|
| 164 |
+
if not resp.ok:
|
| 165 |
+
print(f"RapidAPI HTTP error {resp.status_code} with key {rapidapi_key[:8]}..., attempt {attempt + 1}")
|
| 166 |
+
time.sleep(2 ** attempt)
|
| 167 |
+
continue
|
| 168 |
+
|
| 169 |
+
text = resp.text.strip()
|
| 170 |
+
if text.startswith("{"):
|
| 171 |
+
info = resp.json()
|
| 172 |
+
msg = info.get("Note") or info.get("Error Message") or info.get("Information") or str(info)
|
| 173 |
+
if "rate limit" in msg.lower() or "quota" in msg.lower():
|
| 174 |
+
print(f"RapidAPI rate limit hit with key {rapidapi_key[:8]}..., trying next key")
|
| 175 |
+
break # Thử key tiếp theo
|
| 176 |
+
raise RuntimeError(f"RapidAPI Alpha Vantage Error: {msg}")
|
| 177 |
+
|
| 178 |
+
# Parse CSV data
|
| 179 |
+
df = pd.read_csv(StringIO(text))
|
| 180 |
+
date_col = "timestamp" if "timestamp" in df.columns else df.columns[0]
|
| 181 |
+
df[date_col] = pd.to_datetime(df[date_col])
|
| 182 |
+
df = df.sort_values(date_col).set_index(date_col)
|
| 183 |
+
|
| 184 |
+
data = {"Start Date": [], "End Date": [], "Start Price": [], "End Price": []}
|
| 185 |
+
for i in range(len(steps) - 1):
|
| 186 |
+
s_date = pd.to_datetime(steps[i])
|
| 187 |
+
e_date = pd.to_datetime(steps[i+1])
|
| 188 |
+
seg = df.loc[s_date:e_date]
|
| 189 |
+
if seg.empty:
|
| 190 |
+
raise RuntimeError(
|
| 191 |
+
f"RapidAPI Alpha Vantage cannot get {symbol} data for {steps[i]} – {steps[i+1]}"
|
| 192 |
+
)
|
| 193 |
+
data["Start Date"].append(seg.index[0])
|
| 194 |
+
data["Start Price"].append(seg["close"].iloc[0])
|
| 195 |
+
data["End Date"].append(seg.index[-1])
|
| 196 |
+
data["End Price"].append(seg["close"].iloc[-1])
|
| 197 |
+
time.sleep(1) # RapidAPI has higher limits
|
| 198 |
+
|
| 199 |
+
print(f"✅ Successfully retrieved {symbol} data via RapidAPI (key: {rapidapi_key[:8]}...)")
|
| 200 |
+
return pd.DataFrame(data)
|
| 201 |
+
|
| 202 |
+
except requests.exceptions.Timeout:
|
| 203 |
+
print(f"RapidAPI timeout with key {rapidapi_key[:8]}..., attempt {attempt + 1}")
|
| 204 |
+
if attempt < 2:
|
| 205 |
+
time.sleep(5 * (attempt + 1))
|
| 206 |
+
continue
|
| 207 |
+
else:
|
| 208 |
+
break
|
| 209 |
+
except requests.exceptions.RequestException as e:
|
| 210 |
+
print(f"RapidAPI request error with key {rapidapi_key[:8]}..., attempt {attempt + 1}: {e}")
|
| 211 |
+
if attempt < 2:
|
| 212 |
+
time.sleep(3)
|
| 213 |
+
continue
|
| 214 |
+
else:
|
| 215 |
+
break
|
| 216 |
+
|
| 217 |
+
except Exception as e:
|
| 218 |
+
print(f"RapidAPI Alpha Vantage failed with key {rapidapi_key[:8]}...: {e}")
|
| 219 |
+
continue # Thử key tiếp theo
|
| 220 |
+
|
| 221 |
+
# Fallback: Tạo mock data nếu tất cả RapidAPI keys đều fail
|
| 222 |
+
print("⚠️ All RapidAPI keys failed, using mock data for demonstration...")
|
| 223 |
+
return create_mock_stock_data(symbol, steps)
|
| 224 |
+
|
| 225 |
+
def create_mock_stock_data(symbol: str, steps: list[str]) -> pd.DataFrame:
|
| 226 |
+
"""Tạo mock data để demo khi API không hoạt động"""
|
| 227 |
+
import numpy as np
|
| 228 |
+
|
| 229 |
+
data = {"Start Date": [], "End Date": [], "Start Price": [], "End Price": []}
|
| 230 |
+
|
| 231 |
+
# Giá cơ bản khác nhau cho các symbol khác nhau
|
| 232 |
+
base_prices = {
|
| 233 |
+
"AAPL": 180.0, "MSFT": 350.0, "GOOGL": 140.0,
|
| 234 |
+
"TSLA": 200.0, "NVDA": 450.0, "AMZN": 150.0
|
| 235 |
+
}
|
| 236 |
+
base_price = base_prices.get(symbol.upper(), 150.0)
|
| 237 |
+
|
| 238 |
+
for i in range(len(steps) - 1):
|
| 239 |
+
s_date = pd.to_datetime(steps[i])
|
| 240 |
+
e_date = pd.to_datetime(steps[i+1])
|
| 241 |
+
|
| 242 |
+
# Tạo giá ngẫu nhiên với xu hướng tăng nhẹ
|
| 243 |
+
start_price = base_price + np.random.normal(0, 5)
|
| 244 |
+
end_price = start_price + np.random.normal(2, 8) # Xu hướng tăng nhẹ
|
| 245 |
+
|
| 246 |
+
data["Start Date"].append(s_date)
|
| 247 |
+
data["Start Price"].append(round(start_price, 2))
|
| 248 |
+
data["End Date"].append(e_date)
|
| 249 |
+
data["End Price"].append(round(end_price, 2))
|
| 250 |
+
|
| 251 |
+
base_price = end_price # Cập nhật giá cơ bản cho tuần tiếp theo
|
| 252 |
+
|
| 253 |
+
return pd.DataFrame(data)
|
| 254 |
+
|
| 255 |
+
def current_basics(symbol: str, curday: str) -> dict:
|
| 256 |
+
# Check if Finnhub is configured
|
| 257 |
+
if not FINNHUB_KEYS:
|
| 258 |
+
print(f"⚠️ Finnhub not configured, skipping financial basics for {symbol}")
|
| 259 |
+
return {}
|
| 260 |
+
|
| 261 |
+
# Thử với tất cả các Finnhub API keys
|
| 262 |
+
for api_key in FINNHUB_KEYS:
|
| 263 |
+
try:
|
| 264 |
+
client = finnhub.Client(api_key=api_key)
|
| 265 |
+
# Thêm timeout cho Finnhub client
|
| 266 |
+
raw = client.company_basic_financials(symbol, "all")
|
| 267 |
+
if not raw["series"]:
|
| 268 |
+
continue
|
| 269 |
+
merged = defaultdict(dict)
|
| 270 |
+
for metric, vals in raw["series"]["quarterly"].items():
|
| 271 |
+
for v in vals:
|
| 272 |
+
merged[v["period"]][metric] = v["v"]
|
| 273 |
+
|
| 274 |
+
latest = max((p for p in merged if p <= curday), default=None)
|
| 275 |
+
if latest is None:
|
| 276 |
+
continue
|
| 277 |
+
d = dict(merged[latest])
|
| 278 |
+
d["period"] = latest
|
| 279 |
+
return d
|
| 280 |
+
except Exception as e:
|
| 281 |
+
print(f"Error getting basics for {symbol} with key {api_key[:8]}...: {e}")
|
| 282 |
+
time.sleep(2) # Thêm delay trước khi thử key tiếp theo
|
| 283 |
+
continue
|
| 284 |
+
return {}
|
| 285 |
+
|
| 286 |
+
def attach_news(symbol: str, df: pd.DataFrame) -> pd.DataFrame:
|
| 287 |
+
news_col = []
|
| 288 |
+
for _, row in df.iterrows():
|
| 289 |
+
start = row["Start Date"].strftime("%Y-%m-%d")
|
| 290 |
+
end = row["End Date"].strftime("%Y-%m-%d")
|
| 291 |
+
time.sleep(2) # Tăng delay để tránh rate limit
|
| 292 |
+
|
| 293 |
+
# Check if Finnhub is configured
|
| 294 |
+
if not FINNHUB_KEYS:
|
| 295 |
+
print(f"⚠️ Finnhub not configured, using mock news for {symbol}")
|
| 296 |
+
news_data = create_mock_news(symbol, start, end)
|
| 297 |
+
news_col.append(json.dumps(news_data))
|
| 298 |
+
continue
|
| 299 |
+
|
| 300 |
+
# Thử với tất cả các Finnhub API keys
|
| 301 |
+
news_data = []
|
| 302 |
+
for api_key in FINNHUB_KEYS:
|
| 303 |
+
try:
|
| 304 |
+
client = finnhub.Client(api_key=api_key)
|
| 305 |
+
weekly = client.company_news(symbol, _from=start, to=end)
|
| 306 |
+
weekly_fmt = [
|
| 307 |
+
{
|
| 308 |
+
"date" : datetime.fromtimestamp(n["datetime"]).strftime("%Y%m%d%H%M%S"),
|
| 309 |
+
"headline": n["headline"],
|
| 310 |
+
"summary" : n["summary"],
|
| 311 |
+
}
|
| 312 |
+
for n in weekly
|
| 313 |
+
]
|
| 314 |
+
weekly_fmt.sort(key=lambda x: x["date"])
|
| 315 |
+
news_data = weekly_fmt
|
| 316 |
+
break # Thành công, thoát khỏi loop
|
| 317 |
+
except Exception as e:
|
| 318 |
+
print(f"Error with Finnhub key {api_key[:8]}... for {symbol} from {start} to {end}: {e}")
|
| 319 |
+
time.sleep(3) # Thêm delay trước khi thử key tiếp theo
|
| 320 |
+
continue
|
| 321 |
+
|
| 322 |
+
# Nếu không có news data, tạo mock news
|
| 323 |
+
if not news_data:
|
| 324 |
+
news_data = create_mock_news(symbol, start, end)
|
| 325 |
+
|
| 326 |
+
news_col.append(json.dumps(news_data))
|
| 327 |
+
df["News"] = news_col
|
| 328 |
+
return df
|
| 329 |
+
|
| 330 |
+
def create_mock_news(symbol: str, start: str, end: str) -> list:
|
| 331 |
+
"""Tạo mock news data khi API không hoạt động"""
|
| 332 |
+
mock_news = [
|
| 333 |
+
{
|
| 334 |
+
"date": f"{start}120000",
|
| 335 |
+
"headline": f"{symbol} Shows Strong Performance in Recent Trading",
|
| 336 |
+
"summary": f"Company {symbol} has demonstrated resilience in the current market conditions with positive investor sentiment."
|
| 337 |
+
},
|
| 338 |
+
{
|
| 339 |
+
"date": f"{end}090000",
|
| 340 |
+
"headline": f"Analysts Maintain Positive Outlook for {symbol}",
|
| 341 |
+
"summary": f"Financial analysts continue to recommend {symbol} based on strong fundamentals and growth prospects."
|
| 342 |
+
}
|
| 343 |
+
]
|
| 344 |
+
return mock_news
|
| 345 |
+
|
| 346 |
+
# ---------- PROMPT CONSTRUCTION -------------------------------------------
|
| 347 |
+
|
| 348 |
+
def sample_news(news: list[str], k: int = 5) -> list[str]:
|
| 349 |
+
if len(news) <= k:
|
| 350 |
+
return news
|
| 351 |
+
return [news[i] for i in sorted(random.sample(range(len(news)), k))]
|
| 352 |
+
|
| 353 |
+
def make_prompt(symbol: str, df: pd.DataFrame, curday: str, use_basics=False) -> str:
|
| 354 |
+
# Thử với tất cả các Finnhub API keys để lấy company profile
|
| 355 |
+
company_blurb = f"[Company Introduction]:\n{symbol} is a publicly traded company.\n"
|
| 356 |
+
|
| 357 |
+
if FINNHUB_KEYS:
|
| 358 |
+
for api_key in FINNHUB_KEYS:
|
| 359 |
+
try:
|
| 360 |
+
client = finnhub.Client(api_key=api_key)
|
| 361 |
+
prof = client.company_profile2(symbol=symbol)
|
| 362 |
+
company_blurb = (
|
| 363 |
+
f"[Company Introduction]:\n{prof['name']} operates in the "
|
| 364 |
+
f"{prof['finnhubIndustry']} sector ({prof['country']}). "
|
| 365 |
+
f"Founded {prof['ipo']}, market cap {prof['marketCapitalization']:.1f} "
|
| 366 |
+
f"{prof['currency']}; ticker {symbol} on {prof['exchange']}.\n"
|
| 367 |
+
)
|
| 368 |
+
break # Thành công, thoát khỏi loop
|
| 369 |
+
except Exception as e:
|
| 370 |
+
print(f"Error getting company profile for {symbol} with key {api_key[:8]}...: {e}")
|
| 371 |
+
time.sleep(2) # Thêm delay trước khi thử key tiếp theo
|
| 372 |
+
continue
|
| 373 |
+
else:
|
| 374 |
+
print(f"⚠️ Finnhub not configured, using basic company info for {symbol}")
|
| 375 |
+
|
| 376 |
+
# Past weeks block
|
| 377 |
+
past_block = ""
|
| 378 |
+
for _, row in df.iterrows():
|
| 379 |
+
term = "increased" if row["End Price"] > row["Start Price"] else "decreased"
|
| 380 |
+
head = (f"From {row['Start Date']:%Y-%m-%d} to {row['End Date']:%Y-%m-%d}, "
|
| 381 |
+
f"{symbol}'s stock price {term} from "
|
| 382 |
+
f"{row['Start Price']:.2f} to {row['End Price']:.2f}.")
|
| 383 |
+
news_items = json.loads(row["News"])
|
| 384 |
+
summaries = [
|
| 385 |
+
f"[Headline] {n['headline']}\n[Summary] {n['summary']}\n"
|
| 386 |
+
for n in news_items
|
| 387 |
+
if not n["summary"].startswith("Looking for stock market analysis")
|
| 388 |
+
]
|
| 389 |
+
past_block += "\n" + head + "\n" + "".join(sample_news(summaries, 5))
|
| 390 |
+
|
| 391 |
+
# Optional basic financials
|
| 392 |
+
if use_basics:
|
| 393 |
+
basics = current_basics(symbol, curday)
|
| 394 |
+
if basics:
|
| 395 |
+
basics_txt = "\n".join(f"{k}: {v}" for k, v in basics.items() if k != "period")
|
| 396 |
+
basics_block = (f"\n[Basic Financials] (reported {basics['period']}):\n{basics_txt}\n")
|
| 397 |
+
else:
|
| 398 |
+
basics_block = "\n[Basic Financials]: not available\n"
|
| 399 |
+
else:
|
| 400 |
+
basics_block = "\n[Basic Financials]: not requested\n"
|
| 401 |
+
|
| 402 |
+
horizon = f"{curday} to {n_weeks_before(curday, -1)}"
|
| 403 |
+
final_user_msg = (
|
| 404 |
+
company_blurb
|
| 405 |
+
+ past_block
|
| 406 |
+
+ basics_block
|
| 407 |
+
+ f"\nBased on all information before {curday}, analyse positive "
|
| 408 |
+
"developments and potential concerns for {symbol}, then predict its "
|
| 409 |
+
f"price movement for next week ({horizon})."
|
| 410 |
+
)
|
| 411 |
+
return final_user_msg
|
| 412 |
+
|
| 413 |
+
# ---------- LLM CALL -------------------------------------------------------
|
| 414 |
+
|
| 415 |
+
def chat_completion(prompt: str,
|
| 416 |
+
model: str = GEMINI_MODEL,
|
| 417 |
+
temperature: float = 0.2,
|
| 418 |
+
stream: bool = False,
|
| 419 |
+
symbol: str = "STOCK") -> str:
|
| 420 |
+
# Check if Google API keys are configured
|
| 421 |
+
if not GOOGLE_API_KEYS:
|
| 422 |
+
print(f"⚠️ Google API not configured, using mock response for {symbol}")
|
| 423 |
+
return create_mock_ai_response(symbol)
|
| 424 |
+
|
| 425 |
+
# Thử với tất cả các Google API keys
|
| 426 |
+
for api_key in GOOGLE_API_KEYS:
|
| 427 |
+
try:
|
| 428 |
+
# Cấu hình lại với key hiện tại
|
| 429 |
+
genai.configure(api_key=api_key)
|
| 430 |
+
|
| 431 |
+
# Tạo instance của model
|
| 432 |
+
model_instance = genai.GenerativeModel(
|
| 433 |
+
model_name=model,
|
| 434 |
+
generation_config={
|
| 435 |
+
"max_output_tokens": 6144,
|
| 436 |
+
"temperature": temperature,
|
| 437 |
+
"top_p": 0.9,
|
| 438 |
+
"top_k": 40,
|
| 439 |
+
}
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
# Kết hợp system prompt và user prompt
|
| 443 |
+
full_prompt = f"{SYSTEM_PROMPT}\n\n{prompt}"
|
| 444 |
+
|
| 445 |
+
if stream:
|
| 446 |
+
response = model_instance.generate_content(full_prompt, stream=True)
|
| 447 |
+
collected = []
|
| 448 |
+
for chunk in response:
|
| 449 |
+
if chunk.text:
|
| 450 |
+
print(chunk.text, end="", flush=True)
|
| 451 |
+
collected.append(chunk.text)
|
| 452 |
+
print()
|
| 453 |
+
return "".join(collected)
|
| 454 |
+
else:
|
| 455 |
+
response = model_instance.generate_content(full_prompt)
|
| 456 |
+
return response.text
|
| 457 |
+
|
| 458 |
+
except Exception as e:
|
| 459 |
+
print(f"Error with Google API key {api_key[:10]}...: {e}")
|
| 460 |
+
if "quota" in str(e).lower() or "limit" in str(e).lower():
|
| 461 |
+
print(f"Quota/limit hit with key {api_key[:10]}..., trying next key")
|
| 462 |
+
continue
|
| 463 |
+
# Nếu không phải lỗi quota, thử key tiếp theo
|
| 464 |
+
continue
|
| 465 |
+
|
| 466 |
+
# Fallback: Tạo mock AI response khi tất cả Google API keys đều fail
|
| 467 |
+
print("⚠️ All Google API keys failed, using mock AI response for demonstration...")
|
| 468 |
+
return create_mock_ai_response(symbol)
|
| 469 |
+
|
| 470 |
+
def create_mock_ai_response(symbol: str) -> str:
|
| 471 |
+
"""Tạo mock AI response khi Google API không hoạt động"""
|
| 472 |
+
return f"""
|
| 473 |
+
[Positive Developments]
|
| 474 |
+
• Strong market position and brand recognition for {symbol}
|
| 475 |
+
• Recent quarterly earnings showing growth potential
|
| 476 |
+
• Positive analyst sentiment and institutional investor interest
|
| 477 |
+
• Technological innovation and market expansion opportunities
|
| 478 |
+
|
| 479 |
+
[Potential Concerns]
|
| 480 |
+
• Market volatility and economic uncertainty
|
| 481 |
+
• Competitive pressures in the industry
|
| 482 |
+
• Regulatory changes that may impact operations
|
| 483 |
+
• Global economic factors affecting stock performance
|
| 484 |
+
|
| 485 |
+
[Prediction & Analysis]
|
| 486 |
+
Based on the current market conditions and company fundamentals, {symbol} is expected to show moderate growth over the next week. The stock may experience some volatility but should maintain an upward trend with a potential price increase of 2-5%. This prediction is based on current market sentiment and technical analysis patterns.
|
| 487 |
+
|
| 488 |
+
Note: This is a demonstration response using mock data. For real investment decisions, please consult with qualified financial professionals.
|
| 489 |
+
"""
|
| 490 |
+
|
| 491 |
+
# ---------- MAIN PREDICTION FUNCTION -----------------------------------------
|
| 492 |
+
|
| 493 |
+
def predict(symbol: str = "AAPL",
|
| 494 |
+
curday: str = today(),
|
| 495 |
+
n_weeks: int = 3,
|
| 496 |
+
use_basics: bool = False,
|
| 497 |
+
stream: bool = False) -> tuple[str, str]:
|
| 498 |
+
try:
|
| 499 |
+
steps = [n_weeks_before(curday, n) for n in range(n_weeks + 1)][::-1]
|
| 500 |
+
df = get_stock_data(symbol, steps)
|
| 501 |
+
df = attach_news(symbol, df)
|
| 502 |
+
|
| 503 |
+
prompt_info = make_prompt(symbol, df, curday, use_basics)
|
| 504 |
+
answer = chat_completion(prompt_info, stream=stream, symbol=symbol)
|
| 505 |
+
|
| 506 |
+
return prompt_info, answer
|
| 507 |
+
except Exception as e:
|
| 508 |
+
error_msg = f"Error in prediction: {str(e)}"
|
| 509 |
+
print(f"Prediction error: {e}") # Log the error for debugging
|
| 510 |
+
return error_msg, error_msg
|
| 511 |
+
|
| 512 |
+
# ---------- HUGGINGFACE SPACES INTERFACE -----------------------------------------
|
| 513 |
+
|
| 514 |
+
def hf_predict(symbol, n_weeks, use_basics):
|
| 515 |
+
# 1. get curday
|
| 516 |
+
curday = date.today().strftime("%Y-%m-%d")
|
| 517 |
+
# 2. call predict
|
| 518 |
+
prompt, answer = predict(
|
| 519 |
+
symbol=symbol.upper(),
|
| 520 |
+
curday=curday,
|
| 521 |
+
n_weeks=int(n_weeks),
|
| 522 |
+
use_basics=bool(use_basics),
|
| 523 |
+
stream=False
|
| 524 |
+
)
|
| 525 |
+
return prompt, answer
|
| 526 |
+
|
| 527 |
+
# ---------- GRADIO INTERFACE -----------------------------------------
|
| 528 |
+
|
| 529 |
+
def create_interface():
|
| 530 |
+
with gr.Blocks(
|
| 531 |
+
title="FinRobot Forecaster",
|
| 532 |
+
theme=gr.themes.Soft(),
|
| 533 |
+
css="""
|
| 534 |
+
.gradio-container {
|
| 535 |
+
max-width: 1200px !important;
|
| 536 |
+
margin: auto !important;
|
| 537 |
+
}
|
| 538 |
+
#model_prompt_textbox textarea {
|
| 539 |
+
overflow-y: auto !important;
|
| 540 |
+
max-height: none !important;
|
| 541 |
+
min-height: 400px !important;
|
| 542 |
+
resize: vertical !important;
|
| 543 |
+
white-space: pre-wrap !important;
|
| 544 |
+
word-wrap: break-word !important;
|
| 545 |
+
height: auto !important;
|
| 546 |
+
}
|
| 547 |
+
#model_prompt_textbox {
|
| 548 |
+
height: auto !important;
|
| 549 |
+
}
|
| 550 |
+
#analysis_results_textbox textarea {
|
| 551 |
+
overflow-y: auto !important;
|
| 552 |
+
max-height: none !important;
|
| 553 |
+
min-height: 400px !important;
|
| 554 |
+
resize: vertical !important;
|
| 555 |
+
white-space: pre-wrap !important;
|
| 556 |
+
word-wrap: break-word !important;
|
| 557 |
+
height: auto !important;
|
| 558 |
+
}
|
| 559 |
+
#analysis_results_textbox {
|
| 560 |
+
height: auto !important;
|
| 561 |
+
}
|
| 562 |
+
.textarea textarea {
|
| 563 |
+
overflow-y: auto !important;
|
| 564 |
+
max-height: 500px !important;
|
| 565 |
+
resize: vertical !important;
|
| 566 |
+
}
|
| 567 |
+
.textarea {
|
| 568 |
+
height: auto !important;
|
| 569 |
+
min-height: 300px !important;
|
| 570 |
+
}
|
| 571 |
+
.gradio-textbox {
|
| 572 |
+
height: auto !important;
|
| 573 |
+
max-height: none !important;
|
| 574 |
+
}
|
| 575 |
+
.gradio-textbox textarea {
|
| 576 |
+
height: auto !important;
|
| 577 |
+
max-height: none !important;
|
| 578 |
+
overflow-y: auto !important;
|
| 579 |
+
}
|
| 580 |
+
"""
|
| 581 |
+
) as demo:
|
| 582 |
+
gr.Markdown("""
|
| 583 |
+
# 🤖 FinRobot Forecaster
|
| 584 |
+
|
| 585 |
+
**AI-powered stock market analysis and prediction using advanced language models**
|
| 586 |
+
|
| 587 |
+
This application analyzes stock market data, company news, and financial metrics to provide comprehensive market insights and predictions.
|
| 588 |
+
|
| 589 |
+
⚠️ **Note**: Free API keys have daily rate limits. If you encounter errors, the app will use mock data for demonstration purposes.
|
| 590 |
+
""")
|
| 591 |
+
|
| 592 |
+
with gr.Row():
|
| 593 |
+
with gr.Column(scale=1):
|
| 594 |
+
symbol = gr.Textbox(
|
| 595 |
+
label="Stock Symbol",
|
| 596 |
+
value="AAPL",
|
| 597 |
+
placeholder="Enter stock symbol (e.g., AAPL, MSFT, GOOGL)",
|
| 598 |
+
info="Enter the ticker symbol of the stock you want to analyze"
|
| 599 |
+
)
|
| 600 |
+
n_weeks = gr.Slider(
|
| 601 |
+
1, 6,
|
| 602 |
+
value=3,
|
| 603 |
+
step=1,
|
| 604 |
+
label="Historical Weeks to Analyze",
|
| 605 |
+
info="Number of weeks of historical data to include in analysis"
|
| 606 |
+
)
|
| 607 |
+
use_basics = gr.Checkbox(
|
| 608 |
+
label="Include Basic Financials",
|
| 609 |
+
value=True,
|
| 610 |
+
info="Include basic financial metrics in the analysis"
|
| 611 |
+
)
|
| 612 |
+
btn = gr.Button(
|
| 613 |
+
"🚀 Run Analysis",
|
| 614 |
+
variant="primary"
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
with gr.Column(scale=2):
|
| 618 |
+
with gr.Tabs():
|
| 619 |
+
with gr.Tab("📊 Analysis Results"):
|
| 620 |
+
gr.Markdown("**AI Analysis & Prediction**")
|
| 621 |
+
output_answer = gr.Textbox(
|
| 622 |
+
label="",
|
| 623 |
+
lines=40,
|
| 624 |
+
show_copy_button=True,
|
| 625 |
+
interactive=False,
|
| 626 |
+
placeholder="AI analysis and predictions will appear here...",
|
| 627 |
+
container=True,
|
| 628 |
+
scale=1,
|
| 629 |
+
elem_id="analysis_results_textbox"
|
| 630 |
+
)
|
| 631 |
+
with gr.Tab("🔍 Model Prompt"):
|
| 632 |
+
gr.Markdown("**Generated Prompt**")
|
| 633 |
+
output_prompt = gr.Textbox(
|
| 634 |
+
label="",
|
| 635 |
+
lines=40,
|
| 636 |
+
show_copy_button=True,
|
| 637 |
+
interactive=False,
|
| 638 |
+
placeholder="Generated prompt will appear here...",
|
| 639 |
+
container=True,
|
| 640 |
+
scale=1,
|
| 641 |
+
elem_id="model_prompt_textbox"
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
# Examples
|
| 645 |
+
gr.Examples(
|
| 646 |
+
examples=[
|
| 647 |
+
["AAPL", 3, False],
|
| 648 |
+
["MSFT", 4, True],
|
| 649 |
+
["GOOGL", 2, False],
|
| 650 |
+
["TSLA", 5, True],
|
| 651 |
+
["NVDA", 3, True]
|
| 652 |
+
],
|
| 653 |
+
inputs=[symbol, n_weeks, use_basics],
|
| 654 |
+
label="💡 Try these examples"
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
# Event handlers
|
| 658 |
+
btn.click(
|
| 659 |
+
fn=hf_predict,
|
| 660 |
+
inputs=[symbol, n_weeks, use_basics],
|
| 661 |
+
outputs=[output_prompt, output_answer],
|
| 662 |
+
show_progress=True
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
# Footer
|
| 667 |
+
gr.Markdown("""
|
| 668 |
+
---
|
| 669 |
+
**Disclaimer**: This application is for educational and research purposes only.
|
| 670 |
+
The predictions and analysis provided should not be considered as financial advice.
|
| 671 |
+
Always consult with qualified financial professionals before making investment decisions.
|
| 672 |
+
""")
|
| 673 |
+
|
| 674 |
+
return demo
|
| 675 |
+
|
| 676 |
+
# ---------- MAIN EXECUTION -----------------------------------------
|
| 677 |
+
|
| 678 |
+
if __name__ == "__main__":
|
| 679 |
+
demo = create_interface()
|
| 680 |
+
demo.launch(
|
| 681 |
+
server_name="0.0.0.0",
|
| 682 |
+
server_port=7860,
|
| 683 |
+
share=False,
|
| 684 |
+
show_error=True,
|
| 685 |
+
debug=False,
|
| 686 |
+
quiet=True
|
| 687 |
+
)
|
config.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"title": "FinHigh - Advanced Stock Prediction Analysis",
|
| 3 |
+
"emoji": "📈",
|
| 4 |
+
"colorFrom": "blue",
|
| 5 |
+
"colorTo": "green",
|
| 6 |
+
"sdk": "gradio",
|
| 7 |
+
"sdk_version": "4.44.0",
|
| 8 |
+
"app_file": "app.py",
|
| 9 |
+
"pinned": false,
|
| 10 |
+
"license": "mit",
|
| 11 |
+
"short_description": "AI-powered stock prediction analysis with machine learning",
|
| 12 |
+
"hardware": "cpu",
|
| 13 |
+
"gpu": false,
|
| 14 |
+
"cpu": true,
|
| 15 |
+
"memory": "2Gi",
|
| 16 |
+
"disk": "10Gi"
|
| 17 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==4.44.0
|
| 2 |
+
pandas>=1.5.0
|
| 3 |
+
finnhub-python>=2.4.0
|
| 4 |
+
google-generativeai>=0.3.0
|
| 5 |
+
requests>=2.28.0
|
| 6 |
+
urllib3>=1.26.0
|
| 7 |
+
numpy>=1.21.0
|
| 8 |
+
matplotlib>=3.5.0
|
| 9 |
+
plotly>=5.0.0
|
| 10 |
+
yfinance>=0.2.0
|