R/qcmr.R

Defines functions cer_qcmr qcmr_workbook_links qcmr_report_pages qcmr_url

Documented in cer_qcmr

# Quarterly Carbon Market Report

#' @noRd
QCMR_LANDING <- "https://cer.gov.au/markets/reports-and-data/quarterly-carbon-market-reports"

#' @noRd
QCMR_MONTHS <- c("march", "june", "september", "december")

#' URL of a QCMR data workbook
#'
#' Until late November 2026 the reports page linked every data workbook
#' directly. It now links one report page per quarter, and the workbook
#' is a `/document/` link on that page. Both layouts are handled.
#'
#' @param quarter `"latest"` or a quarter in `"YYYYqN"` form.
#' @param fetch Function taking a URL and returning the page HTML, or
#'   `NA` on failure. Tests pass a fake one to run offline.
#' @return The workbook URL.
#' @noRd
qcmr_url <- function(quarter, fetch = cer_page_html) {
  latest <- identical(quarter, "latest")
  if (!latest) {
    q <- tolower(gsub("[^0-9a-z]", "", quarter))
    parts <- regmatches(q, regexec("^([0-9]{4})q([1-4])$", q))[[1]]
    if (length(parts) != 3L) {
      cli::cli_abort(c(
        "Could not parse quarter {.val {quarter}}.",
        "i" = "Use format like {.val 2025q4} or {.val 2024q2}, or pass {.val latest}."
      ))
    }
    yr <- parts[2]
    month <- QCMR_MONTHS[as.integer(parts[3])]
  }

  landing <- fetch(QCMR_LANDING)
  if (is.na(landing)) {
    cli::cli_abort(c(
      "Could not load the QCMR reports page.",
      "i" = "Check the connection, or browse {.url {QCMR_LANDING}}."
    ))
  }
  pages <- qcmr_report_pages(landing)

  if (latest) {
    hits <- qcmr_workbook_links(landing)
    # A quarter's report page can go up before its workbook, so fall
    # back to the quarter before.
    for (page in utils::head(pages$url, 2L)) {
      if (length(hits) > 0L) break
      html <- fetch(page)
      if (!is.na(html)) hits <- qcmr_workbook_links(html)
    }
    if (length(hits) == 0L) {
      cli::cli_abort(c(
        "Could not find the latest QCMR data workbook.",
        "i" = "Browse {.url {QCMR_LANDING}} manually."
      ))
    }
    return(hits[1L])
  }

  hits <- qcmr_workbook_links(landing, month, yr)
  if (length(hits) == 0L) {
    page <- pages$url[pages$year == yr & pages$month == month]
    if (length(page) == 0L) {
      page <- sprintf("%s/quarterly-carbon-market-report-%s-quarter-%s",
                      QCMR_LANDING, month, yr)
    }
    html <- fetch(page[1L])
    if (!is.na(html)) hits <- qcmr_workbook_links(html, month, yr)
  }
  if (length(hits) == 0L) {
    cli::cli_abort(c(
      "No QCMR data workbook found for {month} quarter {yr}.",
      "i" = "Try {.val latest} or browse {.url {QCMR_LANDING}}."
    ))
  }
  hits[1L]
}

#' Quarter report pages linked from the QCMR reports page, newest first
#'
#' @param html Reports page HTML.
#' @return Data frame with `url` (absolute), `year` and `month` (lower
#'   case), one row per quarter.
#' @noRd
qcmr_report_pages <- function(html) {
  hrefs <- regmatches(html, gregexpr('href="[^"]+"', html))[[1]]
  hrefs <- unique(gsub('^href="|"$', "", hrefs))
  rx <- paste0(
    "^(https://cer\\.gov\\.au)?",
    "(/markets/reports-and-data/quarterly-carbon-market-reports/",
    "quarterly-carbon-market-report-(march|june|september|december)",
    "-quarter-(20[0-9]{2}))/?$"
  )
  m <- regmatches(hrefs, regexec(rx, hrefs))
  m <- m[lengths(m) > 0L]
  if (length(m) == 0L) {
    return(data.frame(url = character(0), year = character(0),
                      month = character(0), stringsAsFactors = FALSE))
  }
  out <- data.frame(
    url = paste0(CER_BASE_URL, vapply(m, `[`, "", 3L)),
    year = vapply(m, `[`, "", 5L),
    month = vapply(m, `[`, "", 4L),
    stringsAsFactors = FALSE
  )
  out <- out[!duplicated(out$url), , drop = FALSE]
  out <- out[order(out$year, match(out$month, QCMR_MONTHS),
                   decreasing = TRUE), , drop = FALSE]
  rownames(out) <- NULL
  out
}

#' QCMR data workbook links in a CER page, optionally for one quarter
#'
#' The workbook is `qcmr-data-workbook-<month>-quarter-<year>` from the
#' December quarter 2023 and `qcmr-<month>-quarter-<year>-data-highlights`
#' in 2022. Infographics also carry `qcmr` in their slug, so the match
#' anchors on the data file's name.
#' @noRd
qcmr_workbook_links <- function(html, month = NULL, yr = NULL) {
  hits <- cer_document_links(html, "qcmr.*data.*workbook|qcmr.*data-highlights")
  if (!is.null(month)) {
    hits <- hits[grepl(month, hits, fixed = TRUE) & grepl(yr, hits, fixed = TRUE)]
  }
  hits
}

#' Quarterly Carbon Market Report data workbook
#'
#' Aggregate carbon market statistics from the CER's Quarterly
#' Carbon Market Report, including ACCU issuances, LGC creations,
#' STC volumes, unit surrenders, and Safeguard Mechanism
#' developments.
#'
#' @param quarter Character. Quarter identifier in `"YYYYqN"` form
#'   (e.g. `"2025q4"` for the December 2025 quarter). Defaults to
#'   `"latest"`, which resolves to the most recent release.
#' @param sheet Sheet name or integer index. The CER QCMR workbook
#'   contains a `Contents` sheet (default) plus one sheet per
#'   figure (e.g. `"Figure 1.1"`, `"Figure 3.14"`). Pass a figure
#'   name to extract that figure's data.
#'
#' @return A `cer_tbl` with the requested sheet's contents.
#'
#' @source Clean Energy Regulator, Quarterly Carbon Market Reports:
#'   <https://cer.gov.au/markets/reports-and-data/quarterly-carbon-market-reports>.
#'   Licensed under CC BY 4.0.
#'
#' @references
#' Clean Energy Regulator (quarterly). \emph{Quarterly Carbon
#'   Market Report}. Methodology notes accompany each release.
#'
#' Clean Energy Regulator (2024). \emph{Carbon Market Indicators:
#'   methodology and data dictionary}.
#'
#' @family qcmr
#' @export
#' @examples
#' \donttest{
#' op <- options(cer.cache_dir = tempdir())
#' try({
#'   # Contents sheet lists all available figures
#'   toc <- cer_qcmr("latest")
#'   head(toc)
#'   # Fetch a specific figure
#'   fig <- cer_qcmr("latest", sheet = "Figure 1.1")
#' })
#' options(op)
#' }
cer_qcmr <- function(quarter = "latest", sheet = "Contents") {
  url <- qcmr_url(quarter)
  df <- cer_fetch_auto(url, sheet = sheet)
  rownames(df) <- NULL
  new_cer_tbl(df,
              source = QCMR_LANDING,
              licence = "CC BY 4.0",
              title = paste0("QCMR ", quarter))
}

Try the cer package in your browser

Any scripts or data that you put into this service are public.

cer documentation built on Dec. 3, 2026, 1:06 a.m.