← back to Watches

api/predictions.js

38 lines

import pool from '../database/connection.js';
import LinearRegression from '../services/ml/linear-regression.js';

export async function getPredictions(req, res) {
  const { watchId } = req.params;

  try {
    // Get historical prices
    const result = await pool.query(`SELECT year, price FROM price_history WHERE watch_id = $1 ORDER BY year`, [watchId]);
    if (result.rows.length < 3) return res.json({ success: false, error: 'Insufficient data' });

    const X = result.rows.map(r => r.year);
    const y = result.rows.map(r => parseFloat(r.price));

    const model = new LinearRegression();
    model.fit(X, y);

    const currentYear = new Date().getFullYear();
    const predictions = [
      { year: currentYear + 1, price: Math.round(model.predict(currentYear + 1)) },
      { year: currentYear + 3, price: Math.round(model.predict(currentYear + 3)) },
      { year: currentYear + 5, price: Math.round(model.predict(currentYear + 5)) }
    ];

    res.json({
      success: true,
      predictions,
      model: { type: 'linear', rSquared: model.rSquared.toFixed(3), rmse: Math.round(model.rmse) },
      confidence: model.rSquared > 0.8 ? 'high' : model.rSquared > 0.5 ? 'medium' : 'low',
      disclaimer: 'Predictions are estimates based on historical data. Not financial advice.'
    });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
}

export default { getPredictions };