Spaces:
Running
Running
| # 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 | |