The OpenElectricity TypeScript client is currently in beta and still under active development.

The OpenElectricity TypeScript client is the official library for accessing the OpenElectricity API, providing simplified access to Australian electricity network data. This client supports both browser and Node.js environments, offering a type-safe interface to work with electricity data from the National Electricity Market (NEM) and Western Australian Electricity Market (WEM).

Features

  • Cross-platform support (Browser & Node.js)
  • Built-in data analysis tools
  • Real-time electricity data access
  • Timezone-aware date handling
  • Time series data manipulation
  • Facility and unit information
  • Market data access

Getting Started

Installation

The Typescript SDK is available on NPM.

npm install @openelectricity/client

Quick Start

import { OpenElectricityClient } from '@openelectricity/client'

// Initialize the client
const client = new OpenElectricityClient()

// Get energy data for the NEM
const { datatable } = await client.getNetworkData('NEM', ['energy'], {
  interval: '1h',
  dateStart: '2024-01-01T00:00:00',
  dateEnd: '2024-01-02T00:00:00',
  primaryGrouping: 'network_region',
})

// Analyze the data
console.table(datatable.toConsole())

Data Analysis

The OpenElectricity client includes a powerful DataTable class that provides a pandas/polars-like interface for analyzing time series data.

DataTable Overview

The DataTable class provides methods for:

  • Filtering and selecting data
  • Grouping and aggregating
  • Sorting and ordering
  • Statistical analysis
  • Data transformation

Core Methods

Accessing Data

// Get all rows
const rows = datatable.getRows()

// Get available grouping columns
const groupings = datatable.getGroupings()

// Get metrics and their units
const metrics = datatable.getMetrics()

// Get the latest timestamp
const latestTime = datatable.getLatestTimestamp()

Filtering

Filter rows based on a condition:

// Filter for high power periods
const highPower = datatable.filter(row => (row.power as number) > 1000)

// Filter for specific region
const nswData = datatable.filter(row => row.network_region === "NSW1")

Selecting Columns

Select specific columns to work with:

// Select only power and region columns
const powerByRegion = datatable.select(["interval", "power", "network_region"])

Grouping and Aggregation

Group data and calculate aggregates:

// Calculate sum by region
const totalByRegion = datatable.groupBy(["network_region"], "sum")

// Calculate mean by region and fuel technology
const avgByRegionAndFuel = datatable.groupBy(
  ["network_region", "fueltech"],
  "mean"
)

Supported aggregation methods:

  • "sum": Calculate the sum of values
  • "mean": Calculate the arithmetic mean

Sorting

Sort data by one or more columns:

// Sort by power, descending
const highestFirst = datatable.sortBy(["power"], false)

// Sort by region, then by power
const sortedData = datatable.sortBy(["network_region", "power"])

Statistical Analysis

Calculate summary statistics for numeric columns:

const stats = datatable.describe()

The describe() method returns statistics including:

  • count: Number of non-null values
  • mean: Arithmetic mean
  • std: Standard deviation
  • min: Minimum value
  • q25: 25th percentile
  • median: 50th percentile
  • q75: 75th percentile
  • max: Maximum value

Performance Considerations

The DataTable class includes several optimizations:

  1. Caching: Results of grouping and sorting operations are cached
  2. Indexed Filtering: Simple equality filters use column indexes
  3. Single-Pass Operations: Many operations are optimized to process data in a single pass
  4. Memory Efficiency: Data structures are reused where possible

Type Reference

Network Types

NetworkCode

Represents the supported electricity networks:

type NetworkCode = "NEM" | "WEM" | "AU"
  • NEM: National Electricity Market (Eastern and Southern Australia)
  • WEM: Western Australian Electricity Market
  • AU: Australia-wide (defaults to NEM timezone)

DataInterval

Supported time intervals for data aggregation:

type DataInterval = "5m" | "1h" | "1d" | "7d" | "1M" | "3M" | "season" | "1y" | "fy"

Metric Types

DataMetric

Metrics available for network and facility data:

type DataMetric = "power" | "energy" | "emissions" | "market_value"

MarketMetric

Metrics available for market data:

type MarketMetric = "price" | "demand" | "demand_energy"

Response Types

ITimeSeriesResponse

Standard response type for time series data:

interface ITimeSeriesResponse {
  response: IAPIResponse<INetworkTimeSeries[]>  // Raw API response
  datatable?: DataTable                         // Processed data table
}

FacilityResponse

Response type for facility queries:

interface FacilityResponse {
  response: IAPIResponse<IFacility[]>           // Raw API response
  table: RecordTable<IFacilityRecord>          // Processed facility records
}

Common Patterns and Examples

Basic Data Retrieval

import { OpenElectricityClient } from '@openelectricity/client'

// Initialize client
const client = new OpenElectricityClient()

// Get energy data for the NEM network
const { response, datatable } = await client.getNetworkData("NEM", ["energy"], {
  interval: "1h",
  dateStart: "2024-01-01T00:00:00",
  dateEnd: "2024-01-02T00:00:00",
  primaryGrouping: "network_region",
})

Analyzing Generation Mix

// Get power data with fuel technology grouping
const { datatable } = await client.getNetworkData("NEM", ["power"], {
  interval: "5m",
  primaryGrouping: "network_region",
  secondaryGrouping: "fueltech",
})

// Calculate renewable vs non-renewable generation
const renewableFueltechs = new Set(["solar", "wind", "hydro", "pumps", "bioenergy"])
const latestData = datatable.filter(row => row.interval.getTime() === datatable.getLatestTimestamp())

let renewable = 0, total = 0
latestData.getRows().forEach(row => {
  const power = row.power as number
  total += power
  if (renewableFueltechs.has(row.fueltech as string)) {
    renewable += power
  }
})

console.log(`Renewable: ${(renewable / total * 100).toFixed(1)}%`)

Calculating Emission Factors

// Get emissions and energy data
const { datatable } = await client.getNetworkData("NEM", ["emissions", "energy"], {
  interval: "1d",
  primaryGrouping: "network_region",
})

// Calculate regional emission factors
const avgByRegion = datatable
  .groupBy(["network_region"], "mean")
  .getRows()
  .map(row => ({
    network_region: row.network_region,
    avg_emission_factor: ((row.emissions as number) / (row.energy as number)).toFixed(3),
  }))

Error Handling

The client throws specific error types:

  • OpenElectricityError: General API errors
  • NoDataFound: When no data matches the query (416 status)
try {
  const result = await client.getNetworkData("NEM", ["energy"])
} catch (error) {
  if (error instanceof OpenElectricityError) {
    console.error("API Error:", error.message)
  } else if (error instanceof NoDataFound) {
    console.error("No matching data found")
  }
}

Support