---
title:
output:
  revealjs::revealjs_presentation:
    theme: white
    css: white-edits.css
    highlight: tango
    transition: slide
    self_contained: false
    reveal_plugins: ["chalkboard","search"]
    transitionSpead: fast
    mathjax: "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS_SVG"
    reveal_options:
      minScale: 1.0
      maxScale: 1.0
      width: 1536
      height: 864
      slideNumber: true
      controlsTutorial: true
      chalkboard:
        theme: whiteboard
        readOnly: false
---

## ACCT 101: Financial Statement Analysis {data-background-video="../Backgrounds/title.mp4" data-background-video-loop=true class="header no-toc-progress present-only" data-state="no-toc-progress"}

<!-- "reveal_plugins:..." and "chalkboard:" are handled by prep.py -->
```{r helpers, echo=FALSE, warning=FALSE, message=F}
library(knitr)
library(kableExtra)
html_df <- function(text, cols=NULL, col1=FALSE, full=F) {
  if(!length(cols)) {
    cols=colnames(text)
  }
  if(!col1) {
    kable(text,"html", col.names = cols, align = c("l",rep('c',length(cols)-1))) %>%
      kable_styling(bootstrap_options = c("striped","hover"), full_width=full)
  } else {
    kable(text,"html", col.names = cols, align = c("l",rep('c',length(cols)-1))) %>%
      kable_styling(bootstrap_options = c("striped","hover"), full_width=full) %>%
      column_spec(1,bold=T)
  }
}
```

<h3 class="date"><br>Session 11</h3>
<h2 class="author"><br>Dr. Richard M. Crowley<br>rcrowley@smu.edu.sg<br><a href="http://rmc.link/">http://rmc.link/</a></h2>

## ACCT 101: Financial Statement Analysis {data-background="../Backgrounds/title.jpg" class="header no-toc-progress present-not" data-state="no-toc-progress"}

<h3 class="date"><br>Session 11</h3>
<h2 class="author"><br>Dr. Richard M. Crowley<br>rcrowley@smu.edu.sg<br><a href="http://rmc.link/">http://rmc.link/</a></h2>

# Front matter {data-background="../Backgrounds/section.jpg" class="header"}

## Final exam details {data-background="../Backgrounds/studying.jpg" class="default exclude"}

<div style="font-size:0.7em">

- The exam will be done electronically on eLearn. Students in Singapore will take the exam at SMU; students abroad will take the exam simultaneously.
- 8 questions that consist of problem solving, journal entries, reasoning & explanations, preparation of partial or full statements, and financial statement analysis (including ratios).  PV/PVA tables will be given (for bonds).
- These are comprehensive questions that integrate several topics.  The following topics will be covered:
    - Accounts receivable and bad debt
    - Bank reconciliation
    - Inventory and COGS
    - Long term assets
    - Accrual accounting: processing information & adjusting
    - Liabilities
    - Stockholders' equity
    - Statement of cash flows
    - Financial ratios
- Ratios: you must use the formulas in these lecture slides.  Formulas will **not** be provided in the exam papers.
- Not covered: Par value for common shares; periodic inventory systems
- Use sample (past year) exam papers **with caution**.  The content, coverage, and difficulty level may be different.
</div>

## Final exam resources {data-background="../Backgrounds/studying.jpg" class="default exclude"}

- Practice final exams
    - These are old exams which I have made annotations to in order to keep them relevant
- Additional practices
- Additional selected book problems
- Review session by TAs
    - In mid-to-late November
- Office hours -- book online!
- eLearn practices (257 questions and counting!)
    - These can be very helpful to identify what you need to study
- All practices from quiz 1 and quiz 2

## Final exam tips {data-background="../Backgrounds/studying.jpg" class="default exclude"}

- Remember that everyone is taking the same exam -- if you find it difficult or long, others likely think the same.
- If you are stuck on a question, skip it and come back later.  It's better to solve everything that you know well and then work on those you are stuck on.
- If you are really stuck on a topic while studying for finals, drop by my office hours and we'll get it worked out.
- Course grades will be curved.

