library(flexdashboard)
library(tidyverse)
library(madstork)
library(highcharter)
library(formattable)
library(lubridate)
library(knitr)
library(xts)

port <- params$port
name <- capitalize(gsub("-|_", " ", port$name))

Summary

Column {data-width=650}

Portfolio Performance

mv <- get_market_value(port)


highchart(type = "stock", height = 900) %>% 
  hc_yAxis_multiples(
    create_yaxis(3, height = c(3, 2, 2), turnopposite = TRUE)
  ) %>% 
  hc_add_series_times_values(dates = mv$date,
                             values = mv$net_value,
                             color = as.character(madstork_cols("dark grey")),
                             name = "Net Value",
                             id = "netvalue",
                             type = "line",
                             yAxis = 0) %>% 
  hc_add_series_times_values(dates = mv$date,
                             values = mv$investments_value,
                             color = as.character(madstork_cols("orange")),
                             name = "Investments",
                             fillOpacity = .5,
                             type = "line",
                             yAxis = 1) %>%
  hc_add_series_times_values(dates = mv$date,
                             values = mv$cash,
                             color = as.character(madstork_cols("dark blue")),
                             name = "Cash",
                             fillOpacity = .5,
                             type = "line",
                             yAxis = 2) %>% 
  hc_tooltip(shared = TRUE) %>% 
  hc_tooltip( pointFormat = '{series.name}: ${point.y:,.0f}</span><br/>') %>%
  hc_plotOptions(area = list(
    dataLabels = list(enabled = FALSE),
    enableMouseTracking = TRUE)
  ) %>% 
  hc_add_theme(hc_theme_smpl()) %>% 
  hc_title(text = "Portfolio Performance Chart") %>% 
  hc_subtitle(text = name)

Column {data-width=350}

Summary

knitr::kable(
  c("last updated" = as.character(max(port$market_value$last_updated)),
    "initialized on" = as.character(port$date_initialized),
    "created on" = as.character(port$date_created)),
  col.names = port$name)

Market Value

get_market_value(port) %>% 
  filter(date == max(date)) %>% 
  filter(last_updated == max(last_updated)) %>% 
  select(net_value, investments_value, cash) %>%
  gather(metric, amount) %>% 
  formattable(.,
              list(amount = formatter("span",
                                      style = x ~ style(color = madstork_cols("dark blue"),
                                                        font.weight = "bold"),
                                      x ~ currency(x, digits = 0))))

Annual Income

port$holdings_market_value %>% 
  summarise(investments_annual_income = sum(annual_income)) %>% 
  mutate(tax_liability = get_tax_liability(port),
         net_income = investments_annual_income - tax_liability) %>% 
  rename(annual_income = investments_annual_income) %>% 
  gather(metric, amount) %>% 
  formattable(.,
              list(amount = formatter("span",
                                      style = x ~ style(color = madstork_cols("orange"),
                                                        font.weight = "bold"),
                                      x ~ currency(x, digits = 0))))

Portfolio Returns

bind_rows(
  get_portfolio_returns(port, today() - days(1) - hours(1)),
  get_portfolio_returns(port, today() - weeks(1) - hours(1)),
  get_portfolio_returns(port, today() - months(1) - hours(1)),
  get_portfolio_returns(port, floor_date(today(), unit = "year")),
  get_portfolio_returns(port, today() -years(1) - hours(1))
) %>% 
  mutate(period = c("day", "week", "month", "ytd", "year")) %>% 
  gather(metric, value, -period) %>%
  spread(period, value = value) %>% 
  select(metric, day, week, month, ytd, year) %>% 
  formattable(.,
              list(
                day = formatter("span",
                                style = x ~ style(color = case_when(x > 0 ~ "green",
                                                                    x == 0 ~ "grey",
                                                                    TRUE ~ "red")),
                                x ~ icontext(case_when(x > 0 ~ "arrow-up",
                                                       x == 0 ~ "arrow", 
                                                       TRUE ~ "arrow-down"), percent(x))),
                week = formatter("span",
                                 style = x ~ style(color = case_when(x > 0 ~ "green",
                                                                     x == 0 ~ "grey",
                                                                     TRUE ~ "red")),
                                 x ~ icontext(case_when(x > 0 ~ "arrow-up",
                                                        x == 0 ~ "arrow", 
                                                        TRUE ~ "arrow-down"), percent(x))),
                month = formatter("span",
                                  style = x ~ style(color = case_when(x > 0 ~ "green",
                                                                      x == 0 ~ "grey",
                                                                      TRUE ~ "red")),
                                  x ~ icontext(case_when(x > 0 ~ "arrow-up",
                                                         x == 0 ~ "arrow", 
                                                         TRUE ~ "arrow-down"), percent(x))),
                ytd = formatter("span",
                                style = x ~ style(color = case_when(x > 0 ~ "green",
                                                                    x == 0 ~ "grey",
                                                                    TRUE ~ "red")),
                                x ~ icontext(case_when(x > 0 ~ "arrow-up",
                                                       x == 0 ~ "arrow", 
                                                       TRUE ~ "arrow-down"), percent(x))),
                year = formatter("span",
                                 style = x ~ style(color = case_when(x > 0 ~ "green",
                                                                     x == 0 ~ "grey",
                                                                     TRUE ~ "red")),
                                 x ~ icontext(case_when(x > 0 ~ "arrow-up",
                                                        x == 0 ~ "arrow", 
                                                        TRUE ~ "arrow-down"), percent(x)))
              ))

Holdings

Column {data-width=1000, .tabset}

Holdings Summary

