---
title: "Classes in `hpiR`"
author: "Andy Krause"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{hpiR Classes}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  chunk_output_type: console
---

```{r setup, include=FALSE}
  knitr::opts_chunk$set(echo = TRUE, collapse=TRUE, messages=FALSE, eval=FALSE)
```

## Introduction

This vignette explains the various classes of objects and data used in the `hpiR` package. By executing the code in this vignette you can create examples of all classes of objects used in the `hpiR` package. 

## Class Structures

The table below shows the basic information on the various **S3** classes used in the package.  The naming convention of classes is such that prefixes indicate the domain (or the type) of the information contained in the object.  The major domains are: 

<br>

* **"series"** = objects referring to information relevant to the entire hpi series (a set of hpi collections)
* **"hpi"** = objects referring to information relevant to the entire hpi collection
* **"index"** = objects referring to information relevant only to the index itself
* **"rt"** or **"hed"** =  objects with information specific to a particular index approach (**"rt"** for repeat transaction and **"hed"** for hedonic model)^[Additional approaches will be added here in the future.]
    * Suffixes of these classes currently include **"data"** and **"model"**
* **"plot"** = objects containing plot objects.  

The `hpi` collection object is the "core" unit of the `hpiR` package. The object will contain all the information, temporary objects (data, models, etc.) and analysis about a single house price index.  

The `serieshpi` object is a "super-unit" that contains multiple house price indexes within it.  Indexes within a series share the same data, modeling approach and parameters; they differ only in the length of the indexes.  Additionally there are two types of analyses that can only be applied to series: forecast accuracy (`calcForecastError()`) and revision (`calcRevision()`). Also note that in an `serieshpi` object the data objects are moved out of the `hpi` objects and into the `serieshpi` object to avoid duplication of data storage.

The table below shows the various classes of objects used with `hpiR`, their type, what they inherit from, what function creates them and a short description.  A tilde (**~**) in front of the inherits value signifies that some of the components of the object inherit from that class, but not all.   

<br>

| Type | Class | Inherits | Created by | Description |
| :---- | :----- | :------: | :-----: | :-------------------------------------- | 
| **Super** | | | | |
| | `serieshpi` | *many* | `createSeries()` | A series of progressively longer indexes  
||||||
| **Core** | | | | |
| | `hpi` | *many* | `**Index()` wrappers  | Unified house price index collection object containing data, model and index as well as additional analytics that can be added to it  
| | `hpiaccuracy` | `data.frame` | `calcAccuracy()` | Accuracy of the index |
||||||
| **Data** | | | | |
| | `hpidata` | `data.frame` | `dateToPeriod()` | Transaction data.frame with dates converted to relative periods |
| | `rtdata` | `hpidata`, `data.frame` | `rtCreateTrans()` | Data.frame of repeat transactions with standardized field names |
| | `heddata` | `hpidata`, `data.frame` | `hedCreatTrans()` | Data.frame of transactions with some standardized field names for use in hedonic model approach |
||||||
| **Model** | | | | |
| | `hpimodel` | Many (ex. `lm`, `rlm`) | `hpiModel()` | Flexible list of model results |
| | `rtmodel` | Many (ex. `lm`, `rlm`) | `rtModel()` | List of repeat transaction model results |
| | `hedmodel` | Many (ex. `lm`, `rlm`) | `hedModel()` | List of hedonic model results |
||||||
| **Index** | | | | |
||||||
| | `hpiindex` | ~`ts` | `modelToIndex()` | List of index information.  `$index` slot is a `ts` object |
| | `indexsmooth` | `ts` | `smoothIndex()` | Smoothed index | 
| | `indexvolatility` | NONE | `calcVolatility()` | List of rolling, mean and median index volatility | 
||||||
| **Series** | | | | |
| | `seriesrevision` | NONE | `calcRevision()` | List of the period, mean and median revision |
| | `seriesaccuracy` | `hpiaccuracy`, `data.frame` | `calcSeriesAccuracy()` | Accuracy of the series |
||||||
| **Visualization** | | | | |
| | `plotindex` | `gg`, `ggplot` | `plot.hpiindex()`, `plot.hpi` | Plotting object for an index |
| | `plotseries` | `gg`, `ggplot` | `plot.serieshpi()` | Plotting object for an index series |
| | `plotrevision` | `gg`, `ggplot` | `plot.seriesrevision()` | Plotting object for revision statistics |
| | `plotaccuracy` | `gtable`, `gTree`, `grob`, `gDesc` | `plot.hpiaccuracy()`, `plot.seriesaccuracy` | Plotting object for accuracy results |
| | `plotvolatility` | `gg`, `ggplot` | `plot.indexvolatility()` | Plotting object for index volatility |