## Learning objectives {data-background="../Backgrounds/default.jpg" class="default"}

<div class="left">
![Diagram](../Course_Diagrams/ACCT_101_course_map_11.png){width=450px}
</div>
<div class="right">

1. Learn about financial statement analysis
2. Calculate and interpret financial ratios
</div>

# Financial statement analysis {data-background="../Backgrounds/section.jpg" class="header"}

## What matters? {data-background-image="../Backgrounds/default.jpg" class="default"}

1. The business environment
    - Economy health
    - Other countries (particularly for multinational firms)
    - Industry demand
    - Resource scarcity or supplier concentration
    - Consumer concentration

## What matters? {data-background-image="../Backgrounds/default.jpg" class="default"}


2. Historical financials
    - Financial statements and notes
    - Competitors statements

<a href="https://web.archive.org/web/20170205082307/https://www.bloomberg.com/news/articles/2017-02-02/snapchat-parent-files-publicly-for-3-billion-initial-offering"><img src="../Figures/snapchat.png" style="max-height:175px"><br>https://rmc.link/101class11-1</a>

## What matters? {data-background-image="../Backgrounds/default.jpg" class="default"}

<div class="left">

3. Historical non-financials
    - Governance, Risk disclosures, Audit report
    - Shareholders, supplier relationships
</div>
<div class="right">
<a href="https://arstechnica.com/cars/2016/09/mobileye-and-tesla-spat-heats-up-as-both-companies-trade-jabs/"><img src="../Figures/Tesla.jpg" style="max-height:175px"><br>https://rmc.link/101class11-2</a>

<a href="http://www.itpro.co.uk/strategy/27005/tesla-autopilot-supplier-mobileye-cuts-ties-with-electric-car-maker"><img src="../Figures/mobileye.png" style="max-height:175px"><br>https://rmc.link/101class11-3</a>
</div>

## Predicting firm value {data-background="../Backgrounds/reference.jpg" class="default"}

1. Trend analysis (a.k.a. Horizontal analysis)
    - Compare dollar and percent changes across years
2. Common size financial statements (a.k.a. Vertical analysis)
    - Compare financials across years or firms
    - A subset of ratio analysis
3. *Ratio analysis*
4. Analytics

> *Only ratio analysis is on the final* -- we'll cover the others briefly.

# Trend analysis {data-background="../Backgrounds/section.jpg" class="header"}


## What is it? {data-background="../Backgrounds/default.jpg" class="default"}

- Comparing different years or quarters of data to see the *trend* in measures.
- Examples:
    - Revenue grew by 3% this year
    - Net income grew by 4% this quarter
    - Quarterly revenue decreased 2% year over year

## Examples {data-background="../Backgrounds/default.jpg" class="default"}

- <a href="https://www.wsj.com/articles/nike-rides-out-its-metoo-moment-1521812723">Nike Rides Out its #MeToo Moment</a>, WSJ

> That is a reflection of a strong quarter: Nike reported earnings of 68 cents a share, beating analysts’ estimates by 15 cents, and *grew revenue by 7%*.

- <a href="https://www.wsj.com/articles/chinas-tencent-invests-in-video-ai-and-mobile-payments-as-earnings-soar-1521645233">China’s Tencent Invests in Video, AI and Mobile Payments, as Earnings Soar</a>, WSJ

> The plans emerged as the Shenzhen-based company said its *fourth-quarter revenue grew 51% year over year* to 66.4 billion yuan ($10.2 billion), boosted by strong growth in mobile payments, digital content subscriptions and advertising on its flagship mobile social apps, WeChat and QQ.

## How to do it {data-background="../Backgrounds/reference.jpg" class="default"}

1. Get 2 financial statements from the same company (typically the income statement)
2. Find the percentage change from the old figures to the new figures

<img src="../Diagrams/trend_analysis.png" width="50%">

