# finlabR: Portfolio Analytics and Simulation

    library(finlabR)
    #> Registered S3 method overwritten by 'quantmod':
    #>   method            from
    #>   as.zoo.data.frame zoo

## Example dataset

    prices <- get_example_prices()
    rets <- calc_returns(prices[, -1])

## Mean-variance optimization

    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)

    plot_efficient_frontier(ef)
    #> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
    #> ℹ Please use `linewidth` instead.
    #> ℹ The deprecated feature was likely used in the finlabR package.
    #>   Please report the issue to the authors.
    #> This warning is displayed once per session.
    #> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    #> generated.

## CVaR minimization

    cvar <- cvar_minimize(rets, alpha = 0.95)
    cvar$cvar
    #> [1] 0.005853819

## Risk parity

    rp <- risk_parity_weights(stats::cov(rets))
    rp$weights
    #>       EQ1       EQ2       EQ3      CMD1   CRYPTO1     BOND1
    #> 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667

## Regime clustering

    regimes <- market_regime_kmeans(rets, k = 3, window = 60)
    table(regimes$labels)
    #>
    #>   1   2   3
    #> 413 276 251

## Asset clustering (PCA + k-means)

    clusters <- asset_clustering(rets, method = "kmeans", reduce = "pca", k = 3)
    clusters$clusters
    #>     EQ1     EQ2     EQ3    CMD1 CRYPTO1   BOND1
    #>       3       3       1       3       2       3

## VaR / CVaR

    var_cvar(rets, alpha = 0.95)
    #>     asset         VaR        CVaR
    #> 1     EQ1 0.018348805 0.023653700
    #> 2     EQ2 0.015278103 0.019074063
    #> 3     EQ3 0.024202496 0.029746296
    #> 4    CMD1 0.025586040 0.032379499
    #> 5 CRYPTO1 0.086507269 0.107429605
    #> 6   BOND1 0.005233202 0.006338586

## Monte Carlo price simulation

    paths <- simulate_gbm_paths(100, 0.08, 0.2, time_horizon = 1, n_steps = 252, n_sims = 1000)
    dim(paths)
    #> [1]  253 1000

## Option pricing

    price_option_mc(100, 100, 0.02, 0.2, time_to_maturity = 1, n_sims = 20000)
    #> $price
    #> [1] 8.774883
    #>
    #> $std_error
    #> [1] 0.09681501
    price_option_binomial(100, 100, 0.02, 0.2, time_to_maturity = 1, n_steps = 200, american = TRUE)
    #> [1] 8.906137