Overview

The SG Cars Trends API provides powerful built-in analytics for comparing data across different time periods. This guide covers all comparison features and practical use cases.

Car Registration Comparison

Basic Comparison

The /v1/cars/compare endpoint provides month-over-month and year-over-year comparisons:

curl "https://api.sgcarstrends.com/v1/cars/compare?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Response Structure

{
  "success": true,
  "data": {
    "current_month": {
      "month": "2024-01",
      "total_registrations": 1250,
      "by_fuel_type": {
        "Petrol": 600,
        "Hybrid": 350,
        "Electric": 200,
        "Diesel": 100
      },
      "by_vehicle_type": {
        "Passenger Cars": 1000,
        "Goods & Other Vehicles": 150,
        "Motorcycles & Scooters": 100
      }
    },
    "previous_month": {
      "month": "2023-12",
      "total_registrations": 1100,
      "by_fuel_type": {
        "Petrol": 650,
        "Hybrid": 300,
        "Electric": 100,
        "Diesel": 50
      }
    },
    "previous_year": {
      "month": "2023-01",
      "total_registrations": 1000,
      "by_fuel_type": {
        "Petrol": 700,
        "Hybrid": 250,
        "Electric": 50,
        "Diesel": 0
      }
    },
    "comparison": {
      "month_over_month": {
        "total_change": 150,
        "total_percentage": 13.64,
        "fuel_type_changes": {
          "Petrol": -50,
          "Hybrid": 50,
          "Electric": 100,
          "Diesel": 50
        }
      },
      "year_over_year": {
        "total_change": 250,
        "total_percentage": 25.0,
        "fuel_type_changes": {
          "Petrol": -100,
          "Hybrid": 100,
          "Electric": 150,
          "Diesel": 100
        }
      }
    }
  }
}

Understanding Growth Metrics

Percentage Calculations

Growth percentages are calculated as:

Percentage Change = ((Current Value - Previous Value) / Previous Value) × 100

Interpreting Results

Positive Growth

Values above 0% indicate growth

  • 10% = 10% increase
  • 25% = 25% increase

Negative Growth

Values below 0% indicate decline

  • -10% = 10% decrease
  • -25% = 25% decrease

Advanced Comparison Analysis

Analyze the shift in fuel type preferences:

async function analyzeFuelTypeTrends(month) {
  const response = await fetch(`https://api.sgcarstrends.com/v1/cars/compare?month=${month}`, {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });
  const data = await response.json();
  
  const trends = {
    electric_growth: {
      mom: data.data.comparison.month_over_month.fuel_type_changes.Electric || 0,
      yoy: data.data.comparison.year_over_year.fuel_type_changes.Electric || 0
    },
    petrol_decline: {
      mom: data.data.comparison.month_over_month.fuel_type_changes.Petrol || 0,
      yoy: data.data.comparison.year_over_year.fuel_type_changes.Petrol || 0
    },
    hybrid_growth: {
      mom: data.data.comparison.month_over_month.fuel_type_changes.Hybrid || 0,
      yoy: data.data.comparison.year_over_year.fuel_type_changes.Hybrid || 0
    }
  };
  
  return trends;
}

const trends = await analyzeFuelTypeTrends('2024-01');
console.log('Electric vehicle growth:', trends.electric_growth);

Market Share Analysis

Calculate market share changes:

function calculateMarketShare(data) {
  const current = data.current_month;
  const previous = data.previous_month;
  
  const currentShares = {};
  const previousShares = {};
  
  // Calculate current market shares
  Object.keys(current.by_fuel_type).forEach(fuelType => {
    currentShares[fuelType] = (current.by_fuel_type[fuelType] / current.total_registrations) * 100;
  });
  
  // Calculate previous market shares
  Object.keys(previous.by_fuel_type).forEach(fuelType => {
    previousShares[fuelType] = (previous.by_fuel_type[fuelType] / previous.total_registrations) * 100;
  });
  
  // Calculate share changes
  const shareChanges = {};
  Object.keys(currentShares).forEach(fuelType => {
    shareChanges[fuelType] = currentShares[fuelType] - (previousShares[fuelType] || 0);
  });
  
  return {
    current: currentShares,
    previous: previousShares,
    changes: shareChanges
  };
}