# Common-size financial statements {data-background="../Backgrounds/section.jpg" class="header"}

## What is it? {data-background="../Backgrounds/default.jpg" class="default"}

- Standardizing figures in a financial statement by dividing by another figure.
- Allows for comparing financial statements across companies
- Ex.:
    - Divide an income statement by revenue
        - $\frac{Gross\ profit}{Revenue}=Gross\ Margin$
        - $\frac{Net\ income}{Revenue}=Profit\ Margin$
    - Divide financial statements by total assets

## Examples {data-background="../Backgrounds/default.jpg" class="default"}

- <a href="https://www.wsj.com/articles/general-mills-rising-supply-chain-costs-weigh-on-profit-1521636567">Cheerios Could Get Pricier as General Mills Faces Rising Costs</a>, WSJ

> Fourteen of the last 15 packaged food makers to [report] earnings posted lower-than-expected gross margins, said J.P. Morgan analyst Ken Goldman.

- <a href="https://www.wsj.com/articles/ford-ceo-says-company-could-exceed-8-margin-target-1521136839">Ford CEO Says Company Could Exceed 8\% Margin Target</a>, WSJ

> The company is forecasting an 8% global profit margin by about 2022, a number that would put it closer to better-performing peers, including GM. Ford's 5% operating margin last year was disappointing...

## How to do it  {data-background="../Backgrounds/reference.jpg" class="default"}

1. Get a financial statement
2. Divide every number by the same amount (sales, total assets, etc.) to get the percent (of sales, of assets, etc.)

<img src="../Diagrams/common_size.png" width="70%">

> We can compare accross companies or years

# Balance sheet ratios {data-background="../Backgrounds/section.jpg" class="header"}

## What is ratio analysis? {data-background="../Backgrounds/default.jpg" class="default"}

- Using various ratios of numbers from financial statements to better understand companies

All examples use the following data

<img src="../Diagrams/ratios_example.png" width="70%">

## Caveats {data-background="../Backgrounds/default.jpg" class="default"}

1. There are a few differences between the ratios in these slides and in the book.  These differences are due to simplifications I have made -- you can use these ratios on the final instead of the book's ratios without penalty.
2. Some ratios have many definitions.  If you look online, you may find other definitions for some of these ratios.  Don't use those on the final.

## Inventory turnover {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{COGS}{\frac{1}{2}\left(Inventory_T + Inventory_{T-1}\right)}
$$

- How many times per year a company sells its inventory on hand
- A similar measure is *Inventory resident period*
    - A.k.a. Number of days' sales in inventory
    - Calculated as $\frac{365}{Inventory\ turnover}$
    - The number of days it take to sell the company's inventory

> Microsoft's 2017 inv. turnover: $\frac{34,261}{\frac{1}{2}\left(2,181 + 2,251\right)} = 15.46$

> Microsoft's 2017 inv. period: $\frac{365}{15.46}=23.6\ days$

## Accounts receivable turnover {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{Revenue}{\frac{1}{2}\left(A/R_T + A/R_{T-1}\right)}
$$

- How many times per year a company collects its A/R on hand
- A similar measure is *Receivable collection period*
    - A.k.a. Number of days' sales in receivables
    - Calculated as $\frac{365}{Accounts\ receivable\ turnover}$
    - The number of days it take to collect the company's A/R

> Microsoft's 2017 A/R turnover: $\frac{89,950}{\frac{1}{2}\left(19,792 + 18,277\right)} = 4.73$

> Microsoft's 2017 A/R period: $\frac{365}{4.73}=77.2\ days$

## Payable turnover {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{COGS}{\frac{1}{2}\left(A/P_T + A/P_{T-1}\right)}
$$

- How many times per year a company pays its A/P it owes
- A similar measure is *Payable outstanding period*
    - Calculated as $\frac{365}{Payable\ turnover}$
    - The number of days it take to pay the company's A/P

> Microsoft's 2017 A/P turnover: $\frac{34,261}{\frac{1}{2}\left(7,390 + 6,898\right)} = 4.80$

