library(FinCal)
library(ggplot2)

#irrex <- irr(cf=c(-10000, 7000, 10000, 12000, -19500, 325.11))
# Multiple changes in sign cause a uniroot error - keep the above as a comment
npvex <- npv(r=0.10, cf=c(-10000, 7000, 10000, 12000, -19500, 325.11))
npvex
## [1] 526.9821
# You can take the large negative cash flow in P4 and discount it back
# to subtract it from the initial to create a modified cash flow *notes*

irr(cf=c(-23319, 7000, 10000, 12000))
## [1] 0.1072417
# It would calculate a 10.7% IRR this way appropriately

# NPV/IRR Delta Examples:
npva <- npv(r=0.09, cf=c(-400000, 241000, 293000))
irra <- irr(cf=c(-400000, 241000, 293000))

npvb <- npv(r=.09, cf=c(-200000, 131000, 172000))
irrb <- irr(cf=c(-200000, 131000, 172000))

npva
## [1] 67713.16
npvb
## [1] 64952.45
irra
## [1] 0.2085595
irrb
## [1] 0.3109907
# Above we can see the NPV informs a decision in favor of project A

# Accept/reject decisions -> both IRR and NPV can be used
# Project Selection (ranking) -> Use NPV
# Capital rationing -> Profitability or Present Value Index

# Comparing Projects with DIff Economic Lives

techanpv <- npv(r=0.10, cf=c(-100000, 60000, 60000))
techbnpv <- npv(r=0.10, cf=c(-100000, 40000, 40000, 47500))

# r = WACC

# r is going to reflect the weighted average of capital the debt holder is 
# going to receive based on the risk of their investment, weighted by the distro
# of debt and equity financing

# Review CAPM and Capital Budgeting before mvoing into discount rates

# Calculating the company versus project cost of capital example:

# Define probabilities and returns as vectors
probabilities <- 0.25
returns_A <- c(0.12, 0.112, 0.10, 0.03)
returns_B <- c(0.16, 0.14, 0.104, 0.06)
returns_C <- c(0.155, 0.125, 0.10, 0.07)
returns_D <- c(0.15, 0.13, 0.07, 0.042)

# Calculate expected returns for each investment
expected_return_A <- sum(probabilities * returns_A)
expected_return_B <- sum(probabilities * returns_B)
expected_return_C <- sum(probabilities * returns_C)
expected_return_D <- sum(probabilities * returns_D)

# Create a named vector for expected returns
expected_returns <- c(A = expected_return_A, B = expected_return_B, 
                      C = expected_return_C, D = expected_return_D)

# Print expected returns
print("Expected returns for each investment:")
## [1] "Expected returns for each investment:"
print(expected_returns)
##      A      B      C      D 
## 0.0905 0.1160 0.1125 0.0980
# Find the investment with the highest expected return
best_investment <- names(which.max(expected_returns))
highest_return <- max(expected_returns)

# Print the best investment and its expected return
cat("The best investment is:", best_investment, "with an expected return of:", highest_return * 100, "%\n")
## The best investment is: B with an expected return of: 11.6 %
# The next step would be to compare the required return for each project to the expected 
# return values above:

# Define risk-free rate and market return
risk_free_rate <- 0.06
market_return <- 0.14

# Beta values for each project
beta_A <- 0.2
beta_B <- 0.35
beta_C <- 0.75
beta_D <- 0.85

# Calculate required return for each project using CAPM
required_return_A <- risk_free_rate + beta_A * (market_return - risk_free_rate)
required_return_B <- risk_free_rate + beta_B * (market_return - risk_free_rate)
required_return_C <- risk_free_rate + beta_C * (market_return - risk_free_rate)
required_return_D <- risk_free_rate + beta_D * (market_return - risk_free_rate)

# Compare expected returns to required returns
meets_required_return_A <- expected_return_A >= required_return_A
meets_required_return_B <- expected_return_B >= required_return_B
meets_required_return_C <- expected_return_C >= required_return_C
meets_required_return_D <- expected_return_D >= required_return_D

