aifinancegen / start.py
mset's picture
Update start.py
a3fcc9a verified
#!/usr/bin/env python3
"""
Script di setup per l'ambiente Financial Transformer
"""
import subprocess
import sys
import os
import platform
def run_command(command, description=""):
"""Esegue un comando e gestisce gli errori"""
print(f"πŸ“¦ {description}")
try:
result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
print(f"βœ… {description} - Completato")
return True
except subprocess.CalledProcessError as e:
print(f"❌ {description} - Errore:")
print(f" {e.stderr}")
return False
def check_python_version():
"""Verifica la versione di Python"""
version = sys.version_info
print(f"🐍 Python version: {version.major}.{version.minor}.{version.micro}")
if version.major < 3 or (version.major == 3 and version.minor < 8):
print("❌ Python 3.8+ richiesto")
return False
print("βœ… Versione Python compatibile")
return True
def detect_system():
"""Rileva il sistema operativo"""
system = platform.system().lower()
print(f"πŸ’» Sistema operativo: {system}")
return system
def install_torch_optimized():
"""Installa PyTorch con ottimizzazioni per il sistema"""
system = detect_system()
if system == "linux":
# Prova CUDA se disponibile
if run_command("nvidia-smi", "Verifica CUDA"):
print("πŸš€ CUDA rilevato, installando PyTorch con supporto GPU")
return run_command(
"pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118",
"Installazione PyTorch con CUDA"
)
else:
print("πŸ’» CPU only, installando PyTorch CPU")
return run_command(
"pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu",
"Installazione PyTorch CPU"
)
elif system == "darwin": # macOS
print("🍎 macOS rilevato, installando PyTorch")
return run_command(
"pip install torch torchvision torchaudio",
"Installazione PyTorch per macOS"
)
else: # Windows e altri
print("πŸͺŸ Sistema generico, installando PyTorch")
return run_command(
"pip install torch torchvision torchaudio",
"Installazione PyTorch generico"
)
def create_virtual_environment():
"""Crea un ambiente virtuale"""
venv_name = "financial_transformer_env"
if not os.path.exists(venv_name):
print(f"πŸ—οΈ Creando ambiente virtuale: {venv_name}")
if run_command(f"python -m venv {venv_name}", "Creazione ambiente virtuale"):
print(f"βœ… Ambiente virtuale creato: {venv_name}")
# Istruzioni per attivazione
system = detect_system()
if system == "windows":
activate_cmd = f"{venv_name}\\Scripts\\activate"
else:
activate_cmd = f"source {venv_name}/bin/activate"
print(f"πŸ”§ Per attivare l'ambiente virtuale:")
print(f" {activate_cmd}")
return True
else:
print(f"βœ… Ambiente virtuale giΓ  esistente: {venv_name}")
return True
return False
def install_requirements():
"""Installa i requirements"""
# Aggiorna pip
run_command("pip install --upgrade pip", "Aggiornamento pip")
# Installa PyTorch ottimizzato
if not install_torch_optimized():
print("❌ Errore nell'installazione di PyTorch")
return False
# Installa altri requirements
requirements = [
("transformers>=4.30.0", "Hugging Face Transformers"),
("numpy>=1.21.0", "NumPy"),
("pandas>=1.3.0", "Pandas"),
("yfinance>=0.2.0", "Yahoo Finance"),
("requests>=2.25.0", "Requests"),
("scipy>=1.7.0", "SciPy"),
("scikit-learn>=1.0.0", "Scikit-learn"),
("accelerate>=0.20.0", "Accelerate"),
("tokenizers>=0.13.0", "Tokenizers"),
("tqdm>=4.62.0", "Progress bars"),
("python-dateutil>=2.8.0", "Date utilities"),
("matplotlib>=3.5.0", "Matplotlib"),
("seaborn>=0.11.0", "Seaborn"),
]
failed_installs = []
for package, description in requirements:
if not run_command(f"pip install {package}", f"Installazione {description}"):
failed_installs.append(package)
if failed_installs:
print(f"\n❌ Pacchetti non installati:")
for package in failed_installs:
print(f" - {package}")
return False
return True
def verify_installation():
"""Verifica l'installazione"""
print("\nπŸ” Verifica installazione...")
test_imports = [
("torch", "PyTorch"),
("transformers", "Hugging Face Transformers"),
("numpy", "NumPy"),
("pandas", "Pandas"),
("yfinance", "Yahoo Finance"),
]
failed_imports = []
for module, description in test_imports:
try:
__import__(module)
print(f"βœ… {description}")
except ImportError as e:
print(f"❌ {description}: {e}")
failed_imports.append(module)
if failed_imports:
print(f"\n❌ Moduli non importabili:")
for module in failed_imports:
print(f" - {module}")
return False
print("\nβœ… Tutti i moduli principali sono installati correttamente!")
return True
def create_test_script():
"""Crea uno script di test"""
test_script = '''#!/usr/bin/env python3
"""
Script di test per verificare l'installazione
"""
import sys
import torch
import transformers
import yfinance as yf
import pandas as pd
import numpy as np
def test_torch():
"""Test PyTorch"""
print("πŸ”₯ Testing PyTorch...")
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = x + y
print(f" Tensor operation: {z.shape}")
if torch.cuda.is_available():
print(f" CUDA available: {torch.cuda.device_count()} devices")
else:
print(" CUDA not available (CPU only)")
print("βœ… PyTorch OK")
def test_transformers():
"""Test Hugging Face"""
print("πŸ€— Testing Transformers...")
from transformers import AutoTokenizer
try:
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
tokens = tokenizer("Hello, world!")
print(f" Tokenized: {len(tokens['input_ids'])} tokens")
print("βœ… Transformers OK")
except Exception as e:
print(f"❌ Transformers error: {e}")
def test_yfinance():
"""Test Yahoo Finance"""
print("πŸ’° Testing yfinance...")
try:
ticker = yf.Ticker("AAPL")
info = ticker.info
print(f" AAPL current price: ${info.get('currentPrice', 'N/A')}")
print("βœ… yfinance OK")
except Exception as e:
print(f"❌ yfinance error: {e}")
def main():
print("πŸ§ͺ Financial Transformer - Test Suite")
print("=" * 40)
test_torch()
test_transformers()
test_yfinance()
print("\\nπŸŽ‰ Test completato!")
if __name__ == "__main__":
main()
'''
with open("test_installation.py", "w") as f:
f.write(test_script)
print("βœ… Script di test creato: test_installation.py")
def main():
"""Funzione principale"""
print("πŸš€ Financial Transformer - Setup")
print("=" * 40)
# Verifica Python
if not check_python_version():
sys.exit(1)
# Rileva sistema
detect_system()
# Opzionale: crea ambiente virtuale
print("\nπŸ“¦ Vuoi creare un ambiente virtuale? (y/n): ", end="")
if input().lower().startswith('y'):
create_virtual_environment()
print("\n⚠️ Attiva l'ambiente virtuale e riavvia questo script")
return
# Installa requirements
print("\nπŸ“¦ Installazione dipendenze...")
if not install_requirements():
print("❌ Errore nell'installazione")
sys.exit(1)
# Verifica installazione
if not verify_installation():
print("❌ Verifica fallita")
sys.exit(1)
# Crea script di test
create_test_script()
print("\nπŸŽ‰ Setup completato!")
print("πŸ§ͺ Esegui: python test_installation.py")
print("πŸš€ Esegui: python app.py")
if __name__ == "__main__":
main()