> Microsoft's 2017 A/P period: $\frac{365}{4.80}=76.1\ days$

## Cash conversion cycle {data-background="../Backgrounds/default.jpg" class="default"}

$$
\begin{equation*}
\frac{365}{Inventory\ turnover} + \frac{365}{A/R\ turnover} - \frac{365}{A/P\ turnover}\\
\Updownarrow\\
\scriptstyle Receivable\ collection\ period + Inventory\ resident\ period - Payable\ outstanding\ period
\end{equation*}
$$

- Measures how long it takes from paying payables to receiving cash for a sale
- Can calculate from turnover ratios or periods

![An image of ](../Diagrams/CCC.png){width=1000px}

> Microsoft's 2017 cash conversion cycle: $23.6 + 77.2 - 76.1 = 24.7\ days$

## Asset turnover {data-background="../Backgrounds/default.jpg" class="default"}

$$
\text{Asset turnover} = \frac{Net~revenue}{\frac{1}{2}\left(Assets_T + Assets_{T-1}\right)}
$$

- Measures sales volume in relation to asset base

> Microsoft's 2017 asset turnover: $\frac{89,950}{\frac{1}{2}\left(241,086+193,468)\right)}=41.4\%$

## Current ratio {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{Current\ assets}{Current\ liabilities}
$$

- Measures a company's ability to pay current liabilities
- This should usually be $>2$
<br><br>

> Microsoft's 2017 current ratio: $\frac{159,851}{64,527}=2.48$


## Quick ratio {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{Cash + Short\ term\ investments + A/R}{Current\ liabilities}
$$

- A.k.a. acid-test ratio 
- Measures a company's ability to pay current liabilities
    - Only factors in liquid current assets
- This should be $>1$
<br><br>

> Microsoft's 2017 quick ratio: $\frac{7,663 + 125,318 + 19,792}{64,527}=2.37$

## Debt ratio {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{Total\ liabilities}{Total\ assets}
$$

- A.k.a. Debt to assets ratio
- Measures a company's leverage
    - Leverage = how much the company is financed by debt
- Higher = more leverage = more debt financing

> Microsoft's 2017 debt ratio: $\frac{168,692}{241,086}=70.0\%$


## Times-interest-earned ratio {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{Income\ from\ operations}{Interest\ expense}
$$

- Measures a company's ability to cover interest payments
- Higher is better, $<1$ should cause some worry

> Microsoft's 2017 times-interest-earned ratio: $\frac{22,326}{2,222}=10.05$

## Practice {data-background="../Backgrounds/question1.jpg" class="default"}

> Calculate the following ratios for Microsoft in 2016

- Payable outstanding period
- Quick ratio
- Debt ratio
- Times-interest-earned ratio

> Extra info: Microsoft's A/P in 2015 was \$6,591M

## Solution {data-background="../Backgrounds/answer.jpg" class="default exclude"}

- Payable payment period ($76.1\ days$ in 2017)
    - $365 / \frac{32,780}{\frac{1}{2}\left(6,898 + 6,591\right)}=75.1\ days$
- Quick ratio ($2.37$ in 2017)
    - $\frac{6,510 + 106,730 + 18,277}{59,357}=2.22$
- Debt ratio ($70.0\%$ in 2017)
    - $\frac{121,471}{193,468}=62.8\%$
- Times-interest-earned ratio ($10.5$ in 2017)
    - $\frac{20,182}{1,243}=16.2$

# Income statement ratios {data-background="../Backgrounds/section.jpg" class="header"}

## Profit Margin {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{Profit}{Revenue}
$$

- Gross profit margin tells you about the company's selling margins
- Operating profit margin tells you about its operating efficiency
- Net profit margin tells you about its overall profitability

> Microsoft's 2017 gross profit margin: $\frac{55,689}{89,950}=61.9\%$

> Microsoft's 2017 operating profit margin: $\frac{22,326}{89,950}=24.8\%$