## Examples And Explanation

Small examples of any of the classes in the table above are available in the `hpiR` package as pre-loaded data.  Use `data(ex_'name of class')` to access. Ex: `data(ex_hpidata)`. 

### Loading

Begin by loading the `hpiR` package. It is assumed that you've followed the instructions in the **"introduction"** vignette in order to obtain the package.  

```{r silent_library_load, echo=FALSE}

  suppressMessages(suppressWarnings(library(hpiR)))
  suppressMessages(suppressWarnings(library(knitr)))
  suppressMessages(suppressWarnings(library(magrittr)))

```

```{r hpir_load}
  
  library(hpiR)

```

Next, load the example dataset of Seattle house transactions into your R session.  We'll limit to just the central city (**area** equal to 13, 14, and 15).  This can also be accessed via `data(ex_sales)`.

```{r data_load}

  # Load all sales
  data(seattle_sales)

  # Create a smaller sample of sales
  ex_sales <- seattle_sales %>%
    dplyr::filter(., area %in% c(13, 14, 15))

  # Or just load it
  data(ex_sales)
  
```

### Data

#### 'hpidata' objects

`hpidata` objects inherit from `data.frame`, but are very flexible and the collection of fields that may be in these objects is solely dependent on the data being used.  The only requirements for creating an `hpidata` object is that there must be an R formatted **date** field that can be turned into a period field.  

The `dateToPeriod()` function will create an `hpidata` object by converting the date into a period.  The only difference between the `hpidata` object and the original data.frame is the addition of **trans_date** and  **trans_period** columns and the **periodicity**, **min_date**, **max_date** and **period_table** attributes. 

```{r create_hpidata}

  ex_hpidata <- dateToPeriod(trans_df = ex_sales,
                             date = 'sale_date',
                             periodicity = 'monthly')

```

```{r class_hpidata}

  class(ex_hpidata)

```

```{r str_hpidata}

  str(ex_hpidata)
  
```

#### Approach-based data objects

Each of the index creation approaches (currently just **rt** and **hed**) will have their own data object classes that include the necessary fields and structures for these approach types.  The name format here is "xxdata"", where 'xx' is the approach abbreviation.  

The `rtdata` object holds repeat transactions and contains the eight standard fields shown below as well as the **period_table** attribute.  

```{r create_rtdata}

  ex_rtdata <- rtCreateTrans(trans_df = ex_hpidata,
                             prop_id = 'pinx',
                             trans_id = 'sale_id',
                             price = 'sale_price')
```

```{r class_rtdata}

  class(ex_rtdata)

```

```{r str_rtdata}

  str(ex_rtdata)
  
```

The `heddata` object requires no changes from the original `hpidata` object and looks the same, with the exception of field standardization (**pinx** is now **prop_id**, **sale_id** is now **trans_id**, **sale_price** is now **price**, **sale_date** is now **date**. ) 

```{r create_heddata}

  ex_heddata <- hedCreateTrans(trans_df = ex_sales,
                               prop_id = 'pinx',
                               trans_id = 'sale_id',
                               price = 'sale_price',
                               date = 'sale_date',
                               periodicity = 'monthly')

```

