File size: 9,263 Bytes
d3be94f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# Flask Web UI - Kronos Ticker Prediction Guide

## Quick Start

### Starting the Flask Server

```bash
cd webui
source ../venv/bin/activate
python app.py
```

The server will start at `http://localhost:5000`

### Accessing the Prediction Interface

**Interactive Web UI (Recommended):**
- Visit: http://localhost:5000/predict
- Simple form to enter ticker symbol
- Real-time Plotly charts with confidence intervals
- Configurable prediction parameters

**Original Complex UI:**
- Visit: http://localhost:5000
- Full file-based prediction interface

---

## Web UI: /predict

### Features**Modern Interface**
- Clean, responsive design
- Real-time interactive charts
- Confidence interval visualization
- Summary statistics display

🎯 **Configurable Parameters**
- Ticker symbol input
- Sample paths (5-100)
- Temperature (0.1-2.0)
- Top-p nucleus sampling (0.5-1.0)

📊 **Output**
- Plotly interactive chart with:
  - Mean price forecast line
  - 90% confidence interval (shaded band)
  - 50% confidence interval (darker band)
- Summary statistics:
  - Mean, standard deviation
  - 5th and 95th percentiles
  - Confidence interval width
  - Time range of forecast

### Usage

1. **Open the page:**
   ```
   http://localhost:5000/predict
   ```

2. **Enter ticker symbol:**
   - Examples: AAPL, MSFT, BTC-USD, TSLA, GOOGL

3. **Adjust parameters (Optional):**
   - Sample Paths: More = better uncertainty (default: 30)
   - Temperature: Higher = more diversity (default: 1.0)
   - Top-p: Lower = more focused (default: 0.9)

4. **Click "Get Prediction"**
   - First run: 30-60 seconds (model loading)
   - Subsequent runs: 5-10 seconds

5. **View Results:**
   - Interactive chart with hover tooltips
   - Summary statistics below chart
   - Confidence intervals visualized as bands

---

## API Endpoint: `/api/predict-ticker`

### Request

**Method:** GET  
**URL:** `http://localhost:5000/api/predict-ticker`

### Query Parameters

| Parameter | Type | Default | Range | Description |
|-----------|------|---------|-------|-------------|
| `ticker` | string | - | - | Stock ticker (required, e.g., 'AAPL') |
| `sample_count` | integer | 30 | 5-100 | Number of sample paths |
| `temperature` | float | 1.0 | 0.1-2.0 | Sampling diversity |
| `top_p` | float | 0.9 | 0.5-1.0 | Nucleus sampling parameter |

### Example Requests

#### Using cURL

```bash
# Basic prediction
curl "http://localhost:5000/api/predict-ticker?ticker=AAPL"

# With custom parameters
curl "http://localhost:5000/api/predict-ticker?ticker=BTC-USD&sample_count=50&temperature=0.8&top_p=0.95"
```

#### Using Python

```python
import requests
import json

response = requests.get('http://localhost:5000/api/predict-ticker', params={
    'ticker': 'AAPL',
    'sample_count': 30,
    'temperature': 1.0,
    'top_p': 0.9
})

data = response.json()
print(f"Prediction successful: {data['success']}")
print(f"Ticker: {data['ticker']}")
print(f"Forecast steps: {data['summary']['forecast_steps']}")
```

#### Using JavaScript/Fetch

```javascript
const params = new URLSearchParams({
    ticker: 'AAPL',
    sample_count: 30,
    temperature: 1.0,
    top_p: 0.9
});

fetch(`/api/predict-ticker?${params}`)
    .then(res => res.json())
    .then(data => {
        console.log('Prediction:', data);
        // Handle chart data
        Plotly.newPlot('chart', data.chart.data, data.chart.layout);
    });
```

### Response Format

**Success Response (200):**

```json
{
    "success": true,
    "ticker": "AAPL",
    "sample_count": 30,
    "forecast_data": [
        {
            "timestamp": "2024-08-29T11:35:00",
            "close_mean": 9.8704,
            "close_std": 0.0153,
            "close_q5": 9.8515,
            "close_q25": 9.8613,
            "close_q75": 9.8777,
            "close_q95": 9.8925,
            "open_mean": 9.8560,
            "high_mean": 9.8803,
            "low_mean": 9.8456,
            "volume_mean": 1500.5
        },
        // ... 23 more time steps
    ],
    "chart": {
        "data": [ /* Plotly trace objects */ ],
        "layout": { /* Plotly layout object */ }
    },
    "summary": {
        "latest_mean": 9.8148,
        "latest_std": 0.0490,
        "latest_q5": 9.7304,
        "latest_q95": 9.8889,
        "confidence_width": 0.1585,
        "forecast_steps": 24,
        "time_range": {
            "start": "2024-08-29T11:35:00",
            "end": "2024-08-29T13:30:00"
        }
    }
}
```

**Error Response (400/500):**

```json
{
    "error": "Ticker parameter is required"
}
```

### Response Fields

#### forecast_data Array