> Microsoft's 2017 net profit margin: $\frac{21,204}{89,950}=23.6\%$

## Return on assets (ROA) {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{Net\ income}{\frac{1}{2}\left(Assets_T + Assets_{T-1}\right)}
$$

- Measures overall profitability based on the company's size
- Very common measure in practice
- Higher is better
<br><br>

> Microsoft's 2017 ROA: $\frac{21,204}{\frac{1}{2}\left(241,086+193,468)\right)}=9.76\%$

## Return on equity (ROE) {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{Net\ income}{\frac{1}{2}\left(Equity_T + Equity_{T-1}\right)}
$$

- Measures overall profitability based on the company's size
    - Stockholder focussed
- Very common measure in practice
- Higher is better
<br><br>

> Microsoft's 2017 ROE: $\frac{21,204}{\frac{1}{2}\left(72,394+71,997)\right)}=29.4\%$

## Practice {data-background="../Backgrounds/question1.jpg" class="default"}

> Calculate the following ratios for Microsoft in 2016

- Net profit margin
- Return on assets (ROA)
- Return on equity (ROE)

> Extra info: Microsoft's 2015 total assets was \$176,223M and Microsoft's 2015 total equity was \$80,083M

## Solution {data-background="../Backgrounds/answer.jpg" class="default exclude"}

- Net profit margin ($23.6\%$ in 2017)
    - $\frac{16,798}{85,320}=19.7\%$
- ROA ($9.76\%$ in 2017)
    - $\frac{16,798}{\frac{1}{2}\left(193,468+176,223\right)}=9.09\%$
- ROE ($29.4\%$ in 2017)
    - $\frac{16,798}{\frac{1}{2}\left(71,997+80,083\right)}=22.1\%$


# Equity ratios {data-background="../Backgrounds/section.jpg" class="header"}

## Earnings per share (EPS) {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{Net\ income - Dividends\ on\ pref.\ shares}{\frac{1}{2}\left(\#Shares_T+\#Shares_{T-1}\right)}
$$

- Measures the amount of profit tied to each share of stock
- Very common measure in practice
- Assume shares in year $T$ and $T-1$ are the same if not stated
- <span style="color:red">Very easily manipulated</span>
<br><br>

> Microsoft's 2017 EPS: $\frac{21,204 - 0}{\frac{1}{2}\left(7,708+7,808)\right)}=\$2.73/share$

## Price/earnings ratio (P/E ratio) {data-background="../Backgrounds/default.jpg" class="default"}

$$
\frac{Stock\ price}{EPS}
$$

- A measure of if a stock is overpriced
- 6 to 8 is common, 20+ is common for tech firms
    - Higher = overpriced
    - Lower = underpriced
- Very common measure in practice
- <span style="color:red">Very easily manipulated</span>, since EPS is easily manipulated
<br><br>

> Microsoft's 2017 P/E ratio: $\frac{68.93}{2.73}=25.2$

## Practice {data-background="../Backgrounds/question1.jpg" class="default"}

> Calculate the following ratios for Microsoft in 2016

- EPS
- P/E Ratio

> Extra info: Microsoft's 2015 outstanding shares was 8,027M

## Solution {data-background="../Backgrounds/answer.jpg" class="default exclude"}

- EPS ($\$2.73/share$ in 2017)
    - $\frac{16,798 - 0}{\frac{1}{2}\left(7,808+8,027\right)} = \$2.12/share$
- P/E Ratio ($25.2$ in 2017)
    - $\frac{51.17}{2.12} = 24.1$

# Equations {data-background="../Backgrounds/section.jpg" class="header"}

## Balance sheet ratio equations {data-background="../Backgrounds/reference.jpg" class="default"}