// Usage
const comparison = await fetch('https://api.sgcarstrends.com/v1/cars/compare?month=2024-01', {
  headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
}).then(r => r.json());

const marketShare = calculateMarketShare(comparison.data);
console.log('Market share changes:', marketShare.changes);

Top Performers Analysis

Top Fuel Types and Vehicle Types

Get the most popular categories for a specific month:

curl "https://api.sgcarstrends.com/v1/cars/top-types?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Response Structure

{
  "success": true,
  "data": {
    "month": "2024-01",
    "top_fuel_type": {
      "fuel_type": "Petrol",
      "registrations": 600,
      "percentage": 48.0
    },
    "top_vehicle_type": {
      "vehicle_type": "Passenger Cars",
      "registrations": 1000,
      "percentage": 80.0
    }
  }
}

Top Makes by Fuel Type

Get the top 3 manufacturers for each fuel type:

curl "https://api.sgcarstrends.com/v1/cars/top-makes?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Response Structure

{
  "success": true,
  "data": {
    "month": "2024-01",
    "by_fuel_type": {
      "Petrol": [
        { "make": "Toyota", "registrations": 180 },
        { "make": "Honda", "registrations": 150 },
        { "make": "Nissan", "registrations": 120 }
      ],
      "Electric": [
        { "make": "Tesla", "registrations": 80 },
        { "make": "BYD", "registrations": 60 },
        { "make": "Hyundai", "registrations": 40 }
      ],
      "Hybrid": [
        { "make": "Toyota", "registrations": 200 },
        { "make": "Honda", "registrations": 100 },
        { "make": "Lexus", "registrations": 50 }
      ]
    }
  }
}

COE Bidding Analytics

Compare COE premiums across different periods:

