---
title: "Taxstats 2015-16"
author: "Hugh Parsonage"
date: "2018-01-01"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Taxstats 2015-16}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

```{r no-run-vignette, include=FALSE}
if (!identical(Sys.getenv("R_GRATTAN_BUILD_MAIN_VIGNETTE"), "true")) {
  opts_hooks$set(inline = function(x) invisible(NULL))
  knit_hooks$set(inline = function(x) deparse(substitute(x)),
                 evaluate.inline = function(code, envir) {
                   deparse(substitute(code))
                 })
  
  opts_knit$set(eval = FALSE, error = TRUE, warning = FALSE)
  opts_chunk$set(eval = FALSE, error = TRUE, warning = FALSE)
}
```

```{r loadPackages}
library(data.table)
library(hutils)
library(magrittr)
library(ggplot2)

library(grattan)  # needs to be before require_taxstats.
has_taxstats <- 
  require_taxstats() &&
  require_taxstats1516()
```


```{r}
s1516 <- 
  as.data.table(sample_file_1516_synth) %>%
  setkey(Taxable_Income) %>%
  mutate_ntile("Taxable_Income", n = 100L) %>%
  mutate_ntile("Taxable_Income", n = 10L) 
s1516[, tax := income_tax(Taxable_Income, "2015-16", .dots.ATO = .SD)]

```


## Negative gearing

### Tax benefits

```{r}
s1516[, taxNoNG := income_tax(Taxable_Income - pminC(Net_rent_amt, 0), 
                              fy.year = "2015-16",
                              .dots.ATO = .SD)]
s1516[, benefit_due_NG := taxNoNG - tax]
```

#### by decile

```{r benefitsNG_by_Decile}
benefitsNG_by_Decile <- 
  s1516[, .(avgBenefitNG = mean(benefit_due_NG)), keyby = "Taxable_IncomeDecile"]

copy(benefitsNG_by_Decile) %>%
  setnames("Taxable_IncomeDecile", "Taxable Income Decile") %>%
  .[, Share := paste0(round(100 * avgBenefitNG / sum(avgBenefitNG)), "%")] %>%
  .[, avgBenefitNG := round(avgBenefitNG, -2)] %>%
  setnames("avgBenefitNG", "Average benefit from NG / $") %>%
  kable(align = "rrr")
```


### Average taxable income, by age and gender, 2015

```{r average-taxable-income-by-age-and-gender-2015}
s1516[, .(avgTaxableIncome = mean(Taxable_Income)), keyby = .(age_range, Gender)] %>%
  .[age_range_decoder, on = "age_range"] %>%
  .[, Sex := if_else(Gender == 1, "Female", "Male")] %>%
  ggplot(aes(x = age_range_description,
             y = avgTaxableIncome,
             group = Sex, 
             color = Sex)) + 
  geom_line() + 
  scale_y_continuous(labels = function(x) paste0("$", prettyNum(x, big.mark = ",")))
```