$$
{\scriptsize
\begin{align*}
\text{Inventory turnover} &= \frac{COGS}{\frac{1}{2}\left(Inventory_T + Inventory_{T-1}\right)} \\
\text{A/R turnover} &= \frac{Revenue}{\frac{1}{2}\left(A/R_T + A/R_{T-1}\right)} \\
\text{A/P turnover} &= \frac{COGS}{\frac{1}{2}\left(A/P_T + A/P_{T-1}\right)}\\
\text{Cash conversion cyle} &= \frac{365}{Inv.\ turnover} + \frac{365}{A/R\ turnover} - \frac{365}{A/P\ turnover}\\
\text{Asset turnover} &= \frac{Net~revenue}{\frac{1}{2}\left(Assets_T + Assets_{T-1}\right)} \\
\text{Current ratio} &= \frac{Current\ assets}{Current\ liabilities} \\
\text{Quick ratio} &= \frac{Cash + Short\ term\ investments + A/R}{Current\ liabilities} \\
\text{Debt ratio} &= \frac{Total\ liabilities}{Total\ assets} \\
\text{Times-interest-earned} &= \frac{Income\ from\ operations}{Interest\ expense}
\end{align*}}
$$

## Income statement ratio equations {data-background="../Backgrounds/reference.jpg" class="default"}

$$
\scriptsize
\begin{align*}
\text{Gross (profit) margin} &= \frac{Gross\ profit}{Revenue} \\
\text{Operating profit margin} &= \frac{Operating\ profit}{Revenue} \\
\text{Net profit margin} &= \frac{Net\ income}{Revenue} \\
\text{Return on assets (ROA)} &= \frac{Net\ income}{\frac{1}{2}\left(Assets_T + Assets_{T-1}\right)} \\
\text{Return on equity (ROE)} &= \frac{Net\ income}{\frac{1}{2}\left(Equity_T + Equity_{T-1}\right)}
\end{align*} \\
$$

## Equity ratio equations {data-background="../Backgrounds/reference.jpg" class="default"}