```{r class_heddata}

  class(ex_heddata)

```

```{r str_heddata}
  
    str(ex_heddata)

```

### Modeling 

Results from modeling the data prior to creating indexes is stored in `hpimodel` objects.  These objects contain eight standard slots, shown below.  The slots are standardized across approaches, with the exception of the `model_obj` slot which will contain an object that is specific to the approach being used to estimate the index. 

```{r create_timematrix, echo=FALSE, eval=FALSE}

  # Created for internal purposes, not shown in Vignette
  ex_timematrix <- rtTimeMatrix(ex_rtdata)

```    


```{r create_hpimodel}
  
  ex_hpimodel <- hpiModel(model_type = 'rt',
                          hpi_df = ex_rtdata,
                          estimator = 'base',
                          log_dep = TRUE)

```

```{r class_hpimodel}

   class(ex_hpimodel)

```

```{r str_hpimodel}

  str(ex_hpimodel, max.level=1)

```    

Below we see an example of a `model_obj` from a repeat transactions model. This is very similar to what you'd get from a call to a linear model (`lm(...)`)

```{r create_model_obj}
  ex_rtmodel <- ex_hpimodel$model_obj

```

```{r class_model_obj}
  class(ex_rtmodel)

```

```{r str_model_obj}
  str(ex_rtmodel, max.level=1, give.attr=FALSE)

```

We also show an example of a `model_obj` from a hedonic price method, again similar to an `lm(...)` output. 

```{r create_hmodel_obj}
  ex_hedmodel <- hpiModel(model_type = 'hed',
                          hpi_df = ex_heddata,
                          estimator = 'base',
                          dep_var = 'price',
                          ind_var = c('tot_sf', 'beds', 'baths'),
                          log_dep = TRUE)[["model_obj"]]

```

```{r class_hmodel_obj}
  class(ex_hedmodel)

```
  
```{r str_hmodel_obj}
    str(ex_hedmodel, max.level=1, give.attr=FALSE)

```

### Indexes and Smoothing

The `modelToIndex()` function will take an `hpimodel` object and turn it into an `hpiindex` object.  `hpiindex` objects contain five standard slots. 

```{r create_hpiindex}
  ex_hpiindex <- modelToIndex(model_obj = ex_hpimodel)

```

```{r class_hpiindex}
  class(ex_hpiindex)

```

```{r str_hpiindex}  
  str(ex_hpiindex, max.level=1)
  
```

If we want to add a smoothed index to this object, we use the `smoothIndex()` function.  In its default state, this function just return a simple `ts` (time-series) object of the smoothed index. 

```{r create_smoothindex}
  ex_smoothindex <- smoothIndex(ex_hpiindex)

```

```{r class_smoothindex}
  class(ex_smoothindex)

```

```{r str_smoothindex}
  str(ex_smoothindex)

```

To add it directly to the `hpiindex` object, we add the **"in_place = TRUE"** argument which will add it to the **\$smooth** slot in the `hpiindex` object. Note that the class of **temp_index** stays the same (`hpiindex`), only the **\$smooth** slot is added with an object of class `smoothindex` (inheriting from `ts`).

```{r smooth_inplace}
  temp_index <- smoothIndex(ex_hpiindex, in_place = TRUE)

```

```{r class_smooth_inplace}
  class(temp_index)
  
```

```{r class_smooth_inplaces}
    class(temp_index$smooth)
    
```

```{r str_smooth_inplace}
    str(temp_index)

```

If you want to store plots of `hpiindex` objects, they are returned as `plotindex` objects, inheriting from `gg` and `ggplot` (from the `ggplot2` package)

```{r create_plotindex}
  ex_plotindex <- plot(ex_hpiindex)

```

```{r class_plotindex}
  class(ex_plotindex)

```

### Wrapper

