From 3b1de2a0a53898fa2ccf002721977411cea93cf2 Mon Sep 17 00:00:00 2001
From: Bergant <darko.bergant@adacta.si>
Date: Mon, 30 Mar 2015 00:58:50 +0200
Subject: [PATCH] calculation

calculation
---
 NAMESPACE              |   2 +
 R/finstr.R             |  31 ++++-
 R/finstr_print.R       |  28 +++-
 README.Rmd             |  68 ++++++++--
 man/calculate.Rd       |   4 +-
 man/calculation.Rd     |  18 +++
 man/do_calculation.Rd  |  20 +++
 readme.md              | 290 +++++++++++++++++++++++++----------------
 vignettes/Overview.Rmd |  65 +++++++--
 9 files changed, 382 insertions(+), 144 deletions(-)
 create mode 100644 man/calculation.Rd
 create mode 100644 man/do_calculation.Rd

diff --git a/NAMESPACE b/NAMESPACE
index eb0bbe1..73da535 100644
--- a/NAMESPACE
+++ b/NAMESPACE
@@ -8,6 +8,8 @@ S3method(print,elements)
 S3method(print,statement)
 S3method(print,statements)
 export(calculate)
+export(calculation)
+export(do_calculation)
 export(get_elements)
 export(get_elements_h)
 export(xbrl_get_relations)
