File size: 8,465 Bytes
c014538
 
a3fcc9a
c014538
 
 
a3fcc9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c014538
a3fcc9a
 
 
c014538
a3fcc9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c014538
a3fcc9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c014538
a3fcc9a
 
 
 
 
 
c014538
a3fcc9a
 
 
 
 
 
c014538
a3fcc9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c014538
a3fcc9a
 
 
 
 
 
 
 
 
 
 
c014538
a3fcc9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c014538
 
a3fcc9a
 
 
 
c014538
a3fcc9a
 
 
 
 
c014538
a3fcc9a
 
 
 
 
 
 
c014538
 
a3fcc9a
 
 
 
 
 
c014538
a3fcc9a
 
 
 
 
 
 
 
 
 
 
 
 
 
c014538
 
a3fcc9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c014538
 
a3fcc9a
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
#!/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()