---
title: "UK Gas Market Information"
author: "Timothy Wong"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{UK Gas Market Information}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(ukgasapi)
```

The National Grid publishes live market information through Market Information Provision Initiative (MIPI) API. It hosts a large volume of data (over 13,500 data items)^[According to the [National Grid](https://www.nationalgrid.com/sites/default/files/documents/42797-MIPI%20Update.pdf)] and is used extensively on a daily basis.

# Calling the API

The function `dataItemExplorer` calls the MIPI API and returns data from the [Data Item Explorer](https://mip-prd-web.azurewebsites.net/DataItemExplorer). The first argument `dataitems` is a character vector of data items where multiple values are accepted. It must match with the data items provided on the Data Item Explorer. This function also requires `fromdate` and `todate` which specify the date range to return data from. The return type is a `data.frame` object.

```{r, results='hide', eval=FALSE}
response <- dataItemExplorer(dataitems = c("Storage Injection, Actual",
                                           "Storage Withdrawal, Actual"),
                             fromdate = "2020-01-01",
                             todate = "2020-06-30")
head(response, 10)
```

# Using batch mode

The National Grid API has certain limit of the size of the query. As a result, we need to implement batch mode if the query it too large. The `batchsize` argument can be configured to limit the size of each API call. It will loop through all dates iteratively and return all results.

```{r, eval=FALSE}
response <- dataItemExplorer(dataitems = c("Storage Injection, Actual",
                                           "Storage Withdrawal, Actual"),
                             fromdate = "2020-01-01",
                             todate = "2020-06-30",
                             batchsize = 20)
```

# Visualising the API response

Since the return type is a `data.frame` object, users can use standard plotting packages such as `ggplot2` to visualise the response.

```{r, echo=TRUE, eval=FALSE}
library(ggplot2)
qplot(x = ApplicableFor,
      y = Value,
      data = response,
      colour = PublicationObjectName,
      geom = "line") + 
  theme(legend.position = "bottom")
```