Each forecast point contains:
- `timestamp`: Forecast time (ISO format)
- `close_mean`: Mean closing price
- `close_std`: Standard deviation
- `close_q5`, `q25`, `q75`, `q95`: Percentiles
- `open_mean`, `high_mean`, `low_mean`: OHLC forecasts
- `volume_mean`: Predicted trading volume

#### chart Object

- `data`: Array of Plotly trace objects
- `layout`: Plotly layout configuration

Can be directly passed to `Plotly.newPlot()`:
```javascript
Plotly.newPlot('chart-div', chart.data, chart.layout);
```

#### summary Object

Statistical summary of the 24-hour forecast:
- `latest_mean`: Mean price at end of forecast window
- `latest_std`: Uncertainty at end of forecast
- `latest_q5/q95`: 90% confidence interval bounds
- `confidence_width`: CI upper - CI lower
- `forecast_steps`: Number of predicted time steps
- `time_range`: Start and end timestamps

---

## Data Format

### Historical Data Requirements

The engine.py function `get_prediction(symbol=...)` fetches data from Yahoo Finance:

- **Data Source:** Yahoo Finance
- **Intervals:** Hourly (1H)
- **Duration:** ~2-3 weeks available (limitation of yfinance)
- **Columns:** Open, High, Low, Close, Volume

### Output Data

The API returns data in multiple formats:

#### JSON (in response body)
- Forecast points with OHLCV predictions
- Percentile confidence intervals
- Interactive Plotly chart

#### Optional: CSV File (from engine.py)
- Output to `predictions/{ticker}_forecast.csv`
- Contains 24 rows × 15 columns
- Includes: timestamps, OHLC means/stds, percentiles, volume

#### Optional: NPZ File (from engine.py)
- Output to `predictions/{ticker}_samples.npz`
- NumPy archive with full sample arrays
- Shape: (24 steps, sample_count samples)

---

## Configuration Examples

### Conservative Forecast (Low Variance)
```
Temperature: 0.5
Top-p: 0.8
Sample Count: 50
```

### Standard Forecast (Balanced)
```
Temperature: 1.0
Top-p: 0.9
Sample Count: 30
```

### Adventurous Forecast (High Variance)
```
Temperature: 1.5
Top-p: 0.95
Sample Count: 50
```

---

## Troubleshooting

### Issue: "Prediction engine not available"
**Cause:** engine.py not found or import failed  
**Solution:** Ensure engine.py is in project root and dependencies are installed

### Issue: "Only X records available"
**Cause:** Yahoo Finance doesn't have enough historical data  
**Solution:** Use local CSV file with `data_path` parameter in engine.py directly

### Issue: Prediction takes 60+ seconds
**Cause:** First run loads Kronos models from HuggingFace  
**Solution:** Normal for first request; subsequent requests are faster (~5-10s)

### Issue: "Invalid ticker"
**Cause:** Ticker doesn't exist on Yahoo Finance  
**Solution:** Use valid ticker (e.g., AAPL, BTC-USD, not AAPL123)

---

## Performance Notes

| Metric | Value |
|--------|-------|
| First Prediction | 30-60 seconds (model loading) |
| Subsequent Predictions | 5-10 seconds |
| Memory Usage | ~2GB RAM |
| Model Size | 24.7M parameters (Kronos-small) |
| CPU Usage | Full utilization during prediction |
| GPU Support | Yes (CUDA/MPS) |

---

## Integrating with External Services

### Example: Discord Bot

```python
import discord
from discord.ext import commands
import requests

@bot.command(name='predict')
async def predict_price(ctx, ticker: str):
    async with ctx.typing():
        response = requests.get(f'http://localhost:5000/api/predict-ticker', 
                              params={'ticker': ticker.upper()})
        data = response.json()
        
        embed = discord.Embed(title=f"Prediction for {ticker}")
        embed.add_field(name="Mean Price", 
                       value=f"${data['summary']['latest_mean']:.4f}")
        embed.add_field(name="90% CI", 
                       value=f"${data['summary']['latest_q5']:.4f} - ${data['summary']['latest_q95']:.4f}")
        await ctx.send(embed=embed)
```

### Example: Frontend Dashboard

```html
<script>
async function updateDashboard() {
    const tickers = ['AAPL', 'MSFT', 'GOOGL'];
    
    for (const ticker of tickers) {
        const response = await fetch(`/api/predict-ticker?ticker=${ticker}`);
        const data = await response.json();
        
        updateCard(ticker, data.summary);
    }
}
</script>
```

---

## Documentation Reference

- **Engine Module:** See [USAGE.md](../USAGE.md)
- **Implementation Details:** See [IMPLEMENTATION_SUMMARY.md](../IMPLEMENTATION_SUMMARY.md)
- **Model Documentation:** [Kronos GitHub](https://github.com/shiyu-coder/Kronos)

---

## Support

For issues or feature requests, refer to:
- [engine.py](../engine.py) source code
- [USAGE.md](../USAGE.md) comprehensive guide
- [engine.py docstrings](../engine.py) for parameter details