npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@charlie-the-ai/analytics-core

v0.2.0

Published

Deterministic, zero-dependency business intelligence and analytics calculation engine for Charlie the Business Advisor

Readme

@charlie-the-ai/analytics-core ⚡

Pure, deterministic, zero-dependency business intelligence and financial calculation engine.

npm version License: MIT Zero Dependencies TypeScript


Overview

@charlie-the-ai/analytics-core is the mathematical heart of Charlie the Business Advisor. It runs anywhere JavaScript runs — Node.js, browsers, Edge workers (Cloudflare Workers, Vercel Edge), Deno, or Bun — with zero runtime external dependencies.

Key Capabilities

  1. Fixed-Point Financial Mathematics (Money)

    • Arithmetic on integer minor units (cents, kobo, pence) eliminates IEEE-754 floating-point errors.
    • Half-up rounding, percentage ratios, safe-integer bounds checking, and locale-aware currency formatting.
  2. Sales & Revenue Diagnostics (calculateSalesSummary)

    • Gross revenue, net revenue, total discounts, refunds, average order value (AOV), and average items per order.
    • Period-over-period percentage growth comparisons.
    • Periodic breakdowns (hourly, daily, weekly, monthly).
  3. Pareto (80/20) Concentration Analysis (calculatePareto)

    • Ranks contributors (products, customers, categories) by descending revenue.
    • Computes cumulative revenue percentages, cumulative share of items, and Gini coefficient.
    • Identifies the critical subset driving 80% (or custom threshold) of business performance.
  4. RFM Customer Segmentation & Retention (calculateCustomerAnalytics)

    • Quintile-based Recency, Frequency, and Monetary (RFM) scoring (1-5 scales).
    • Automated cohort segmentation: Champions, Loyal, Potential Loyalists, At Risk, Hibernating, and Lost.
    • Retention rate, churn rate, repeat customer rate, and customer lifetime value (CLV).
  5. Product Velocity & Margins (calculateProductAnalytics)

    • Unit sales velocity, revenue contribution, gross margin percentage, and unit profitability.
    • Identification of high-velocity vs. high-margin items.
  6. Statistical Trends & Anomaly Detection (calculateTrends)

    • 7-day and 30-day simple moving averages (SMA).
    • Rolling standard deviations and z-score anomaly detection to flag revenue spikes or drops.
  7. Standardized Snapshot Generation (createAnalyticsSnapshot)

    • Generates an immutable, deterministic, hash-verified snapshot encompassing all metrics.
    • Computes data quality scores and flags data omissions (missing customer IDs, missing cost basis).

Installation

# npm
npm install @charlie-the-ai/analytics-core @charlie-the-ai/advisor-types

# pnpm
pnpm add @charlie-the-ai/analytics-core @charlie-the-ai/advisor-types

# yarn
yarn add @charlie-the-ai/analytics-core @charlie-the-ai/advisor-types

Usage Examples

1. Deterministic Money Operations

import { Money } from "@charlie-the-ai/analytics-core";

// Addition and subtraction (in minor units)
const total = Money.add(1099, 2500, 450); // 4049 (cents)
const net = Money.subtract(total, 500);    // 3549 (cents)

// Safe multiplication & division with half-up rounding
const discounted = Money.multiply(10000, 0.85); // 8500
const unitShare = Money.divide(10000, 3);        // 3333

// Formatted string output
console.log(Money.format(2500000, "NGN")); // "₦25,000.00"
console.log(Money.format(1499, "USD"));    // "$14.99"
console.log(Money.format(1500, "JPY"));    // "¥1,500"

// Conversion
const minorUnits = Money.toMinorUnits(19.99, "USD"); // 1999
const majorUnits = Money.toMajorUnits(1999, "USD");  // 19.99

2. Comprehensive Analytics Snapshot

import { createAnalyticsSnapshot } from "@charlie-the-ai/analytics-core";
import type { Order } from "@charlie-the-ai/advisor-types";

const orders: Order[] = [
  {
    id: "ord_001",
    customerId: "cust_101",
    status: "completed",
    totalAmount: 15000, // $150.00
    currency: "USD",
    createdAt: "2026-03-01T10:00:00Z",
    items: [
      {
        id: "item_01",
        productId: "prod_a",
        productName: "Mechanical Keyboard",
        quantity: 1,
        unitPrice: 15000,
        totalPrice: 15000,
      },
    ],
  },
  // ... more orders
];

const snapshot = createAnalyticsSnapshot({
  businessId: "biz_acme",
  currency: "USD",
  period: {
    from: "2026-03-01T00:00:00Z",
    to: "2026-03-31T23:59:59Z",
  },
  orders,
  paretoThreshold: 80,
});

console.log("Snapshot ID:", snapshot.snapshotId);
console.log("Net Revenue:", snapshot.sales.netRevenueMinorUnits);
console.log("AOV:", snapshot.sales.averageOrderValueMinorUnits);
console.log("Pareto 80/20 Concentration:", snapshot.pareto.products.concentrationRatio);
console.log("Data Quality Score:", snapshot.dataQuality.scorePercentage);

3. Pareto Analysis Standalone

import {
  calculatePareto,
  extractParetoInputsFromOrders,
} from "@charlie-the-ai/analytics-core";

const inputs = extractParetoInputsFromOrders(orders, "product");

const result = calculatePareto({
  dimension: "product",
  items: inputs,
  currency: "USD",
  thresholdPercentage: 80,
});

console.log(`Gini Coefficient: ${result.giniCoefficient}`);
console.log(`Items generating 80% revenue: ${result.topContributorsCount} of ${result.totalItemsCount}`);
for (const item of result.contributors) {
  console.log(`${item.name}: ${item.cumulativePercentage}% cumulative`);
}

4. RFM Customer Segmentation Standalone

import { calculateCustomerAnalytics } from "@charlie-the-ai/analytics-core";

const customerAnalytics = calculateCustomerAnalytics({
  orders,
  currency: "USD",
  referenceDate: new Date("2026-03-31T23:59:59Z"),
});

console.log("Repeat Customer Rate:", customerAnalytics.repeatCustomerRate);
console.log("Champions:", customerAnalytics.segments.champions.length);
console.log("At Risk:", customerAnalytics.segments.atRisk.length);

Architecture & Determinism

  • No Date Non-determinism: All algorithms accept an optional referenceDate parameter for testing or historical point-in-time replays.
  • Stable Sorting: Deterministic tie-breaking on Pareto and RFM calculations ensures identical output for identical datasets across all platforms.
  • Hash-Verified Snapshots: Every snapshot produces an immutable hash ID derived from content, schema version, and calculation version.

Related Packages


License

MIT © 2026 Charlie the Business Advisor Contributors