holdings <- get_holdings_market_value(port)
DT::datatable(
  holdings[, -1],
  caption = paste("Last updated on", as.character(holdings[1,1])),
  options = list(
    pageLength = 20,
    lengthMenu = c(10, 20),
    order = list(list(5, 'desc')))) %>%
  DT::formatCurrency(c('market_value', 'cost_basis', "unrealized_gain",
                       "dividend", "annual_income")) %>%
  DT::formatRound(c("price"), 2) %>% 
  DT::formatPercentage(c('yield', 'investments_share', "portfolio_share"), 2)

Portfolio Allocation

df <- get_symbol_portfolio_share(port) %>% 
  arrange(-portfolio_share) %>% 
  rename(y = portfolio_share, name = symbol) %>% 
  mutate(y = round(y*100,1))


highchart() %>%
  hc_title(text = "", style = list(fontSize = "4px")) %>% 
  hc_add_series_labels_values(df$name, df$y,
                              type = "pie",  size = '100%', innerSize = "50%",
                              dataLabels = list(distance = -40, 
                                                color = '#ffffff')) %>% 
  hc_tooltip( pointFormat = '{point.y:.1f}%</span><br/>')

Activity

activity <- get_activity(port)
if(nrow(activity)  > 0) {
  DT::datatable(
    activity,
    options = list(
      pageLength = 20,
      lengthMenu = c(10, 20), 
      order = list(list(2, 'desc'))),
    rownames = FALSE,
    filter = 'top') %>% 
    DT::formatCurrency(c("amount"))
}

Cashflow

Column {data-width=650}

Cashflow Chart

port_income <- port$income %>%
  mutate_at(c("date_added", "transaction_date"), as.Date) %>% 
  group_by(month = ceiling_date(transaction_date, unit = "month") - days(1)) %>%
  summarise(income = sum(amount))


port_flows <- port$activity %>% 
  mutate_at(c("date_added", "transaction_date"), as.Date) %>% 
  filter(type %in% c("deposit"),
         ! grepl("trade_id", desc)) %>% 
  group_by(month = ceiling_date(transaction_date, unit = "month") - days(1)) %>%
  summarise(deposits = sum(amount)) %>% 
  full_join(
    port$activity %>% 
      mutate_at(c("date_added", "transaction_date"), as.Date) %>% 
      filter(type %in% c("fee", "withdraw"), 
             ! grepl("trade_id", desc)) %>% 
      group_by(month = ceiling_date(transaction_date, unit = "month") - days(1)) %>%
      summarise(outflows = sum(amount)) ,
    by = "month") %>% 
  replace_na(list(deposits = 0, outflows = 0))


port_cash <- port$market_value %>% 
  group_by(month = as.Date(ceiling_date(date, unit = "month")) - days(1)) %>% 
  filter(date == max(date)) %>% 
  filter(last_updated == max(last_updated)) %>% 
  ungroup() %>% 
  select(month, cash)


highchart(height = 850) %>% 
  hc_xAxis(type = "datetime") %>%
  hc_chart(type = "area", zoomType = "xy") %>%
  hc_tooltip(shared = TRUE) %>% 
  hc_tooltip(pointFormat = '{series.name}: ${point.y:.0f}</span><br/>') %>% 
  hc_yAxis_multiples(create_yaxis(3, height = c(.40, .30, .30), turnopposite = TRUE)) %>% 
  hc_add_series(xts(port_income$income, order.by = port_income$month),
                yAxis = 0, 
                name = "Income",
                type = "column",
                color = madstork_colors["light blue"][[1]]) %>% 
  hc_add_series(xts(port_flows$deposits, order.by = port_flows$month),
                yAxis = 1, 
                name = "Inflows",
                type = "column",
                color = "green")%>% 
  hc_add_series(xts(port_flows$outflows, order.by = port_flows$month),
                yAxis = 1, 
                name = "Outflows",
                type = "column",
                color = madstork_colors["orange"][[1]]) %>% 
  hc_add_series(xts(port_cash$cash, order.by = port_cash$month),
                yAxis = 2, 
                name = "Cash Balance",
                type = "line",
                color = madstork_colors["dark blue"][[1]]) %>% 
  hc_plotOptions(area = list(
    dataLabels = list(enabled = FALSE),
    enableMouseTracking = TRUE)
  ) %>% 
  hc_add_theme(hc_theme_smpl()) %>% 
  hc_title(text = "MadStork Portfolio Income & Cashflow Chart") %>% 
  hc_subtitle(text = name)

Column {data-width=350, .tabset}

Monthly Cashflow Summary

port_flows %>% 
  full_join(
    port_income,
    by = "month"
  ) %>% 
  replace_na(list(income = 0, deposits = 0, outflows = 0)) %>% 
  arrange(month) %>% 
  mutate(month = format(month, '%b-%y'),
         net = income + deposits - outflows) %>% 
  formattable(.,
              list(income = formatter("span", x ~ currency(x, digits = 0)),
                   deposits = formatter("span", x ~ currency(x, digits = 0)),
                   outflows = formatter("span", x ~ currency(x, digits = 0)),
                   net = formatter("span", 
                                   style = x ~ style(color = case_when(x > 0 ~ "green",
                                                                       x < 0 ~ "red",
                                                                       TRUE ~ "grey")),
                                   x ~  currency(x, digits = 0))))

Income Activity

port$income %>% 
  select(id, transaction_date, type, symbol, amount) %>% 
  DT::datatable(.,
                caption = "Income Activity",
                rownames = FALSE,
                filter = "top",
                options = list(
                  pageLength = 20,
                  lengthMenu = c(10, 20),
                  order = list(list(1, 'desc')))) %>%
  DT::formatCurrency(c("amount")) 


chrishaarstick/madstork documentation built on Jan. 3, 2022, 8:34 p.m.