## Gamblers ruin

In this simulation a gambler starts with \$1,000 (`wealth`). She places a single bet each day of the year and has decided to invest 5% (`perc_invest`) of the available money each time. The probability of winning is 20% (`prob_win`) and if the gambler wins she gets 5 times (`win_mult`) the amount she bet (i.e., the investment).

The challenge in this simulation is that the amount invested (bet) each day depends on whether the gambler won or lost her bet yesterday. To calculate the dynamic wealth, we need to write a custom function (`calc_wealth`). We can _call_ the `calc_wealth` function from the `Simulation formulas` input.

The first line in the function creates a vector of length 366 where the first value is the initial investment amount. The other elements of the vector are set to `NA` (i.e., a missing value) because they are, as yet, unknown. We then _loop_ through the `win` vector to calculate the available wealth and investment amount for each day.

All required settings are shown in the screenshot below:

![](https://raw.githubusercontent.com/radiant-rstats/docs/gh-pages/examples/gamblers-ruin-input.png)


```{r}
## win: a vector indicating if a bet was won or lost
## wealth: amount of mony the gambler starts starts
## mult: the winning multiplier
calc_wealth <- function(win, wealth, mult) {
  wealth = c(wealth, rep(NA, length(win)))
  for (i in 1:length(win)) {
    wealth[i+1] = ifelse(
      win[i], 
      wealth[i] + mult * perc_invest * wealth[i], 
      wealth[i] - perc_invest * wealth[i]
    )
  }
  return(wealth[-1])  ## dropping the initial wealth value
}

simdat <- simulater(
  const = c("wealth 1000", "perc_invest 0.05", "prob_win 0.2", "win_mult 5"), 
  unif = "rnd 0 1", 
  sequ = "time 1 365", 
  form = c(
    "win = rnd < prob_win", 
    "dyn_wealth = calc_wealth(win, wealth, win_mult)", 
    "final = last(dyn_wealth)"
  ), 
  funcs = list(calc_wealth = calc_wealth), 
  seed = 1234, 
  nr = 365
)
summary(simdat, dec = 2)
register("simdat")
```

The following plot shows the rise and fall of the gambler's wealth over the course of the year.

```{r fig.width = 7, fig.height = 7, dpi = 144}
visualize(
  simdat, 
  xvar = "time", 
  yvar = "dyn_wealth", 
  type = "line", 
  custom = FALSE
)
```

Of course, the above similation only shows a possible result for one year. What would be the expected annual result if the gambler continous on for 50 years and starts each year with $1,000? We can use the _Model > Simulate > Repeat_ tab to find the answer.

```{r fig.width = 7, fig.height = 3.23, dpi = 144}
repdat <- repeater(
  simdat, 
  nr = 50, 
  vars = "rnd", 
  sum_vars = "dyn_wealth", 
  byvar = ".rep", 
  fun = "last", 
  seed = 1234
)
summary(repdat, dec = 2)
plot(repdat, custom = FALSE)
register("repdat")
```

The results shown above indicate that the gambler should expect just over \$13K profit per year from this gambling strategy.