The index level wrappers (`rtIndex()` and `hedIndex()` -- more to come) combine the above steps -- data prep, modeling and index creation -- into a single function, the output of which is an hpi collection, or simply, an `hpi` object.  Directly after creation with a wrapper this object is a list of:

1. A data object (`hpidata`)
2. A model object (`hpimodel`)  
3. An index object (`hpiindex`)  

```{r create_hpi}
  ex_hpi <- rtIndex(trans_df = ex_rtdata,
                    estimator = 'robust',
                    log_dep = TRUE,
                    trim_model = TRUE,
                    smooth = TRUE)

```

```{r class_hpi}
  class(ex_hpi)

```

```{r str_hpi}
  str(ex_hpi, max.level=1)
 
```

### Analyzing Indexes

#### Volatility

Index volatility can be calculated by providing an `hpiindex` object to the `calcVolatility()` function. The result is an object of class `indexvolatility`, containing three vector objects as well as two attributes indicating the original index and the window used. 

```{r create_indexvolatility}
  ex_indexvolatility <- calcVolatility(index = ex_hpiindex,
                                       window = 5)

```

```{r class_indexvolatility}
  class(ex_indexvolatility)

```

```{r str_indexvolatility}
  str(ex_indexvolatility)
  
```

The `indexvolatility` object can be nested within an `hpiindex` object by setting **in_place = TRUE**. 

```{r vol_inplace}
  temp_index <- calcVolatility(index = ex_hpiindex,
                               window = 3, 
                               in_place = TRUE)

```

```{r class_volinplace1}
  class(temp_index)

```

```{r class_volinplace2}
  class(temp_index$volatility)

```

```{r str_volinplace}
  str(temp_index, max.level=1, give.attr=FALSE)

```

Volatility plots can be saved in objects of class `plotvolatility`, inheriting from `gg` and `ggplot`

```{r create_volplot}
  ex_plotvolatility <- plot(ex_indexvolatility)

```

```{r class_volplot}
  class(ex_plotvolatility)
 
```

#### Accuracy (Fitting)

Calculating an index's (fitting) accuracy through either **insample** or **kfold** (out of sample) methods via `calcAccuracy()` returns an object of class `hpiaccuracy`, inheriting from `data.frame`.  These object contain four fields, shown below.  In `hpiaccuracy` objects, each observation is that is being tested for accuracy is only found once.  This differs from the `seriesaccuracy` objects which are discussed later in which an observation may be tested against an index for each index in the series and therefore may appear multiple times in the `seriesaccuracy` object.  

```{r create_hpiaccr}
  ex_hpiaccuracy <- calcAccuracy(hpi_obj = ex_hpi,
                                 test_type = 'rt',
                                 test_method = 'insample')
```

```{r class_hpiaccr}
  class(ex_hpiaccuracy)

```

```{r str_hpiaccr}
  str(ex_hpiaccuracy)
  
```

`hpiaccuracy` objects can be added directly to an `hpi` object with the **in_place = TRUE** argument.^[Accuracy results are added to `hpi` objects and not `hpindex` object because they require data that is outside of the `hpiindex` object and therefore relate to the hpi collection more than just the index.] 

```{r hpia_inplace}
  temp_hpi <- calcAccuracy(hpi_obj = ex_hpi,
                           test_type = 'rt',
                           test_method = 'insample',
                           in_place = TRUE)
```

```{r class_hpia_inplace1}
  class(temp_hpi)

```

```{r class_hpia_inplace2}
  class(temp_hpi$accuracy)

```

```{r str_hpia_inplace}
  str(temp_hpi, max.level=1, give.attr=FALSE)

```

An `hpiaccuracy` object can be plotted and saved to a `plotaccuracy` object, but need the `return_plot=TRUE` argument to return to an object. 

```{r create_plotaccr, fig.keep='none'}
  ex_plotaccuracy <- plot(ex_hpiaccuracy, return_plot = TRUE)

```

```{r class_plotaccr}
  class(ex_plotaccuracy)
 
```

#### Series

