///////////////////////


8.34 Explain using the spread() function in tidyr to reshape data from long to wide format.
8.35 What are pivot_longer() and pivot_wider() functions used for in tidyr?
8.21 What are the advantages of using `dplyr` and `tidyr` for data manipulation compared to base R functions?

///////////////////////

normal project, R code  
////////////////////////////////
 A normal project is defined as 
    cash outflows first, then cash inflows. 

irr_f<-function(cashflows,bigV=100000){
   irr<-2
   rates<-seq(-1,1,1e-4)
   for(r in rates){
        npv<-abs(npv_f(r,cashflows))
        #print(npv)
        if(npv< bigV){
           irr<-r
           bigV<-npv
     }
   }
   return(irr)
}
cashflows<-c(-100,90,50,30)
irr_f(cashflows)  # [1] 0.4069
///////////////////////////////

Estimate IBM's totak risk (Excel vs. R)
////////////////////////////////
 For a company (stocks), its total risk has two components. 
    Total risk = market risk + firm specific risk

  We use the standard deviation of stock returns to 
     measure the total risk. 
Excel
------------
      Step 1: download the data .show_ibmMonthly(0)
      Step 2: estimate monthly returns
      Step 3: estimate the standard deviation
      Step 4: annualize it   std(annual) = sqrt(12)*std_monthly
R
-------------
      Step 1: download the data at http://datayyy.com/data_R/ibmMonthly.RData
      Step 2: estimate monthly returns
      Step 3: estimate the standard deviation
      Step 4: annualize it   std(annual) = sqrt(12)*std_monthly
      [you can combine the last three step3]

/////////////////////////

NPV profile 
////////////////////////////////

rates<-seq(0,1,1e-1)
cashflows<-c(-400,100,200,200,200,200)

npvs<-npv_f(rates,cashflows)
title<-"NPV profile"
x<-"Discount Rate"
plot(rates,npvs,main=title,xlab=x,ylab="NPV",type='b',lwd=4)

# add a line
x1<-rates
y1<-x1*0
lines(x1,y1,lwd=1)
text(0.4, 106, labels=expression("NPV=0") ,cex = 1)

#
y2<-seq(-300,400,1)
irr<-irr_f(cashflows)
x2<-rep(irr,length(y2))
lines(x2,y2,lwd=1)

///////////////////////////////