diff --git a/R/finstr.R b/R/finstr.R
index 761093c..d8429b5 100644
--- a/R/finstr.R
+++ b/R/finstr.R
@@ -353,7 +353,7 @@ get_elements <- function(x, parent_id = NULL, all = TRUE) {
   # if parent_id provided, only descendands from this elements are returned
 
   if( !"statement" %in% class(x)  ) {
-    strop("Not a statement class")
+    stop("Not a statement class")
   }
   
   elements <- attr(x, "elements")
@@ -477,6 +477,7 @@ merge.statements <- function(x, y, ...) {
 #' 
 #' @param x a statement object
 #' @param ... list of formulas
+#' @param digits if specified the results will be rounded according to number of digits
 #' @examples
 #' \dontrun{
 #' 
@@ -492,14 +493,36 @@ merge.statements <- function(x, y, ...) {
 #' )
 #' }
 #' @export
-calculate <- function(x, ...) {
+calculate <- function(x, ..., digits = NULL) {
 
   #dplyr::transmute_(x, endDate = ~endDate, .dots = lazyeval::lazy_dots(...))
-  dplyr::transmute_(x, endDate = ~endDate, .dots = lazyeval::lazy_dots(...)) %>%
+  res <- 
+    dplyr::transmute_(x, date = ~endDate, .dots = lazyeval::lazy_dots(...)) %>%
     dplyr::select(everything(), -matches("^\\."))
-  
+  if(!missing(digits)) {
+    res[,2:ncol(res)] <- round(res[,2:ncol(res)], digits) 
+  }
+  return(res)
+}
+
+#' Define calculation
+#' @param ... formulas
+#' @seealso \code{\link{do_calculation}}
+#' @export
+calculation <- function(...) {
+  lazyeval::lazy(calculate(x, ...)) 
+}
+
+#' Run the calculation
+#' @param x statement object
+#' @param calculation a calculation expression
+#' @seealso \code{\link{calculation}}
+#' @export
+do_calculation <- function(x, calculation) {
+  lazyeval::lazy_eval(calculation, list(x = x))
 }
 
+
 #' Statement lagged differences
 #' 
 #' @param x a statement to be differenced
diff --git a/R/finstr_print.R b/R/finstr_print.R
index f0cd9d7..9827a8d 100644
--- a/R/finstr_print.R
+++ b/R/finstr_print.R
@@ -45,8 +45,6 @@ print.statement <- function(x, ...) {
   cat( "Financial statement: ")
   cat( nrow(x), "observations from", min(x$endDate),"to",max(x$endDate), "\n")
   cat("Numbers in ", paste(rep("0", -decimals), collapse = ""), "\n")
-  
-  
 
   concepts <- names(x)[5:ncol(x)]
   values <- as.data.frame( t(x[, concepts] * 10^decimals))
@@ -54,7 +52,31 @@ print.statement <- function(x, ...) {
   if(ncol(values)>1) {
     values <- values[,ncol(values):1]
   }
-  row.names(values) <- substring(row.names(values), 1, 50)
+  
+  # names
+  elements <- get_elements(x)
+  r_names <- row.names(values)
+  el_pos <- which(elements$elementId %in% r_names )
+  #fill_dots <- paste0(rep(". ", max(elements$level)), collapse = "")
+  fill_dots <- paste0(rep("  ", max(elements$level)), collapse = "")
+  parent_pos <- match(elements$parentId, elements$elementId)
+  r_names <- 
+    paste0( 
+      substring(fill_dots,1, (elements[["level"]][el_pos]-1)*2-2),
+      ifelse( 
+        is.na(elements[["balance"]][parent_pos]), 
+        "",
+        ifelse(
+          elements[["balance"]][el_pos] == elements[["balance"]][parent_pos],
+          "+ ", "- "
+        )
+      ),
+      r_names,
+      ifelse(elements[["level"]][el_pos] < elements[["level"]][el_pos+1],
+             " = ", "")
+    )
+
+  row.names(values) <- substring(r_names, 1, 50)
 
   x <- values
   NextMethod(object = x, right = FALSE, ...)
diff --git a/README.Rmd b/README.Rmd
index 71677d9..96d420a 100644
--- a/README.Rmd
+++ b/README.Rmd
@@ -6,6 +6,7 @@ output:
 ---
 
 
+
 ```{r, echo=FALSE, results='hide', message=FALSE }
 library(dplyr)
 library(tidyr)
@@ -63,23 +64,23 @@ To get a single *statement* use *statements* object as a regular R list:
 ```{r statement}
 balance_sheet2013 <- st2013$StatementOfFinancialPositionClassified
 balance_sheet2014 <- st2014$StatementOfFinancialPositionClassified
+income2013 <- st2013$StatementOfIncome
+income2014 <- st2014$StatementOfIncome
 balance_sheet2014
+income2014
 ```
 
 
 Information about hierarchical structure of elements (concepts) is stored 
 as an attribute to the statement object.
 
-To see the calculation hierarchy of elements use `get_elements`: 
+To get more data about the concepts used in the statement call `get_elements`: 
 ```{r relations}
-get_elements(balance_sheet2014)
+bs_els <- get_elements(balance_sheet2014)
 ```
 
-To query the fundamental elements from higher order elements use
-`get_elements`:
-```{r elements}
-get_elements(balance_sheet2014, parent_id = "LiabilitiesCurrent")
-```
+Elements store concept descriptions, balance attribute (debit/credit) and 
+parent/child relationships between concepts.
 
 ## Merge statements from different periods
 Use `merge` function to create single financial statement data from two 
@@ -88,9 +89,9 @@ statements.
 balance_sheet <- merge( balance_sheet2013, balance_sheet2014 )
 ```
 
-The structure of merged balance sheets may differ because of changes in XBRL
-taxonomy. 
-Function `merge` takes care of it by expanding the element 
+The structure of merged balance sheets may differ if XBRL
+taxonomy changed. 
+Function `merge` takes care of it by expanding the elements 
 hierarchy to fit both statements. 
 The values of any missing elements is set to 0.
 
@@ -98,7 +99,7 @@ To merge all statements from *statements* object use merge on statements objects
 ```{r merge_statements}
 # merge all statements
 st_all <- merge( st2013, st2014 )
-# check if balance sheets are merged:
+# check if blance sheets are merged:
 balance_sheet <- st_all$StatementOfFinancialPositionClassified
 ```
 
@@ -167,6 +168,51 @@ balance_sheet %>%
 The leading dot instructs the calculate function to hide the value. In our case
 only DaysSalesOutstanding is selected in final result.
 
+Use digits parameter to control rounding:
+
+```{r income}
+
+
+st_all$StatementOfIncome %>% calculate( digits = 2,
+
+  Gross_Margin = 
+    (SalesRevenueNet -  CostOfGoodsAndServicesSold) / SalesRevenueNet,
+
+  Operating_Margin =
+    OperatingIncomeLoss / SalesRevenueNet,
+
+  Net_Margin = 
+    NetIncomeLoss / SalesRevenueNet
+
+  ) 
+
+```
+
+When running same calculation for different statements, store the
+calculation with `calculation` and run with `do_calculation`:
+```{r calculation}
+# define calculation
+profit_margins <- calculation(
+  
+  Gross_Margin = 
+    (SalesRevenueNet -  CostOfGoodsAndServicesSold) / SalesRevenueNet,
+  
+  Operating_Margin =
+    OperatingIncomeLoss / SalesRevenueNet,
+  
+  Net_Margin = 
+    NetIncomeLoss / SalesRevenueNet,
+  
+  digits = 3
+)
+
+# run profit margins for two different statements
+income2013 %>% do_calculation(profit_margins)
+income2014 %>% do_calculation(profit_margins)
+
+```
+
+
 ##Lagged difference
 To calculate lagged difference for entire statement use `diff` function.
 The result is statement of changes between successive years:
diff --git a/man/calculate.Rd b/man/calculate.Rd
index 0273b19..b2ccfe6 100644
--- a/man/calculate.Rd
+++ b/man/calculate.Rd
@@ -4,12 +4,14 @@
 \alias{calculate}
 \title{Calculate formulas}
 \usage{
-calculate(x, ...)
+calculate(x, ..., digits = NULL)
 }
 \arguments{
 \item{x}{a statement object}
 
 \item{...}{list of formulas}
+
+\item{digits}{if specified the results will be rounded according to number of digits}
 }
 \description{
 Calculate formulas
diff --git a/man/calculation.Rd b/man/calculation.Rd
new file mode 100644
index 0000000..949db4e
--- /dev/null
+++ b/man/calculation.Rd
@@ -0,0 +1,18 @@
+% Generated by roxygen2 (4.1.0): do not edit by hand
+% Please edit documentation in R/finstr.R
+\name{calculation}
+\alias{calculation}
+\title{Define calculation}
+\usage{
+calculation(...)
+}
+\arguments{
+\item{...}{formulas}
+}
+\description{
+Define calculation
+}
+\seealso{
+\code{\link{do_calculation}}
+}
+
diff --git a/man/do_calculation.Rd b/man/do_calculation.Rd
new file mode 100644
index 0000000..55aad3c
--- /dev/null
+++ b/man/do_calculation.Rd
@@ -0,0 +1,20 @@
+% Generated by roxygen2 (4.1.0): do not edit by hand
+% Please edit documentation in R/finstr.R
+\name{do_calculation}
+\alias{do_calculation}
+\title{Run the calculation}
+\usage{
+do_calculation(x, calculation)
+}
+\arguments{
+\item{x}{statement object}
+
+\item{calculation}{a calculation expression}
+}
+\description{
+Run the calculation
+}
+\seealso{
+\code{\link{calculation}}
+}
+
diff --git a/readme.md b/readme.md
index fce43d3..a5f037c 100644
--- a/readme.md
+++ b/readme.md
@@ -3,6 +3,7 @@
 
 
 
+
 **Warning: finstr package is in development. 
 Please use with caution.**
 
@@ -64,100 +65,91 @@ To get a single *statement* use *statements* object as a regular R list:
 ```r
 balance_sheet2013 <- st2013$StatementOfFinancialPositionClassified
 balance_sheet2014 <- st2014$StatementOfFinancialPositionClassified
+income2013 <- st2013$StatementOfIncome
+income2014 <- st2014$StatementOfIncome
 balance_sheet2014
 ```
 
 ```
 ## Financial statement: 2 observations from 2013-09-28 to 2014-09-27 
 ## Numbers in  000000 
-##                                                 2014-09-27 2013-09-28
-## Assets                                          231839     207000    
-## AssetsCurrent                                    68531      73286    
-## CashAndCashEquivalentsAtCarryingValue            13844      14259    
-## AvailableForSaleSecuritiesCurrent                11233      26287    
-## AccountsReceivableNetCurrent                     17460      13102    
-## InventoryNet                                      2111       1764    
-## DeferredTaxAssetsNetCurrent                       4318       3453    
-## NontradeReceivablesCurrent                        9759       7539    
-## OtherAssetsCurrent                                9806       6882    
-## AvailableForSaleSecuritiesNoncurrent            130162     106215    
-## PropertyPlantAndEquipmentNet                     20624      16597    
-## Goodwill                                          4616       1577    
-## IntangibleAssetsNetExcludingGoodwill              4142       4179    
-## OtherAssetsNoncurrent                             3764       5146    
-## LiabilitiesAndStockholdersEquity                231839     207000    
-## Liabilities                                     120292      83451    
-## LiabilitiesCurrent                               63448      43658    
-## AccountsPayableCurrent                           30196      22367    
-## AccruedLiabilitiesCurrent                        18453      13856    
-## DeferredRevenueCurrent                            8491       7435    
-## CommercialPaper                                   6308          0    
-## DeferredRevenueNoncurrent                         3031       2625    
-## LongTermDebt                                     28987      16960    
-## OtherLiabilitiesNoncurrent                       24826      20208    
-## CommitmentsAndContingencies                          0          0    
-## StockholdersEquity                              111547     123549    
-## CommonStocksIncludingAdditionalPaidInCapital     23313      19764    
-## RetainedEarningsAccumulatedDeficit               87152     104256    
-## AccumulatedOtherComprehensiveIncomeLossNetOfTax   1082       -471
+##                                                    2014-09-27 2013-09-28
+## Assets =                                           231839     207000    
+## + AssetsCurrent =                                   68531      73286    
+##   + CashAndCashEquivalentsAtCarryingValue           13844      14259    
+##   + AvailableForSaleSecuritiesCurrent               11233      26287    
+##   + AccountsReceivableNetCurrent                    17460      13102    
+##   + InventoryNet                                     2111       1764    
+##   + DeferredTaxAssetsNetCurrent                      4318       3453    
+##   + NontradeReceivablesCurrent                       9759       7539    
+##   + OtherAssetsCurrent                               9806       6882    
+## + AvailableForSaleSecuritiesNoncurrent             130162     106215    
+## + PropertyPlantAndEquipmentNet                      20624      16597    
+## + Goodwill                                           4616       1577    
+## + IntangibleAssetsNetExcludingGoodwill               4142       4179    
+## + OtherAssetsNoncurrent                              3764       5146    
+## LiabilitiesAndStockholdersEquity =                 231839     207000    
+## + Liabilities =                                    120292      83451    
+##   + LiabilitiesCurrent =                            63448      43658    
+##     + AccountsPayableCurrent                        30196      22367    
+##     + AccruedLiabilitiesCurrent                     18453      13856    
+##     + DeferredRevenueCurrent                         8491       7435    
+##     + CommercialPaper                                6308          0    
+##   + DeferredRevenueNoncurrent                        3031       2625    
+##   + LongTermDebt                                    28987      16960    
+##   + OtherLiabilitiesNoncurrent                      24826      20208    
+## + CommitmentsAndContingencies                           0          0    
+## + StockholdersEquity =                             111547     123549    
+##   + CommonStocksIncludingAdditionalPaidInCapital    23313      19764    
+##   + RetainedEarningsAccumulatedDeficit              87152     104256    
+##   + AccumulatedOtherComprehensiveIncomeLossNetOfTa   1082       -471
+```
+
+```r
+income2014
+```
+
+```
+## Financial statement: 3 observations from 2012-09-29 to 2014-09-27 
+## Numbers in  000000 
+##                                                    2014-09-27 2013-09-28
+## NetIncomeLoss =                                     39510      37037    
+## + IncomeLossFromContinuingOperationsBeforeIncomeTa  53483      50155    
+##   + OperatingIncomeLoss =                           52503      48999    
+##     + GrossProfit =                                 70537      64304    
+##       + SalesRevenueNet                            182795     170910    
+##       - CostOfGoodsAndServicesSold                 112258     106606    
+##     - OperatingExpenses =                           18034      15305    
+##       + ResearchAndDevelopmentExpense                6041       4475    
+##       + SellingGeneralAndAdministrativeExpense      11993      10830    
+##   + NonoperatingIncomeExpense                         980       1156    
+## - IncomeTaxExpenseBenefitNA                         13973      13118    
+##                                                    2012-09-29
+## NetIncomeLoss =                                     41733    
+## + IncomeLossFromContinuingOperationsBeforeIncomeTa  55763    
+##   + OperatingIncomeLoss =                           55241    
+##     + GrossProfit =                                 68662    
+##       + SalesRevenueNet                            156508    
+##       - CostOfGoodsAndServicesSold                  87846    
+##     - OperatingExpenses =                           13421    
+##       + ResearchAndDevelopmentExpense                3381    
+##       + SellingGeneralAndAdministrativeExpense      10040    
+##   + NonoperatingIncomeExpense                         522    
+## - IncomeTaxExpenseBenefitNA                         14030
 ```
 
 
 Information about hierarchical structure of elements (concepts) is stored 
 as an attribute to the statement object.
 
-To see the calculation hierarchy of elements use `get_elements`: 
+To get more data about the concepts used in the statement call `get_elements`: 
 
 ```r
-get_elements(balance_sheet2014)
-```
-
-```
-## Assets 
-## ..AssetsCurrent 
-## ....CashAndCashEquivalentsAtCarryingValue 
-## ....AvailableForSaleSecuritiesCurrent 
-## ....AccountsReceivableNetCurrent 
-## ....InventoryNet 
-## ....DeferredTaxAssetsNetCurrent 
-## ....NontradeReceivablesCurrent 
-## ....OtherAssetsCurrent 
-## ..AvailableForSaleSecuritiesNoncurrent 
-## ..PropertyPlantAndEquipmentNet 
-## ..Goodwill 
-## ..IntangibleAssetsNetExcludingGoodwill 
-## ..OtherAssetsNoncurrent 
-## LiabilitiesAndStockholdersEquity 
-## ..Liabilities 
-## ....LiabilitiesCurrent 
-## ......AccountsPayableCurrent 
-## ......AccruedLiabilitiesCurrent 
-## ......DeferredRevenueCurrent 
-## ......CommercialPaper 
-## ....DeferredRevenueNoncurrent 
-## ....LongTermDebt 
-## ....OtherLiabilitiesNoncurrent 
-## ..CommitmentsAndContingencies 
-## ..StockholdersEquity 
-## ....CommonStocksIncludingAdditionalPaidInCapital 
-## ....RetainedEarningsAccumulatedDeficit 
-## ....AccumulatedOtherComprehensiveIncomeLossNetOfTax
-```
-
-To query the fundamental elements from higher order elements use
-`get_elements`:
-
-```r
-get_elements(balance_sheet2014, parent_id = "LiabilitiesCurrent")
+bs_els <- get_elements(balance_sheet2014)
 ```
 
-```
-## ....LiabilitiesCurrent 
-## ......AccountsPayableCurrent 
-## ......AccruedLiabilitiesCurrent 
-## ......DeferredRevenueCurrent 
-## ......CommercialPaper
-```
+Elements store concept descriptions, balance attribute (debit/credit) and 
+parent/child relationships between concepts.
 
 ## Merge statements from different periods
 Use `merge` function to create single financial statement data from two 
@@ -167,9 +159,9 @@ statements.
 balance_sheet <- merge( balance_sheet2013, balance_sheet2014 )
 ```
 
-The structure of merged balance sheets may differ because of changes in XBRL
-taxonomy. 
-Function `merge` takes care of it by expanding the element 
+The structure of merged balance sheets may differ if XBRL
+taxonomy changed. 
+Function `merge` takes care of it by expanding the elements 
 hierarchy to fit both statements. 
 The values of any missing elements is set to 0.
 
@@ -178,7 +170,7 @@ To merge all statements from *statements* object use merge on statements objects
 ```r
 # merge all statements
 st_all <- merge( st2013, st2014 )
-# check if balance sheets are merged:
+# check if blance sheets are merged:
 balance_sheet <- st_all$StatementOfFinancialPositionClassified
 ```
 
@@ -228,7 +220,7 @@ balance_sheet %>% calculate(
 ```
 
 ```
-##      endDate Current_Ratio Quick_Ratio
+##         date Current_Ratio Quick_Ratio
 ## 1 2012-09-29      1.495849    1.039360
 ## 2 2013-09-28      1.678639    1.228824
 ## 3 2014-09-27      1.080113    0.670423
@@ -259,7 +251,7 @@ balance_sheet %>%
 ```
 
 ```
-##      endDate DaysSalesOutstanding
+##         date DaysSalesOutstanding
 ## 1 2012-09-29                   NA
 ## 2 2013-09-28             25.66169
 ## 3 2014-09-27             30.51268
@@ -268,6 +260,74 @@ balance_sheet %>%
 The leading dot instructs the calculate function to hide the value. In our case
 only DaysSalesOutstanding is selected in final result.
 
+Use digits parameter to control rounding:
+
+
+```r
+st_all$StatementOfIncome %>% calculate( digits = 2,
+
+  Gross_Margin = 
+    (SalesRevenueNet -  CostOfGoodsAndServicesSold) / SalesRevenueNet,
+
+  Operating_Margin =
+    OperatingIncomeLoss / SalesRevenueNet,
+
+  Net_Margin = 
+    NetIncomeLoss / SalesRevenueNet
+
+  ) 
+```
+
+```
+##         date Gross_Margin Operating_Margin Net_Margin
+## 1 2011-09-24         0.40             0.31       0.24
+## 2 2012-09-29         0.44             0.35       0.27
+## 3 2013-09-28         0.38             0.29       0.22
+## 4 2014-09-27         0.39             0.29       0.22
+```
+
+When running same calculation for different statements, store the
+calculation with `calculation` and run with `do_calculation`:
+
+```r
+# define calculation
+profit_margins <- calculation(
+  
+  Gross_Margin = 
+    (SalesRevenueNet -  CostOfGoodsAndServicesSold) / SalesRevenueNet,
+  
+  Operating_Margin =
+    OperatingIncomeLoss / SalesRevenueNet,
+  
+  Net_Margin = 
+    NetIncomeLoss / SalesRevenueNet,
+  
+  digits = 3
+)
+
+# run profit margins for two different statements
+income2013 %>% do_calculation(profit_margins)
+```
+
+```
+##         date Gross_Margin Operating_Margin Net_Margin
+## 1 2011-09-24        0.405            0.312      0.239
+## 2 2012-09-29        0.439            0.353      0.267
+## 3 2013-09-28        0.376            0.287      0.217
+```
+
+```r
+income2014 %>% do_calculation(profit_margins)
+```
+
+```
+##         date Gross_Margin Operating_Margin Net_Margin
+## 1 2012-09-29        0.439            0.353      0.267
+## 2 2013-09-28        0.376            0.287      0.217
+## 3 2014-09-27        0.386            0.287      0.216
+```
+
+
 ##Lagged difference
 To calculate lagged difference for entire statement use `diff` function.
 The result is statement of changes between successive years:
@@ -280,35 +340,35 @@ balance_sheet %>% diff()
 ```
 ## Financial statement: 2 observations from 2013-09-28 to 2014-09-27 
 ## Numbers in  000000 
-##                                                 2014-09-27 2013-09-28
-## Assets                                           24839      30936    
-## AssetsCurrent                                    -4755      15633    
-## CashAndCashEquivalentsAtCarryingValue             -415       3513    
-## AvailableForSaleSecuritiesCurrent               -15054       7904    
-## AccountsReceivableNetCurrent                      4358       2172    
-## InventoryNet                                       347        973    
-## DeferredTaxAssetsNetCurrent                        865        870    
-## NontradeReceivablesCurrent                        2220       -223    
-## OtherAssetsCurrent                                2924        424    
-## AvailableForSaleSecuritiesNoncurrent             23947      14093    
-## PropertyPlantAndEquipmentNet                      4027       1145    
-## Goodwill                                          3039        442    
-## IntangibleAssetsNetExcludingGoodwill               -37        -45    
-## OtherAssetsNoncurrent                            -1382       -332    
-## LiabilitiesAndStockholdersEquity                 24839      30936    
-## Liabilities                                      36841      25597    
-## LiabilitiesCurrent                               19790       5116    
-## AccountsPayableCurrent                            7829       1192    
-## AccruedLiabilitiesCurrent                         4597       2442    
-## DeferredRevenueCurrent                            1056       1482    
-## CommercialPaper                                   6308          0    
-## DeferredRevenueNoncurrent                          406        -23    
-## LongTermDebt                                     12027      16960    
-## OtherLiabilitiesNoncurrent                        4618       3544    
-## CommitmentsAndContingencies                          0          0    
-## StockholdersEquity                              -12002       5339    
-## CommonStockValue                                     0     -16422    
-## RetainedEarningsAccumulatedDeficit              -17104       2967    
-## AccumulatedOtherComprehensiveIncomeLossNetOfTax   1553       -970    
-## CommonStocksIncludingAdditionalPaidInCapital      3549      19764
+##                                                    2014-09-27 2013-09-28
+## Assets =                                            24839      30936    
+## + AssetsCurrent =                                   -4755      15633    
+##   + CashAndCashEquivalentsAtCarryingValue            -415       3513    
+##   + AvailableForSaleSecuritiesCurrent              -15054       7904    
+##   + AccountsReceivableNetCurrent                     4358       2172    
+##   + InventoryNet                                      347        973    
+##   + DeferredTaxAssetsNetCurrent                       865        870    
+##   + NontradeReceivablesCurrent                       2220       -223    
+##   + OtherAssetsCurrent                               2924        424    
+## + AvailableForSaleSecuritiesNoncurrent              23947      14093    
+## + PropertyPlantAndEquipmentNet                       4027       1145    
+## + Goodwill                                           3039        442    
+## + IntangibleAssetsNetExcludingGoodwill                -37        -45    
+## + OtherAssetsNoncurrent                             -1382       -332    
+## LiabilitiesAndStockholdersEquity =                  24839      30936    
+## + Liabilities =                                     36841      25597    
+##   + LiabilitiesCurrent =                            19790       5116    
+##     + AccountsPayableCurrent                         7829       1192    
+##     + AccruedLiabilitiesCurrent                      4597       2442    
+##     + DeferredRevenueCurrent                         1056       1482    
+##     + CommercialPaper                                6308          0    
+##   + DeferredRevenueNoncurrent                         406        -23    
+##   + LongTermDebt                                    12027      16960    
+##   + OtherLiabilitiesNoncurrent                       4618       3544    
+## + CommitmentsAndContingencies                           0          0    
+## + StockholdersEquity =                             -12002       5339    
+##   + CommonStockValue                                    0     -16422    
+##   + RetainedEarningsAccumulatedDeficit             -17104       2967    
+##   + AccumulatedOtherComprehensiveIncomeLossNetOfTa   1553       -970    
+##   + CommonStocksIncludingAdditionalPaidInCapitalNA   3549      19764
 ```
diff --git a/vignettes/Overview.Rmd b/vignettes/Overview.Rmd
index 0aca12c..2777b7b 100644
--- a/vignettes/Overview.Rmd
+++ b/vignettes/Overview.Rmd
@@ -66,23 +66,23 @@ To get a single *statement* use *statements* object as a regular R list:
 ```{r statement}
 balance_sheet2013 <- st2013$StatementOfFinancialPositionClassified
 balance_sheet2014 <- st2014$StatementOfFinancialPositionClassified
+income2013 <- st2013$StatementOfIncome
+income2014 <- st2014$StatementOfIncome
 balance_sheet2014
+income2014
 ```
 
 
 Information about hierarchical structure of elements (concepts) is stored 
 as an attribute to the statement object.
 
-To see the calculation hierarchy of elements use `get_elements`: 
+To get more data about the concepts used in the statement call `get_elements`: 
 ```{r relations}
-get_elements(balance_sheet2014)
+bs_els <- get_elements(balance_sheet2014)
 ```
 
-To query the fundamental elements from higher order elements use
-`get_elements`:
-```{r elements}
-get_elements(balance_sheet2014, parent_id = "LiabilitiesCurrent")
-```
+Elements store concept descriptions, balance attribute (debit/credit) and 
+parent/child relationships between concepts.
 
 ## Merge statements from different periods
 Use `merge` function to create single financial statement data from two 
@@ -91,9 +91,9 @@ statements.
 balance_sheet <- merge( balance_sheet2013, balance_sheet2014 )
 ```
 
-The structure of merged balance sheets may differ because of changes in XBRL
-taxonomy. 
-Function `merge` takes care of it by expanding the element 
+The structure of merged balance sheets may differ if XBRL
+taxonomy changed. 
+Function `merge` takes care of it by expanding the elements 
 hierarchy to fit both statements. 
 The values of any missing elements is set to 0.
 
@@ -170,6 +170,51 @@ balance_sheet %>%
 The leading dot instructs the calculate function to hide the value. In our case
 only DaysSalesOutstanding is selected in final result.
 
+Use digits parameter to control rounding:
+
+```{r income}
+
+
+st_all$StatementOfIncome %>% calculate( digits = 2,
+
+  Gross_Margin = 
+    (SalesRevenueNet -  CostOfGoodsAndServicesSold) / SalesRevenueNet,
+
+  Operating_Margin =
+    OperatingIncomeLoss / SalesRevenueNet,
+
+  Net_Margin = 
+    NetIncomeLoss / SalesRevenueNet
+
+  ) 
+
+```
+
+When running same calculation for different statements, store the
+calculation with `calculation` and run with `do_calculation`:
+```{r calculation}
+# define calculation
+profit_margins <- calculation(
+  
+  Gross_Margin = 
+    (SalesRevenueNet -  CostOfGoodsAndServicesSold) / SalesRevenueNet,
+  
+  Operating_Margin =
+    OperatingIncomeLoss / SalesRevenueNet,
+  
+  Net_Margin = 
+    NetIncomeLoss / SalesRevenueNet,
+  
+  digits = 3
+)
+
+# run profit margins for two different statements
+income2013 %>% do_calculation(profit_margins)
+income2014 %>% do_calculation(profit_margins)
+
+```
+
+
 ##Lagged difference
 To calculate lagged difference for entire statement use `diff` function.
 The result is statement of changes between successive years:
-- 
GitLab