# Print whether each project meets its required return
cat("Does Project A meet its required return?", meets_required_return_A, "\n")
## Does Project A meet its required return? TRUE
cat("Does Project B meet its required return?", meets_required_return_B, "\n")
## Does Project B meet its required return? TRUE
cat("Does Project C meet its required return?", meets_required_return_C, "\n")
## Does Project C meet its required return? FALSE
cat("Does Project D meet its required return?", meets_required_return_D, "\n")
## Does Project D meet its required return? FALSE
# Calculate alpha for each project
alpha_A <- expected_return_A - required_return_A
alpha_B <- expected_return_B - required_return_B
alpha_C <- expected_return_C - required_return_C
alpha_D <- expected_return_D - required_return_D

# Store alphas in a named vector
alphas <- c(A = alpha_A, B = alpha_B, C = alpha_C, D = alpha_D)

# Find the project with the greatest alpha
greatest_alpha_project <- names(which.max(alphas))
greatest_alpha_value <- max(alphas)

# Print the project with the greatest alpha and its value
cat("The project with the greatest alpha is:", greatest_alpha_project, "with an alpha of:", greatest_alpha_value, "\n")
## The project with the greatest alpha is: B with an alpha of: 0.028
# Project A would not proceed because it lies below the WACC of 10% unless the risk
# profile (beta) is less than the required risk to meet those returns in the market
# Return matches the risk profile for shareholders to demand that specific return
# See example in the estimation of equity/risk


# Data for plotting
beta_values <- c(0.2, 0.35, 0.75, 0.85)
required_returns <- c(required_return_A, required_return_B, required_return_C, required_return_D)
expected_returns <- c(expected_return_A, expected_return_B, expected_return_C, expected_return_D) # From previous calculations
project_names <- c("Project A", "Project B", "Project C", "Project D")
wacc <- 0.10 # WACC of 10%

# Create a data frame for ggplot
investment_data <- data.frame(Beta = beta_values, Required_Return = required_returns, 
                              Expected_Return = expected_returns, Project = project_names)

# Plotting
ggplot() +
  geom_point(data = investment_data, aes(x = Beta, y = Required_Return, color = "Required Return"), size = 3) +
  geom_point(data = investment_data, aes(x = Beta, y = Expected_Return, color = "Expected Return"), size = 3) +
  geom_hline(yintercept = wacc, linetype = "dashed", color = "darkgreen", size = 1) +
  geom_text(data = investment_data, aes(x = Beta, y = Required_Return, label = Project), nudge_y = 0.01, size = 3.5) +
  geom_abline(intercept = risk_free_rate, slope = (market_return - risk_free_rate), color = "red", linetype = "solid") +
  geom_segment(data = investment_data, aes(x = Beta, xend = Beta, y = Required_Return, yend = Expected_Return), 
               linetype = "dashed", color = "grey") + # Add dashed lines between required and expected returns
  scale_color_manual(name = "", values = c("Required Return" = "red", "Expected Return" = "blue")) +
  labs(title = "Security Market Line (SML) and WACC Comparison",
       subtitle = "Projects' Required and Expected Returns vs. Beta",
       x = "Beta (Systematic Risk)", y = "Return (%)",
       caption = "Note: WACC (10%) shown as dashed green line. SML in red. Dashed lines connect required and expected returns.") +
  theme_minimal() +
  theme(legend.position = "bottom")

# Pure play/comparison/twin companies that have an identical product as a business unit
# within a larger company can be used for an industry beta for that business unit
# You must also consider the asset split for each company when analyzing the beta
#      Equity beta affects business risk and the effect of financial leverage
#      You must correct for the difference in equity leverage (unlevering)

# Unlevered betas are not published for many reasons, one of which is that there is
# no agreed upon methodology - i.e. Anjolein uses debt betas, Demoderan does not