A series of `hpi` objects are created with `createSeries()`.  This results in a `serieshpi` object, with two initial slots: **\$data** (`hpidata` object) and **\$hpis** a list of `hpi` objects (minus the data component which has been removed to avoid duplication.)  

```{r create_serieshpi}

  ex_serieshpi <- createSeries(hpi_obj = ex_hpi,
                               train_period = 48,
                               max_period = 60)
```

```{r class_serieshpi}
  class(ex_serieshpi)

```

```{r str_serieshpi}
  str(ex_serieshpi, max.level=1)
 
```

Series can be plotted and saved into a `plotseries` object. 

```{r create_plotserieshpi}
  ex_plotseries <- plot(ex_serieshpi)

```

```{r class_plotserieshpi}
  class(ex_plotseries)
 
```

#### Revision

The revision of a series is calculated with `calcRevision()` and returns an object of class `seriesrevision`.  This object contains a `data.frame` of revision by period and median and mean summaries of overall revision levels. 

```{r create_seriesrevision}
  ex_seriesrevision <- calcRevision(series_obj = ex_serieshpi)

```

```{r class_seriesrevision}
  class(ex_seriesrevision)
  
```

```{r str_seriesrevision}  
  str(ex_seriesrevision)
 
```

To add the revision to the `serieshpi` object, use **in_place = TRUE**.  

```{r srev_inplace}
  temp_series <- calcRevision(series_obj = ex_serieshpi,
                              in_place = TRUE)

```

```{r class_srev_inplace1}
  class(temp_series)

```

```{r class_srev_inplace2}
  class(temp_series$revision)

```

```{r str_srev_inplace}
  str(temp_series, max.level=1)

```

Plotting revisions can be saved to a `plotrevision` object.

```{r create_plotrevision}
  ex_plotrevision <- plot(ex_seriesrevision)

```

```{r class_plotrevision}
  class(ex_plotrevision)
 
```

### Series Accuracy

Finally, accuracy can be calculated at the series level by providing a `serieshpi` object to `calcSeriesAccuracy()`, resulting in a `seriesaccuracy` object.  `seriesaccuracy` objects look nearly identical to `hpiaccuracy` objects, however they differ in two respects: 1) they may include estimate of accuracy for the same observation multiple times ^[This will **not** happen only when using a test_method of type "forecast" and a "forecast_length" of 1.]; 2) they will have a **series** field, indicating from which index in the series the accuracy estimate is derived. 

Using **test_method = 'forecast'** will create a true, prediction-type test of accuracy (out of sample and into the future), where **kfold** is out of sample (but with knowledge of the future) and **insample** is just a simple fitting measure. 

```{r create_seriesaccr}
  ex_seriesaccuracy <- calcSeriesAccuracy(series_obj = ex_serieshpi,
                                          test_method = 'insample',
                                          test_type = 'rt')

```

```{r class_seriesaccr}
  class(ex_seriesaccuracy)

```

```{r str_seriesaccr}
  str(ex_seriesaccuracy)

```  
  
This object can be added directly to the `serieshpi` object by using the **in_place = TRUE** argument.

```{r create_sainplace}
  temp_series <- calcSeriesAccuracy(series_obj = ex_serieshpi,
                                    test_method = 'insample',
                                    test_type = 'rt',
                                    in_place=TRUE)

```

```{r class_sainplace}
  class(temp_series)

```

```{r class_sainplace2}
  class(temp_series$accuracy)

```

```{r str_sainplace}
  str(temp_series, max.level=1)
  
``` 

Finally, `seriesaccuracy` objects can be saved to a plot of class `plotaccuracy`

```{r create_plotsaccuracy, fig.keep='none'}
  ex_plotaccuracy <- plot(ex_seriesaccuracy, return_plot = TRUE)

```

```{r class_plotsaccuracy}
  class(ex_plotaccuracy)
 
```

For more information on using the above functions please see the **"Introduction"** Vignette also provided with this package.  