$$
\scriptsize
\begin{align*}
\text{Earnings per share (EPS)} &= \frac{Net\ income - Dividends\ on\ pref.\ shares}{\frac{1}{2}\left(\#Shares_T+\#Shares_{T-1}\right)} \\
\text{Price/earnings ratio (P/E)} &= \frac{Stock\ price}{EPS}
\end{align*}
$$

# Analytics {data-background="../Backgrounds/math_idea.jpg" class="header"}

## Background {data-background-image="../Backgrounds/default.jpg" class="default"}

> This is a quick preview of a module called "Forecasting and Forensic Analytics," part of the Analytics major in SOA

- You don't need to know this for this class, but the techniques covered here are becoming more and more important

## Revenue prediction {data-background-image="../Backgrounds/case_digital.jpg" class="default"}

> Predicting ROA for tech companies using prior year data

```{r, echo=FALSE}
load("Data/fit.rda")
```
```{r, echo=TRUE}
summary(fit)
```

## Code: Revenue prediction {data-background="../Backgrounds/code.jpg" class="default"}

```{r, eval=FALSE}
library(readr)
library(dplyr)
df <-read.csv("/media/Data/Data/Compustat/Compustat_199301-201703.csv")
df <- data.frame(df)
df_tech <- subset(df,gsector == 45 & at > 10000,
                  select=c("gvkey","datadate","at","ni","lt","revt","gind"))
df_tech <- arrange(df_tech, gvkey, datadate)
df_tech$ROA <- df_tech$ni / df_tech$at
df_tech$Revenue <- df_tech$revt / df_tech$at
df_tech$Debt <- df_tech$lt / df_tech$at
x <- c("ROA", "Revenue","Debt") # Columns to lag
df_tech <- df_tech %>%
  group_by(gvkey) %>%
  mutate_at(.cols=x, .funs=funs(lag = dplyr::lag(., n=1, default=NA)))
is.na(df_tech) <- sapply(df_tech, is.infinite)
fit <- lm(ROA ~ ROA_lag + Revenue_lag + Debt_lag + factor(gind), data=df_tech)
save(fit, file = "Data/fit.rda")
summary(fit)
```

## Revenue prediction for Microsoft {data-background-image="../Backgrounds/case_digital.jpg" class="default"}

> Predict out Microsoft's 2018 ROA

```{r, echo=FALSE, warning = FALSE, plotly=TRUE}
load("Data/df_ms.rda")
suppressPackageStartupMessages(library(plotly))
m <- list(l = 60,  r = 50,  b = 60,  t = 100,  pad = 4)
plot_ly(df_ms,x=~year,y=~ROA, name='Actual ROA', type='scatter', mode='lines', width = 800, height = 500) %>%
  add_trace(y=~ROA_predicted, name='Predicted ROA') %>%
  layout(autosize = F, margin = m,
         xaxis=list(title="Year"), yaxis=list(title="ROA"))
```

## Code: Revenue prediction for Microsoft {data-background-image="../Backgrounds/code.jpg" class="default"}

```{r, eval=FALSE}
df_ms <- subset(df,gvkey==12141, select=c("gvkey","datadate","at", "ni","lt",
                                          "revt","gind"))
df_ms2 <- data.frame(gvkey=12141, datadate=20170630, at=241086,ni=21204,
                     lt=168692,revt=89950,gind=451030)
df_ms3 <- data.frame(gvkey=12141, datadate=20180630, at=NA,ni=NA,
                     lt=NA,revt=NA,gind=451030)
df_ms <- rbind(df_ms, df_ms2, df_ms3)
df_ms$ROA <- df_ms$ni / df_ms$at
df_ms$Revenue <- df_ms$revt / df_ms$at
df_ms$Debt <- df_ms$lt / df_ms$at
x <- c("ROA", "Revenue","Debt") # Columns to lag
df_ms <- df_ms %>%
  group_by(gvkey) %>%
  mutate_at(.cols=x, .funs=funs(lag = dplyr::lag(., n=1, default=NA)))
df_ms$ROA_predicted <- predict(fit, df_ms)
df_ms$year = floor(df_ms$datadate/10000)
save(df_ms, file="Data/df_ms.rda")
```
```{r, eval=FALSE}
suppressPackageStartupMessages(library(plotly))
m <- list(l = 60,  r = 50,  b = 60,  t = 100,  pad = 4)
plot_ly(df_ms,x=~year,y=~ROA, name='Actual ROA', type='scatter',
        mode='lines', width = 800, height = 500) %>%
  add_trace(y=~ROA_predicted, name='Predicted ROA') %>%
  layout(autosize = F, margin = m,
         xaxis=list(title="Year"), yaxis=list(title="ROA"))
```

## Fraud detection {data-background-image="../Backgrounds/case_digital.jpg" class="default"}

<div class="left">

- Using 3 components:
    1. **T**opic -- what companies say in annual reports
    2. **S**tyle -- writing style used in annual reports
    3. **F**inancials -- financial ratios
    
<img src="../Figures/AAER_classification.png" width="400px">

- Brown, Crowley, & Elliott (2020, Journal of Accounting Research)
</div>
<div class="right">
<img src="../Figures/Detection_by_year.png" width="380px">

</div>

## Text classification of what you found interesting on HW2 {data-background-image="../Backgrounds/neural-net.jpg" class="default"}

```{r, echo=FALSE, eval=FALSE}
library(readr)
library(tm)
bd <- read.csv("Data/all.csv", stringsAsFactors=FALSE)
bd <- as.character(unlist(bd[, 1]))
stop_words <- stopwords("SMART")
# pre-processing:
bd <- gsub("'", "", bd)  # remove apostrophes
bd <- gsub("[[:punct:]]", " ", bd)  # replace punctuation with space
bd <- gsub("[[:cntrl:]]", " ", bd)  # replace control characters with space
bd <- gsub('[[:digit:]]+', '', bd) # remove numbers
bd <- gsub("[[:space:]]", " ", bd) # replace whitespace with spaces
bd <- gsub("^[[:space:]]+", "", bd) # remove whitespace at beginning of documents
bd <- gsub("[[:space:]]+$", "", bd) # remove whitespace at end of documents


bd <- tolower(bd)  # force to lowercase

# tokenize on space and output as a list:
doc.list <- strsplit(bd, "[[:space:]]+")

# compute the table of terms:
term.table <- table(unlist(doc.list))
term.table <- sort(term.table, decreasing = TRUE)

# remove terms that are stop words or occur fewer than 2 times:
del <- names(term.table) %in% stop_words | term.table < 3
term.table <- term.table[!del]
vocab <- names(term.table)

# now put the documents into the format required by the lda package:
get.terms <- function(x) {
  index <- match(x, vocab)
  index <- index[!is.na(index)]
  rbind(as.integer(index - 1), as.integer(rep(1, length(index))))
}
documents <- lapply(doc.list, get.terms)

D <- length(documents)  # number of documents (516)
W <- length(vocab)  # number of terms in the vocab (2675)
doc.length <- sapply(documents, function(x) sum(x[2, ]))  # number of tokens per document
N <- sum(doc.length)  # total number of tokens in the data (17266)
term.frequency <- as.integer(term.table)

K <- 10
G <- 5000
alpha <- 0.01
eta <- 0.02

library(lda)
set.seed(357)
t1 <- Sys.time()
fit <- lda.collapsed.gibbs.sampler(documents = documents, K = K, vocab = vocab, 
                                   num.iterations = G, alpha = alpha, 
                                   eta = eta, initial = NULL, burnin = 0,
                                   compute.log.likelihood = TRUE)
t2 <- Sys.time()
t2 - t1  # about 6.5s on desktop

theta <- t(apply(fit$document_sums + alpha, 2, function(x) x/sum(x)))
phi <- t(apply(t(fit$topics) + eta, 2, function(x) x/sum(x)))

All <- list(phi = phi,
            theta = theta,
            doc.length = doc.length,
            vocab = vocab,
            term.frequency = term.frequency)

library(LDAvis)

json <- createJSON(phi = All$phi, 
                   theta = All$theta, 
                   doc.length = All$doc.length, 
                   vocab = All$vocab, 
                   term.frequency = All$term.frequency)
library(servr)
serVis(json, out.dir = 'vis2', open.browser = FALSE)
```

<a href="https://rmc.link/Slides/acct101v5/Session_11/vis2/#topic=1&lambda=0.43&term="><img src="../Figures/LDA_2021.png" width="800px"></a>

# End matter {data-background="../Backgrounds/ending.jpg" class="header"}

## Wrap up {data-background="../Backgrounds/ending.jpg" class="default"}

- For next week
    1. Homework 5
        - Cash flows and financial ratios
        - Turn in by next week
    2. Next week:
        - Groups will present in order 
            - Group numbers were randomly assigned initially!
        - Group project presentations
        - Email me slides by 10am of that class day
    1. Extra practice available
        - Financial ratios eLearn quiz
- Survey on the class session at <a href="https://rmc.link/101survey11">rmc.link/101survey11</a>

## Packages used for these slides {data-background="../Backgrounds/code.jpg" class="default stack"}

- dplyr
- kableExtra
- knitr
- lda
- LDAvis
- plotly
- revealjs
- servr
- tm

## References {data-background="../Backgrounds/books-old.jpg" class="default stack never"}

## Custom code {data-background="../Backgrounds/code.jpg" class="default stack never"}

<small style="width:100%">
```{r, eval=F}

```
</small>


## NOTES {class="never"}

- Consider adding:
    - Debt to equity ratio
- Consider removing:
    - Operating profit margin
    - Debt ratio


- Print out the ratios in advance -- too difficult to wing
- To prep for analytics, play following link during break:
    - https://magenta.tensorflow.org/demos/performance_rnn/index.html#2|2,0,1,0,1,1,0,1,0,1,0,1|1,1,1,1,1,1,1,1,1,1,1,1|1,1,1,1,1,1,1,1,1,1,1,1|false