All files / timesfm-cli/src csv-forecast.ts

98.61% Statements 142/144
100% Branches 30/30
85.71% Functions 6/7
98.61% Lines 142/144

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                  1x 1x 1x 1x                                   1x 1x 35x 35x 1x     1x                                                                 1x 16x 16x 16x 16x 16x 16x   16x 1x 1x     15x 16x     16x     16x 16x 19x 19x 40x 40x 40x 19x 19x   15x 15x   1x 25x 25x 25x 25x           8x 8x     8x   8x     8x 8x 8x     8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x     8x 8x   8x 10x 10x 10x   8x 8x     8x 4x 4x 4x 4x   8x 8x 8x           1x 7x 7x 7x 7x 7x 7x 7x   7x 8x 8x   8x 19x 19x 19x 19x 19x 19x 19x 19x 19x 8x   7x   7x 3x 3x 7x 4x 4x 7x   1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x   8x   8x 4x 4x 4x 4x 4x 8x  
/**
 * CSV forecasting engine for the TimesFM CLI.
 *
 * Reads a CSV file, extracts time series, runs TimesFM forecasts,
 * and outputs results as CSV or JSON.
 *
 * @module csv-forecast
 */
 
import * as fs from 'node:fs';
import { parse } from 'csv-parse/sync';
import { stringify } from 'csv-stringify/sync';
import { TimesFMModel, createForecastConfig } from '@agentix-e/timesfm-core';
 
// ---------------------------------------------------------------------------
// Logger interface
// ---------------------------------------------------------------------------
 
/**
 * Progress logger for CSV forecasting operations.
 *
 * Inject a custom implementation to capture progress events
 * for logging pipelines or to suppress output in quiet mode.
 * Defaults to `console.error` when omitted.
 */
export interface CSVForecastLogger {
  info(msg: string): void;
  error(msg: string): void;
}
 
const defaultLogger: CSVForecastLogger = {
  info(msg: string) {
    console.error(msg);
  },
  error(msg: string) {
    console.error(msg);
  },
};
 
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
 
export interface CSVForecastOptions {
  inputPath: string;
  horizon: number;
  modelPath: string;
  dateCol: string;
  valueCols?: string[];
  outputPath?: string;
  outputFormat: 'csv' | 'json';
  maxContext: number;
  normalizeInputs: boolean;
  forceFlipInvariance: boolean;
  inferIsPositive: boolean;
  fixQuantileCrossing: boolean;
  useContinuousQuantileHead: boolean;
  /** Optional progress logger (defaults to console.error). */
  logger?: CSVForecastLogger;
}
 
interface ParsedCSV {
  dates: string[];
  series: Map<string, Float32Array>;
}
 
// ---------------------------------------------------------------------------
// CSV parsing
// ---------------------------------------------------------------------------
 
export function parseCSVData(filePath: string, dateCol: string, valueCols?: string[]): ParsedCSV {
  const raw = fs.readFileSync(filePath, 'utf-8');
  const records: Record<string, string>[] = parse(raw, {
    columns: true,
    skip_empty_lines: true,
    trim: true,
  });
 
  if (records.length === 0) {
    throw new Error(`Empty CSV file: ${filePath}`);
  }
 
  // Identify columns
  const allCols = Object.keys(records[0]);
  const numericCols = valueCols ?? allCols.filter((c) => c !== dateCol);
 
  // Extract dates
  const dates = records.map((r) => r[dateCol] ?? '');
 
  // Extract series
  const series = new Map<string, Float32Array>();
  for (const col of numericCols) {
    const values: number[] = [];
    for (const record of records) {
      const v = parseFloat(record[col]);
      values.push(Number.isFinite(v) ? v : NaN);
    }
    series.set(col, removeTrailingNaN(new Float32Array(values)));
  }
 
  return { dates, series };
}
 
export function removeTrailingNaN(arr: Float32Array): Float32Array {
  let end = arr.length;
  while (end > 0 && Number.isNaN(arr[end - 1])) end--;
  return arr.slice(0, end);
}
 
// ---------------------------------------------------------------------------
// Main forecast function
// ---------------------------------------------------------------------------
 