async function analyzeCOETrends(months) {
  const results = await Promise.all(
    months.map(async (month) => {
      const response = await fetch(`https://api.sgcarstrends.com/v1/coe?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      });
      const data = await response.json();
      return {
        month,
        averagePremium: data.data.reduce((sum, item) => sum + item.premium, 0) / data.data.length
      };
    })
  );
  
  return results;
}

const coeTrends = await analyzeCOETrends(['2024-01', '2024-02', '2024-03']);

Success Rate Analysis

Calculate COE bidding success rates:

async function calculateCOESuccessRates(month) {
  const response = await fetch(`https://api.sgcarstrends.com/v1/coe?month=${month}`, {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });
  const data = await response.json();
  
  const successRates = data.data.map(item => ({
    vehicle_class: item.vehicle_class,
    success_rate: (item.bids_success / item.bids_received) * 100,
    quota_utilization: (item.bids_success / item.quota) * 100
  }));
  
  return successRates;
}

const successRates = await calculateCOESuccessRates('2024-01');

Time Series Analysis

Multi-Month Comparison

Compare data across multiple months:

async function createTimeSeries(months, metric = 'total') {
  const timeSeriesData = await Promise.all(
    months.map(async (month) => {
      const response = await fetch(`https://api.sgcarstrends.com/v1/cars?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      });
      const data = await response.json();
      
      let value;
      if (metric === 'total') {
        value = data.data.reduce((sum, item) => sum + item.number, 0);
      } else if (metric === 'electric') {
        value = data.data
          .filter(item => item.fuel_type === 'Electric')
          .reduce((sum, item) => sum + item.number, 0);
      }
      
      return { month, value };
    })
  );
  
  // Calculate month-over-month changes
  const withChanges = timeSeriesData.map((item, index) => {
    if (index === 0) return { ...item, change: 0, percentChange: 0 };
    
    const prev = timeSeriesData[index - 1];
    const change = item.value - prev.value;
    const percentChange = ((change / prev.value) * 100).toFixed(2);
    
    return { ...item, change, percentChange: parseFloat(percentChange) };
  });
  
  return withChanges;
}

// Usage
const months = ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05'];
const totalRegistrations = await createTimeSeries(months, 'total');
const electricVehicles = await createTimeSeries(months, 'electric');

Seasonal Analysis

Identify seasonal patterns:

async function analyzeSeasonalPatterns(year) {
  const months = Array.from({ length: 12 }, (_, i) => 
    `${year}-${String(i + 1).padStart(2, '0')}`
  );
  
  const seasonalData = await createTimeSeries(months, 'total');
  
  const quarters = {
    Q1: seasonalData.slice(0, 3),
    Q2: seasonalData.slice(3, 6),
    Q3: seasonalData.slice(6, 9),
    Q4: seasonalData.slice(9, 12)
  };
  
  const quarterlyAverages = Object.entries(quarters).map(([quarter, data]) => ({
    quarter,
    average: data.reduce((sum, item) => sum + item.value, 0) / data.length,
    total: data.reduce((sum, item) => sum + item.value, 0)
  }));
  
  return quarterlyAverages;
}

const seasonalPatterns = await analyzeSeasonalPatterns('2024');

Benchmarking and KPIs

Key Performance Indicators

Calculate important metrics:

async function calculateKPIs(month) {
  const [comparison, topTypes, topMakes] = await Promise.all([
    fetch(`https://api.sgcarstrends.com/v1/cars/compare?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    fetch(`https://api.sgcarstrends.com/v1/cars/top-types?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    fetch(`https://api.sgcarstrends.com/v1/cars/top-makes?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json())
  ]);
  
  const kpis = {
    total_registrations: comparison.data.current_month.total_registrations,
    mom_growth: comparison.data.comparison.month_over_month.total_percentage,
    yoy_growth: comparison.data.comparison.year_over_year.total_percentage,
    electric_share: (comparison.data.current_month.by_fuel_type.Electric / 
                    comparison.data.current_month.total_registrations) * 100,
    electric_growth_yoy: comparison.data.comparison.year_over_year.fuel_type_changes.Electric || 0,
    top_fuel_type: topTypes.data.top_fuel_type.fuel_type,
    market_leader: topMakes.data.by_fuel_type.Petrol[0].make
  };
  
  return kpis;
}

const kpis = await calculateKPIs('2024-01');
console.log('Monthly KPIs:', kpis);

Comparative Benchmarking

Compare performance against historical averages:

async function benchmarkAgainstAverage(currentMonth, historicalMonths) {
  const [current, ...historical] = await Promise.all([
    fetch(`https://api.sgcarstrends.com/v1/cars?month=${currentMonth}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    ...historicalMonths.map(month => 
      fetch(`https://api.sgcarstrends.com/v1/cars?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      }).then(r => r.json())
    )
  ]);
  
  const currentTotal = current.data.reduce((sum, item) => sum + item.number, 0);
  const historicalTotals = historical.map(data => 
    data.data.reduce((sum, item) => sum + item.number, 0)
  );
  
  const historicalAverage = historicalTotals.reduce((sum, total) => sum + total, 0) / historicalTotals.length;
  const percentageVsAverage = ((currentTotal - historicalAverage) / historicalAverage) * 100;
  
  return {
    current: currentTotal,
    historical_average: historicalAverage,
    performance_vs_average: percentageVsAverage,
    above_average: percentageVsAverage > 0
  };
}

const benchmark = await benchmarkAgainstAverage('2024-01', ['2023-01', '2022-01', '2021-01']);

Practical Use Cases

1. Monthly Report Generation

async function generateMonthlyReport(month) {
  const [comparison, topTypes, topMakes] = await Promise.all([
    fetch(`https://api.sgcarstrends.com/v1/cars/compare?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    fetch(`https://api.sgcarstrends.com/v1/cars/top-types?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    fetch(`https://api.sgcarstrends.com/v1/cars/top-makes?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json())
  ]);
  
  const report = {
    month,
    summary: {
      total_registrations: comparison.data.current_month.total_registrations,
      mom_change: comparison.data.comparison.month_over_month.total_change,
      mom_percentage: comparison.data.comparison.month_over_month.total_percentage,
      yoy_change: comparison.data.comparison.year_over_year.total_change,
      yoy_percentage: comparison.data.comparison.year_over_year.total_percentage
    },
    top_performers: {
      fuel_type: topTypes.data.top_fuel_type,
      vehicle_type: topTypes.data.top_vehicle_type,
      makes: topMakes.data.by_fuel_type
    },
    trends: {
      electric_adoption: comparison.data.current_month.by_fuel_type.Electric,
      electric_growth_yoy: comparison.data.comparison.year_over_year.fuel_type_changes.Electric
    }
  };
  
  return report;
}

const monthlyReport = await generateMonthlyReport('2024-01');

2. Electric Vehicle Adoption Tracking

async function trackElectricVehicleAdoption(months) {
  const evData = await Promise.all(
    months.map(async (month) => {
      const response = await fetch(`https://api.sgcarstrends.com/v1/cars/fuel-types/Electric?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      });
      const data = await response.json();
      
      const total = data.data.reduce((sum, item) => sum + item.number, 0);
      
      return { month, registrations: total };
    })
  );
  
  // Calculate adoption rate
  const withGrowth = evData.map((item, index) => {
    if (index === 0) return { ...item, growth: 0 };
    
    const prev = evData[index - 1];
    const growth = ((item.registrations - prev.registrations) / prev.registrations) * 100;
    
    return { ...item, growth: parseFloat(growth.toFixed(2)) };
  });
  
  return withGrowth;
}

const evAdoption = await trackElectricVehicleAdoption([
  '2024-01', '2024-02', '2024-03', '2024-04', '2024-05'
]);

Best Practices

1. Data Validation

Always validate comparison data:

function validateComparisonData(data) {
  const required = ['current_month', 'previous_month', 'previous_year', 'comparison'];
  const missing = required.filter(field => !data.data[field]);
  
  if (missing.length > 0) {
    throw new Error(`Missing required fields: ${missing.join(', ')}`);
  }
  
  return true;
}

2. Handle Missing Data

Account for months with no data:

function safeDivision(numerator, denominator) {
  if (denominator === 0) return 0;
  return numerator / denominator;
}

function calculateGrowthRate(current, previous) {
  if (!previous || previous === 0) return null;
  return ((current - previous) / previous) * 100;
}

3. Round Numbers Appropriately

function formatPercentage(value, decimals = 2) {
  if (value === null || value === undefined) return 'N/A';
  return `${value.toFixed(decimals)}%`;
}

function formatNumber(value) {
  if (value === null || value === undefined) return 'N/A';
  return value.toLocaleString();
}

Next Steps

Overview

The SG Cars Trends API provides powerful built-in analytics for comparing data across different time periods. This guide covers all comparison features and practical use cases.

Car Registration Comparison

Basic Comparison

The /v1/cars/compare endpoint provides month-over-month and year-over-year comparisons:

curl "https://api.sgcarstrends.com/v1/cars/compare?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Response Structure

{
  "success": true,
  "data": {
    "current_month": {
      "month": "2024-01",
      "total_registrations": 1250,
      "by_fuel_type": {
        "Petrol": 600,
        "Hybrid": 350,
        "Electric": 200,
        "Diesel": 100
      },
      "by_vehicle_type": {
        "Passenger Cars": 1000,
        "Goods & Other Vehicles": 150,
        "Motorcycles & Scooters": 100
      }
    },
    "previous_month": {
      "month": "2023-12",
      "total_registrations": 1100,
      "by_fuel_type": {
        "Petrol": 650,
        "Hybrid": 300,
        "Electric": 100,
        "Diesel": 50
      }
    },
    "previous_year": {
      "month": "2023-01",
      "total_registrations": 1000,
      "by_fuel_type": {
        "Petrol": 700,
        "Hybrid": 250,
        "Electric": 50,
        "Diesel": 0
      }
    },
    "comparison": {
      "month_over_month": {
        "total_change": 150,
        "total_percentage": 13.64,
        "fuel_type_changes": {
          "Petrol": -50,
          "Hybrid": 50,
          "Electric": 100,
          "Diesel": 50
        }
      },
      "year_over_year": {
        "total_change": 250,
        "total_percentage": 25.0,
        "fuel_type_changes": {
          "Petrol": -100,
          "Hybrid": 100,
          "Electric": 150,
          "Diesel": 100
        }
      }
    }
  }
}

Understanding Growth Metrics

Percentage Calculations

Growth percentages are calculated as:

Percentage Change = ((Current Value - Previous Value) / Previous Value) × 100

Interpreting Results

Positive Growth

Values above 0% indicate growth

  • 10% = 10% increase
  • 25% = 25% increase

Negative Growth

Values below 0% indicate decline

  • -10% = 10% decrease
  • -25% = 25% decrease

Advanced Comparison Analysis

Analyze the shift in fuel type preferences:

async function analyzeFuelTypeTrends(month) {
  const response = await fetch(`https://api.sgcarstrends.com/v1/cars/compare?month=${month}`, {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });
  const data = await response.json();
  
  const trends = {
    electric_growth: {
      mom: data.data.comparison.month_over_month.fuel_type_changes.Electric || 0,
      yoy: data.data.comparison.year_over_year.fuel_type_changes.Electric || 0
    },
    petrol_decline: {
      mom: data.data.comparison.month_over_month.fuel_type_changes.Petrol || 0,
      yoy: data.data.comparison.year_over_year.fuel_type_changes.Petrol || 0
    },
    hybrid_growth: {
      mom: data.data.comparison.month_over_month.fuel_type_changes.Hybrid || 0,
      yoy: data.data.comparison.year_over_year.fuel_type_changes.Hybrid || 0
    }
  };
  
  return trends;
}

const trends = await analyzeFuelTypeTrends('2024-01');
console.log('Electric vehicle growth:', trends.electric_growth);

Market Share Analysis

Calculate market share changes:

function calculateMarketShare(data) {
  const current = data.current_month;
  const previous = data.previous_month;
  
  const currentShares = {};
  const previousShares = {};
  
  // Calculate current market shares
  Object.keys(current.by_fuel_type).forEach(fuelType => {
    currentShares[fuelType] = (current.by_fuel_type[fuelType] / current.total_registrations) * 100;
  });
  
  // Calculate previous market shares
  Object.keys(previous.by_fuel_type).forEach(fuelType => {
    previousShares[fuelType] = (previous.by_fuel_type[fuelType] / previous.total_registrations) * 100;
  });
  
  // Calculate share changes
  const shareChanges = {};
  Object.keys(currentShares).forEach(fuelType => {
    shareChanges[fuelType] = currentShares[fuelType] - (previousShares[fuelType] || 0);
  });
  
  return {
    current: currentShares,
    previous: previousShares,
    changes: shareChanges
  };
}

// Usage
const comparison = await fetch('https://api.sgcarstrends.com/v1/cars/compare?month=2024-01', {
  headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
}).then(r => r.json());

const marketShare = calculateMarketShare(comparison.data);
console.log('Market share changes:', marketShare.changes);

Top Performers Analysis

Top Fuel Types and Vehicle Types

Get the most popular categories for a specific month:

curl "https://api.sgcarstrends.com/v1/cars/top-types?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Response Structure

{
  "success": true,
  "data": {
    "month": "2024-01",
    "top_fuel_type": {
      "fuel_type": "Petrol",
      "registrations": 600,
      "percentage": 48.0
    },
    "top_vehicle_type": {
      "vehicle_type": "Passenger Cars",
      "registrations": 1000,
      "percentage": 80.0
    }
  }
}

Top Makes by Fuel Type

Get the top 3 manufacturers for each fuel type:

curl "https://api.sgcarstrends.com/v1/cars/top-makes?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Response Structure

{
  "success": true,
  "data": {
    "month": "2024-01",
    "by_fuel_type": {
      "Petrol": [
        { "make": "Toyota", "registrations": 180 },
        { "make": "Honda", "registrations": 150 },
        { "make": "Nissan", "registrations": 120 }
      ],
      "Electric": [
        { "make": "Tesla", "registrations": 80 },
        { "make": "BYD", "registrations": 60 },
        { "make": "Hyundai", "registrations": 40 }
      ],
      "Hybrid": [
        { "make": "Toyota", "registrations": 200 },
        { "make": "Honda", "registrations": 100 },
        { "make": "Lexus", "registrations": 50 }
      ]
    }
  }
}

COE Bidding Analytics

Compare COE premiums across different periods:

async function analyzeCOETrends(months) {
  const results = await Promise.all(
    months.map(async (month) => {
      const response = await fetch(`https://api.sgcarstrends.com/v1/coe?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      });
      const data = await response.json();
      return {
        month,
        averagePremium: data.data.reduce((sum, item) => sum + item.premium, 0) / data.data.length
      };
    })
  );
  
  return results;
}

const coeTrends = await analyzeCOETrends(['2024-01', '2024-02', '2024-03']);

Success Rate Analysis

Calculate COE bidding success rates:

async function calculateCOESuccessRates(month) {
  const response = await fetch(`https://api.sgcarstrends.com/v1/coe?month=${month}`, {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });
  const data = await response.json();
  
  const successRates = data.data.map(item => ({
    vehicle_class: item.vehicle_class,
    success_rate: (item.bids_success / item.bids_received) * 100,
    quota_utilization: (item.bids_success / item.quota) * 100
  }));
  
  return successRates;
}

const successRates = await calculateCOESuccessRates('2024-01');

Time Series Analysis

Multi-Month Comparison

Compare data across multiple months:

async function createTimeSeries(months, metric = 'total') {
  const timeSeriesData = await Promise.all(
    months.map(async (month) => {
      const response = await fetch(`https://api.sgcarstrends.com/v1/cars?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      });
      const data = await response.json();
      
      let value;
      if (metric === 'total') {
        value = data.data.reduce((sum, item) => sum + item.number, 0);
      } else if (metric === 'electric') {
        value = data.data
          .filter(item => item.fuel_type === 'Electric')
          .reduce((sum, item) => sum + item.number, 0);
      }
      
      return { month, value };
    })
  );
  
  // Calculate month-over-month changes
  const withChanges = timeSeriesData.map((item, index) => {
    if (index === 0) return { ...item, change: 0, percentChange: 0 };
    
    const prev = timeSeriesData[index - 1];
    const change = item.value - prev.value;
    const percentChange = ((change / prev.value) * 100).toFixed(2);
    
    return { ...item, change, percentChange: parseFloat(percentChange) };
  });
  
  return withChanges;
}

// Usage
const months = ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05'];
const totalRegistrations = await createTimeSeries(months, 'total');
const electricVehicles = await createTimeSeries(months, 'electric');

Seasonal Analysis

Identify seasonal patterns:

async function analyzeSeasonalPatterns(year) {
  const months = Array.from({ length: 12 }, (_, i) => 
    `${year}-${String(i + 1).padStart(2, '0')}`
  );
  
  const seasonalData = await createTimeSeries(months, 'total');
  
  const quarters = {
    Q1: seasonalData.slice(0, 3),
    Q2: seasonalData.slice(3, 6),
    Q3: seasonalData.slice(6, 9),
    Q4: seasonalData.slice(9, 12)
  };
  
  const quarterlyAverages = Object.entries(quarters).map(([quarter, data]) => ({
    quarter,
    average: data.reduce((sum, item) => sum + item.value, 0) / data.length,
    total: data.reduce((sum, item) => sum + item.value, 0)
  }));
  
  return quarterlyAverages;
}

const seasonalPatterns = await analyzeSeasonalPatterns('2024');

Benchmarking and KPIs

Key Performance Indicators

Calculate important metrics:

async function calculateKPIs(month) {
  const [comparison, topTypes, topMakes] = await Promise.all([
    fetch(`https://api.sgcarstrends.com/v1/cars/compare?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    fetch(`https://api.sgcarstrends.com/v1/cars/top-types?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    fetch(`https://api.sgcarstrends.com/v1/cars/top-makes?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json())
  ]);
  
  const kpis = {
    total_registrations: comparison.data.current_month.total_registrations,
    mom_growth: comparison.data.comparison.month_over_month.total_percentage,
    yoy_growth: comparison.data.comparison.year_over_year.total_percentage,
    electric_share: (comparison.data.current_month.by_fuel_type.Electric / 
                    comparison.data.current_month.total_registrations) * 100,
    electric_growth_yoy: comparison.data.comparison.year_over_year.fuel_type_changes.Electric || 0,
    top_fuel_type: topTypes.data.top_fuel_type.fuel_type,
    market_leader: topMakes.data.by_fuel_type.Petrol[0].make
  };
  
  return kpis;
}

const kpis = await calculateKPIs('2024-01');
console.log('Monthly KPIs:', kpis);

Comparative Benchmarking

Compare performance against historical averages:

async function benchmarkAgainstAverage(currentMonth, historicalMonths) {
  const [current, ...historical] = await Promise.all([
    fetch(`https://api.sgcarstrends.com/v1/cars?month=${currentMonth}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    ...historicalMonths.map(month => 
      fetch(`https://api.sgcarstrends.com/v1/cars?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      }).then(r => r.json())
    )
  ]);
  
  const currentTotal = current.data.reduce((sum, item) => sum + item.number, 0);
  const historicalTotals = historical.map(data => 
    data.data.reduce((sum, item) => sum + item.number, 0)
  );
  
  const historicalAverage = historicalTotals.reduce((sum, total) => sum + total, 0) / historicalTotals.length;
  const percentageVsAverage = ((currentTotal - historicalAverage) / historicalAverage) * 100;
  
  return {
    current: currentTotal,
    historical_average: historicalAverage,
    performance_vs_average: percentageVsAverage,
    above_average: percentageVsAverage > 0
  };
}

const benchmark = await benchmarkAgainstAverage('2024-01', ['2023-01', '2022-01', '2021-01']);

Practical Use Cases

1. Monthly Report Generation

async function generateMonthlyReport(month) {
  const [comparison, topTypes, topMakes] = await Promise.all([
    fetch(`https://api.sgcarstrends.com/v1/cars/compare?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    fetch(`https://api.sgcarstrends.com/v1/cars/top-types?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    fetch(`https://api.sgcarstrends.com/v1/cars/top-makes?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json())
  ]);
  
  const report = {
    month,
    summary: {
      total_registrations: comparison.data.current_month.total_registrations,
      mom_change: comparison.data.comparison.month_over_month.total_change,
      mom_percentage: comparison.data.comparison.month_over_month.total_percentage,
      yoy_change: comparison.data.comparison.year_over_year.total_change,
      yoy_percentage: comparison.data.comparison.year_over_year.total_percentage
    },
    top_performers: {
      fuel_type: topTypes.data.top_fuel_type,
      vehicle_type: topTypes.data.top_vehicle_type,
      makes: topMakes.data.by_fuel_type
    },
    trends: {
      electric_adoption: comparison.data.current_month.by_fuel_type.Electric,
      electric_growth_yoy: comparison.data.comparison.year_over_year.fuel_type_changes.Electric
    }
  };
  
  return report;
}

const monthlyReport = await generateMonthlyReport('2024-01');

2. Electric Vehicle Adoption Tracking

async function trackElectricVehicleAdoption(months) {
  const evData = await Promise.all(
    months.map(async (month) => {
      const response = await fetch(`https://api.sgcarstrends.com/v1/cars/fuel-types/Electric?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      });
      const data = await response.json();
      
      const total = data.data.reduce((sum, item) => sum + item.number, 0);
      
      return { month, registrations: total };
    })
  );
  
  // Calculate adoption rate
  const withGrowth = evData.map((item, index) => {
    if (index === 0) return { ...item, growth: 0 };
    
    const prev = evData[index - 1];
    const growth = ((item.registrations - prev.registrations) / prev.registrations) * 100;
    
    return { ...item, growth: parseFloat(growth.toFixed(2)) };
  });
  
  return withGrowth;
}

const evAdoption = await trackElectricVehicleAdoption([
  '2024-01', '2024-02', '2024-03', '2024-04', '2024-05'
]);

Best Practices

1. Data Validation

Always validate comparison data:

function validateComparisonData(data) {
  const required = ['current_month', 'previous_month', 'previous_year', 'comparison'];
  const missing = required.filter(field => !data.data[field]);
  
  if (missing.length > 0) {
    throw new Error(`Missing required fields: ${missing.join(', ')}`);
  }
  
  return true;
}

2. Handle Missing Data

Account for months with no data:

function safeDivision(numerator, denominator) {
  if (denominator === 0) return 0;
  return numerator / denominator;
}

function calculateGrowthRate(current, previous) {
  if (!previous || previous === 0) return null;
  return ((current - previous) / previous) * 100;
}

3. Round Numbers Appropriately

function formatPercentage(value, decimals = 2) {
  if (value === null || value === undefined) return 'N/A';
  return `${value.toFixed(decimals)}%`;
}

function formatNumber(value) {
  if (value === null || value === undefined) return 'N/A';
  return value.toLocaleString();
}

Next Steps