---
title: "finlabR: Portfolio Analytics and Simulation"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{finlabR: Portfolio Analytics and Simulation}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
```

```{r}
library(finlabR)
```

## Example dataset

```{r}
prices <- get_example_prices()
rets <- calc_returns(prices[, -1])
```

## Mean-variance optimization

```{r}
min_var <- mvo_min_variance(rets)
ef <- mvo_efficient_frontier(rets, n = 30, rf = 0.02)
max_sharpe <- mvo_max_sharpe(rets, rf = 0.02)
```

```{r}
plot_efficient_frontier(ef)
```

## CVaR minimization

```{r}
cvar <- cvar_minimize(rets, alpha = 0.95)
cvar$cvar
```

## Risk parity

```{r}
rp <- risk_parity_weights(stats::cov(rets))
rp$weights
```

## Regime clustering

```{r}
regimes <- market_regime_kmeans(rets, k = 3, window = 60)
table(regimes$labels)
```

## Asset clustering (PCA + k-means)

```{r}
clusters <- asset_clustering(rets, method = "kmeans", reduce = "pca", k = 3)
clusters$clusters
```

## VaR / CVaR

```{r}
var_cvar(rets, alpha = 0.95)
```

## Monte Carlo price simulation

```{r}
paths <- simulate_gbm_paths(100, 0.08, 0.2, time_horizon = 1, n_steps = 252, n_sims = 1000)
dim(paths)
```

## Option pricing

```{r}
price_option_mc(100, 100, 0.02, 0.2, time_to_maturity = 1, n_sims = 20000)
price_option_binomial(100, 100, 0.02, 0.2, time_to_maturity = 1, n_steps = 200, american = TRUE)
```