export async function csvForecast(options: CSVForecastOptions): Promise<void> {
  const log = options.logger ?? defaultLogger;
 
  // Parse input
  const { series } = parseCSVData(options.inputPath, options.dateCol, options.valueCols);
 
  log.info(`Loaded ${series.size} series from ${options.inputPath}`);
 
  // Create model
  const model = await TimesFMModel.fromPretrained({
    modelPath: options.modelPath,
  });
 
  // Compile
  const fc = createForecastConfig({
    maxContext: options.maxContext,
    maxHorizon: options.horizon,
    normalizeInputs: options.normalizeInputs,
    forceFlipInvariance: options.forceFlipInvariance,
    inferIsPositive: options.inferIsPositive,
    fixQuantileCrossing: options.fixQuantileCrossing,
    useContinuousQuantileHead: options.useContinuousQuantileHead,
  });
 
  model.compile(fc);
  log.info(`Compiled model with maxContext=${fc.maxContext}, maxHorizon=${fc.maxHorizon}`);
 
  // Forecast
  const inputList: Float32Array[] = [];
  const seriesNames: string[] = [];
 
  for (const [name, data] of series) {
    inputList.push(data);
    seriesNames.push(name);
  }
 
  log.info(`Forecasting ${inputList.length} series for ${options.horizon} steps...`);
  const result = await model.forecast(options.horizon, inputList);
 
  // Output
  if (options.outputFormat === 'json') {
    outputJSON(result, seriesNames, options, log);
  } else {
    outputCSV(result, seriesNames, options, log);
  }
 
  await model.dispose();
  log.info('Done.');
}
 
// ---------------------------------------------------------------------------
// Output formatters
// ---------------------------------------------------------------------------
 
export function outputCSV(
  result: { pointForecast: Float32Array[]; quantileForecast: Float32Array[][] },
  seriesNames: string[],
  options: CSVForecastOptions,
  log?: CSVForecastLogger,
): void {
  const logFn = log ?? defaultLogger;
  const rows: Record<string, string | number>[] = [];
 
  for (let s = 0; s < result.pointForecast.length; s++) {
    const pf = result.pointForecast[s];
    const qf = result.quantileForecast[s];
 
    for (let h = 0; h < pf.length; h++) {
      rows.push({
        series_id: seriesNames[s],
        horizon_step: h + 1,
        point_forecast: pf[h],
        q10: qf[1][h],
        q50: qf[5][h],
        q90: qf[9][h],
      });
    }
  }
 
  const csv = stringify(rows, { header: true });
 
  if (options.outputPath) {
    fs.writeFileSync(options.outputPath, csv);
    logFn.info(`Wrote ${rows.length} rows to ${options.outputPath}`);
  } else {
    process.stdout.write(csv);
  }
}
 
export function outputJSON(
  result: { pointForecast: Float32Array[]; quantileForecast: Float32Array[][] },
  seriesNames: string[],
  options: CSVForecastOptions,
  log?: CSVForecastLogger,
): void {
  const logFn = log ?? defaultLogger;
  const output: Record<string, unknown> = {
    model: 'timesfm-2.5',
    horizon: options.horizon,
    series: {},
  };
 
  const seriesOut = output.series as Record<string, unknown>;
  for (let s = 0; s < result.pointForecast.length; s++) {
    seriesOut[seriesNames[s]] = {
      point_forecast: Array.from(result.pointForecast[s]),
      lower_80: Array.from(result.quantileForecast[s][1]), // q10
      upper_80: Array.from(result.quantileForecast[s][9]), // q90
      quantiles: {
        q10: Array.from(result.quantileForecast[s][1]),
        q20: Array.from(result.quantileForecast[s][2]),
        q30: Array.from(result.quantileForecast[s][3]),
        q40: Array.from(result.quantileForecast[s][4]),
        q50: Array.from(result.quantileForecast[s][5]),
        q60: Array.from(result.quantileForecast[s][6]),
        q70: Array.from(result.quantileForecast[s][7]),
        q80: Array.from(result.quantileForecast[s][8]),
        q90: Array.from(result.quantileForecast[s][9]),
      },
    };
  }
 
  const json = JSON.stringify(output, null, 2);
 
  if (options.outputPath) {
    fs.writeFileSync(options.outputPath, json);
    logFn.info(`Wrote JSON to ${options.outputPath}`);
  } else {
    process.stdout.write(json);
  }
}