---
title: "On portfolios: In Class"
author: "Milica Cudina"
date: "`r Sys.Date()`"
lang: en
output:
  html_document:
    toc: true
    toc_depth: 2
    theme: null
    highlight: null
    df_print: paged
    css: "high_contrast.css"
  pdf_document:
    latex_engine: xelatex
    keep_tex: true
---
<!-- The author of this template is Dr. Gordan Zitkovic.-->
<!-- The code chunk below contains some settings that will  -->
<!-- make your R code look better in the output pdf file.  -->
<!-- If you are curious about what each option below does, -->
<!-- go to https://yihui.org/knitr/options/ -->
<!-- If not, feel free to disregard everything ...  -->
```{r echo=FALSE, warning=FALSE, include=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  fig.align = "center",
  fig.pos = "t",
  strip.white = TRUE,
  message = FALSE,
  warning = FALSE
)
```
<!-- ... down to here. -->

# Accessibility note
This document is written so that all key information (including tables) is available as text. 

---

# Problems

## Problem \#1 
Your initial wealth is exactly \$100. You are allowed to invest in shares of a particular stock. You are also allowed to both lend and borrow at the continuously compounded, risk-free interest rate of 0.05. Keeping your money uninvested is **not allowed**.

You rebalance your portfolio every morning, once you have observed the opening stock price. This means that you can change the number of shares you own (if you decide to do so) and accordingly adapt your risk-free investment.

You proceed to create a ``rule'' according to which you will be
rebalancing your portfolio. Here is a possible rule you can use:

*Start by purchasing half a share of stock. Thereafter, if the stock had gone up overnight, you invest an extra \$10 in the stock (you might need to borrow money); if the stock had gone down, you take out \$10 worth of investment from the stock and put that in the savings account (you might need to short the stock); if the stock price remains the same, change nothing.* 

Over the following 10 days, you observe the following stock prices for a non-dividend-paying stock:

| Day | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| Stock price | 100 | 80 | 64 | 80 | 64 | 80 | 100 | 80 | 64 | 80 | 100 |

**Table description (for accessibility):** The stock price starts at 100 on day 0, drops to 80 (day 1), then 64 (day 2), then alternates between 80 and 64 until returning to 100 on day 6 and day 10.

As the time passes you follow the investment rule above to rebalance your portfolio. Complete the following table describing your portfolio **just before and just after** the rebalancing is done. Even more precisely, for the $10$ days, both for "before" and "after" the rebalancing, print out:

- the number of shares of stock in the portfolio, 
- the balance of the risk-free investment, 
- the wealth in the stock, 
- the total wealth. 



*Solution:*
First, record the ccrfir:
```{r}
r=0.05
```
Second, create a vector containing the stock prices:
```{r}
s=c(100, 80, 64, 80, 64, 80, 100, 80, 64, 80, 100)
```
Create vectors for our quantities of interest:
```{r}
#this will be the number of shares in the portfolio
pi.v=numeric(11)
#this will be cash
cash=numeric(11)
#this will be the total wealth
wealth=numeric(11)
```
Now, we implement the rule, starting with the initial condition:
```{r}
wealth[1]=100
pi.v[1]=1/2
cash[1]=wealth[1]-s[1]*pi.v[1]
```
**We create a rebalancing function.**
```{r}
rebalance<-function(s.beg, s.end, shares){
  if (s.beg==s.end){
    return(shares)
  } else {
    if (s.beg<s.end){
      return(shares+10/s.end)
    } else {
      return(shares-10/s.end)
    }
  }
}
```


**Now we run through the 10 days.**
```{r}
#the libraries I need to make it esthetically pleasing
library(tibble)
library(dplyr)

#a tibble,i.e., my environment for the before/after during the 10 days
rows<-vector("list", 2*10)

k<-1
for (i in 1:10){
  cash[i+1]<-cash[i]*exp(r/365)
  wealth[i+1]<-cash[i+1]+pi.v[i]*s[i+1]

  #add the row for *before* rebalancing
  rows[[k]]<-tibble(
    day=i,
    when="before",
    stock_price=s[i+1],
    cash=cash[i+1],
    shares=pi.v[i],
    stock_value=pi.v[i]*s[i+1],
    total_wealth=wealth[i+1]
  )
  
  k<-k+1

  pi.v[i+1]=rebalance(s[i], s[i+1], pi.v[i])
  cash[i+1] = wealth[i+1]-pi.v[i+1]*s[i+1]
  
  #add the row for *after* rebalancing
  rows[[k]]<-tibble(
    day=i,
    when="after",
    stock_price=s[i+1],
    cash=cash[i+1],
    shares=pi.v[i+1],
    stock_value=pi.v[i+1]*s[i+1],
    total_wealth=wealth[i+1]
  )
  k<-k+1
}

balances<-bind_rows(rows)
#balances

#the following creates a prettier table
library(knitr)

balances_pretty <- balances %>%
  mutate(across(where(is.numeric), ~ round(.x,2))) %>%
  arrange(day,when) %>%
  select(day, when, stock_price, shares, stock_value, cash, total_wealth)

knitr::kable(
  balances_pretty,
  caption="Portfolio evolution before and after daily rebalancing"
)

```

