### Install PAenhance from GitHub Source: https://github.com/braverock/performanceanalytics/blob/master/sandbox/PAenhance/README.md Use devtools to install the development version of the package from GitHub. ```R install.packages("devtools") devtools::install_github("devtools") library(devtools) install_github("kecoli/PAenhance") library(PAenhance) ``` -------------------------------- ### QQ Plot Chart Example Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Generates a QQ plot. This example is a placeholder and requires specific data and function calls not detailed here. ```R source(ex_file, echo = TRUE, max.deparse.length = Inf) ``` -------------------------------- ### Histogram Chart Examples Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Demonstrates creating histograms with different methods like adding density, rug plots, normal distribution, centered distribution, and QQ plots. Requires the 'edhec' dataset. ```R chart.Histogram(edhec[, "Equity Market Neutral", drop = FALSE]) ``` ```R chart.Histogram(edhec[, "Equity Market Neutral", drop = FALSE], breaks = 40, methods = c("add.density", "add.rug")) ``` ```R chart.Histogram(edhec[, "Equity Market Neutral", drop = FALSE], methods = c("add.density", "add.normal")) ``` ```R chart.Histogram(edhec[, "Equity Market Neutral", drop = FALSE], methods = c("add.density", "add.centered")) ``` ```R chart.Histogram(edhec[, "Equity Market Neutral", drop = FALSE], methods = c("add.centered", "add.density", "add.rug")) ``` ```R chart.Histogram(edhec[, "Equity Market Neutral", drop = FALSE], methods = c("add.centered", "add.density", "add.rug", "add.qqplot")) ``` ```R chart.Histogram(edhec[, "Equity Market Neutral", drop = FALSE], methods = c("add.density", "add.centered", "add.rug", "add.risk")) ``` -------------------------------- ### Relative Performance Chart Example Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Creates a relative performance chart comparing multiple assets against a benchmark, with options for custom color sets and legend placement. Requires the 'managers' dataset. ```R chart.RelativePerformance(managers[, 1:6, drop = FALSE], managers[, 8, drop = FALSE], colorset = rich8equal, legend.loc = "bottomright", main = "Relative Performance to S&P") ``` -------------------------------- ### Roxygen Documentation Template Source: https://github.com/braverock/performanceanalytics/wiki/How-to-Contribute-to-PerformanceAnalytics A standard template for Roxygen documentation, including sections for description, parameters, author, see also, references, examples, aliases, and export. ```r #' A brief, one line description #' #' Detailed description, including equations #' \deqn{\LaTeX}{ascii} #' @param ... please mention what functions you pass the dots into #' @author #' @seealso \cr #' @references #' @examples #' @aliases #' @export ``` -------------------------------- ### Rolling Performance Chart Examples Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Demonstrates plotting rolling performance metrics such as mean return and annualized Sharpe ratio over a specified window. Requires the 'edhec' dataset and options for custom styling. ```R chart.RollingPerformance(edhec[, 1:3], width = 24) ``` ```R chart.RollingPerformance(edhec[, 1:3], FUN = "mean", width = 24, colorset = rich8equal, lwd = 2, legend.loc = "topleft", main = "Rolling 24-Month Mean Return") ``` ```R chart.RollingPerformance(edhec[, 1:3], FUN = "SharpeRatio.annualized", width = 24, colorset = rich8equal, lwd = 2, legend.loc = "topleft", main = "Rolling 24-Month Sharpe Ratio") ``` -------------------------------- ### Regression Chart Example Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Illustrates plotting regression analysis between two sets of variables, including options for different fitting methods and adding a legend. Requires the 'managers' dataset. ```R chart.Regression(managers[, 1:2, drop = FALSE], managers[, 8, drop = FALSE], Rf = managers[, 10, drop = FALSE], excess.returns = TRUE, fit = c("loess", "linear"), legend.loc = "topleft") ``` -------------------------------- ### Sort Drawdowns by Return Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md This example sorts the drawdowns calculated by `findDrawdowns` based on the return value. It's useful for identifying the largest drawdowns. ```R sortDrawdowns(findDrawdowns(edhec[, "Funds of Funds", drop = FALSE])) ``` -------------------------------- ### Calculate Omega with Interpolation Method Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md This snippet demonstrates calculating Omega using the 'interp' method for a single asset. It requires the Hmisc package to be installed and loaded. ```R if (requireNamespace("Hmisc", quietly = TRUE)) { Omega(edhec[, 13], method = "interp", output = "point") Omega(edhec[, 13], method = "interp", output = "full") } ``` -------------------------------- ### Recreate data objects for debugging Source: https://github.com/braverock/performanceanalytics/wiki/How-to-Contribute-to-PerformanceAnalytics Use this command to print an expression that recreates a specific data object for reproducible examples. ```R dump("x", file=stdout()) ``` -------------------------------- ### Rolling Mean Chart Example Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates and plots the rolling mean for a specified asset. Requires the 'edhec' dataset. ```R chart.RollingMean(edhec[, 9, drop = FALSE]) ``` -------------------------------- ### Rolling Correlation Chart Example Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Plots rolling correlations between multiple assets over a specified window, with options for color sets and legend placement. Requires the 'managers' dataset. ```R chart.RollingCorrelation(managers[, 1:6, drop = FALSE], managers[, 8, drop = FALSE], colorset = rich8equal, legend.loc = "bottomright", width = 24, main = "Rolling 12-Month Correlation") ``` -------------------------------- ### Risk Return Scatter Plot Examples Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Generates a scatter plot of risk and return, with an option to add boxplots. Requires the 'edhec' dataset and a specified risk-free rate. ```R chart.RiskReturnScatter(edhec, Rf = 0.04/12) ``` ```R chart.RiskReturnScatter(edhec, Rf = 0.04/12, add.boxplots = TRUE) ``` -------------------------------- ### Access Package Help Source: https://github.com/braverock/performanceanalytics/blob/master/sandbox/PAenhance/README.md Retrieve the main help documentation for the PAenhance package. ```R help(package = "PAenhance") ``` -------------------------------- ### Display Warning Message Source: https://github.com/braverock/performanceanalytics/wiki/How-to-Contribute-to-PerformanceAnalytics Example of a warning message generated when a function makes assumptions about user data. ```R Warning message: In Return.rebalancing(managers[, 1:4]) : NA's detected: filling NA's with zeros ``` -------------------------------- ### Load and Inspect edhec Dataset Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Initializes the environment and displays the first few rows of the edhec dataset. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) ``` ```R > data(edhec) > head(edhec) ``` -------------------------------- ### Calculate Treynor Ratio with multiple assets and benchmarks Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Illustrates calculating the Treynor Ratio for multiple assets (columns 1 to 6) against multiple benchmarks (columns 8 and 7), using both fixed and time-varying risk-free rates. Requires 'managers' dataset. ```R round(TreynorRatio(managers[, 1:6], managers[, 8:7], + Rf = 0.035/12), 4) ``` ```R round(TreynorRatio(managers[, 1:6], managers[, 8:7], + Rf = managers[, 10]), 4) ``` -------------------------------- ### Visualize Portfolio Weights and Returns Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Load portfolio weights and generate visualizations for stacked bar charts and cumulative returns. ```R > data(weights) > chart.StackedBar(weights) > x <- Return.portfolio(edhec["2000::", 1:11], weights = weights, + verbose = TRUE) > chart.CumReturns(x$returns) > chart.StackedBar(x$BOP.Weight) > chart.StackedBar(x$BOP.Value) ``` -------------------------------- ### Retrieve Package Description Source: https://github.com/braverock/performanceanalytics/blob/master/sandbox/PAenhance/README.md View the package description file and library help information. ```R packageDescription("PAenhance") # Short description library(help=PAenhance) ``` -------------------------------- ### List Package Functions Source: https://github.com/braverock/performanceanalytics/blob/master/sandbox/PAenhance/README.md Display all functions available within the PAenhance package. ```R ls("package:PAenhance") ``` -------------------------------- ### Initialize PDF Output Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md This code initializes a PDF device for output. It is often used before generating plots or saving results. ```R pdf(file = NULL) ``` -------------------------------- ### Load PerformanceAnalytics and Sample Data Source: https://github.com/braverock/performanceanalytics/wiki/How-to-Contribute-to-PerformanceAnalytics Loads the PerformanceAnalytics package and the 'managers' dataset, then sets and resets console output width. ```r library(PerformanceAnalytics, verbose = FALSE, warn.conflicts = FALSE, quietly = TRUE) data(managers) options(width=200) head(managers) options(width=80) ``` -------------------------------- ### Calculate Treynor Ratio for multiple assets Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Shows how to compute the Treynor Ratio for a range of assets (columns 1 to 6) against a benchmark (column 8), with both fixed and time-varying risk-free rates. Requires 'managers' dataset. ```R round(TreynorRatio(managers[, 1:6], managers[, 8], + Rf = 0.035/12), 4) ``` ```R round(TreynorRatio(managers[, 1:6], managers[, 8], + Rf = managers[, 10]), 4) ``` -------------------------------- ### Expand Grid for Multi-Asset Calculations Source: https://github.com/braverock/performanceanalytics/wiki/How-to-Contribute-to-PerformanceAnalytics Utilize expand.grid to handle combinations of multiple assets and benchmarks before applying a function. ```R pairs = expand.grid(1:NCOL(Ra), 1:NCOL(Rb)) result = apply(pairs, 1, FUN = function(n, xRa, xRb) alpha(xRa[,n[1]], xRb[,n[2]]), xRa = xRa, xRb = xRb) ``` -------------------------------- ### Calculate Up/Down Ratios for a single asset Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Demonstrates calculating various Up/Down Ratio metrics (Capture, Number, Percent) for a single asset against a benchmark using the 'managers' dataset. ```R UpDownRatios(managers[, 1, drop = FALSE], managers[, + 8, drop = FALSE]) ``` -------------------------------- ### CAPM.dynamic with basic inputs Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates CAPM metrics using a single asset and a benchmark. Requires Rf and Z values. ```R data(managers) CAPM.dynamic(managers[, 1, drop = FALSE], managers[, 8, drop = FALSE], Rf = 0.035/12, Z = managers[, 9:10]) ``` -------------------------------- ### Detailed Portfolio Returns with Verbose Output Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates portfolio returns and provides detailed output including returns, contribution, and weights when verbose is set to TRUE. Requires the 'edhec' dataset. ```R data(edhec) Return.portfolio(edhec["1997", 1:5], rebalance_on = "quarters", verbose = TRUE) ``` -------------------------------- ### Calculate Treynor Ratio with different risk-free rates Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Demonstrates calculating the Treynor Ratio using a fixed risk-free rate and a time-varying risk-free rate from a data series. Requires 'managers' dataset. ```R round(TreynorRatio(managers[, 1], managers[, 8], Rf = 0.035/12), + 4) ``` ```R round(TreynorRatio(managers[, 1], managers[, 8], Rf = managers[, + 10]), 4) ``` -------------------------------- ### Calculate SFM Beta and Timing Ratios Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates beta, bull/bear beta, and timing ratios for manager performance data. ```R > data(managers) > SFM.beta(managers[, "HAM1"], managers[, "SP500 TR"], + Rf = managers[, "US 3m TR"]) [1] 0.3900 > SFM.beta(managers[, 1:3], managers[, 8:10], Rf = 0.035/12) Beta : SP500 TR Beta : US 10Y TR Beta : US 3m TR HAM1 0.391 -0.359 0.692 HAM2 0.343 -0.043 4.159 HAM3 0.557 -0.099 4.687 > SFM.beta(managers[, 1], managers[, 8:10], Rf = 0.035/12, + benchmarkCols = FALSE) HAM1 Beta : SP500 TR 0.391 Beta : US 10Y TR -0.359 Beta : US 3m TR 0.692 > SFM.beta.bull(managers[, "HAM2"], managers[, "SP500 TR"], + Rf = managers[, "US 3m TR"]) [1] 0.5226 > SFM.beta.bear(managers[, "HAM2"], managers[, "SP500 TR"], + Rf = managers[, "US 3m TR"]) [1] 0.0698 > TimingRatio(managers[, "HAM2"], managers[, "SP500 TR"], + Rf = managers[, "US 3m TR"]) [1] 7.4852 > if (requireNamespace("RobStatTM", quietly = TRUE)) { + betas <- SFM.beta(managers[, 1:6], managers[, 8:10], Rf = 0.035/12, + method = "Robust", family = "opt", bb = 0.25, max.it = 200, + digits = 4) + betas["HAM1", ] + betas[, "Beta : SP500 TR"] + SFM.beta.bull(managers[, "HAM2"], managers[, "SP500 TR"], + Rf = managers[, "US 3m TR"], method = "Robust") + SFM.beta.bear(managers[, "HAM2"], managers[, "SP500 TR"], + Rf = managers[, "US 3m TR"], method = "Robust") + TimingRatio(managers[, "HAM2"], managers[, "SP500 TR"], Rf = managers[, + "US 3m TR"], method = "Robust", family = "mopt") + } [1] 19.2649 > chart.Regression(managers[, "HAM2"], managers[, "SP500 TR"], + Rf = managers[, "US 3m TR"], fit = "conditional", main = "Conditional Beta") ``` -------------------------------- ### Calculate Fama-Beta with Portfolio Data Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates the Fama-Beta for a given portfolio's monthly returns against a market benchmark. Requires the 'portfolio_bacon' dataset. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) data(portfolio_bacon) print(FamaBeta(portfolio_bacon[, 1], portfolio_bacon[, + 2])) ``` -------------------------------- ### Calculate Up/Down Ratios for multiple assets Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Shows the calculation of Up/Down Ratio metrics for multiple assets (columns 1 to 6) against a single benchmark (column 8) using the 'managers' dataset. ```R UpDownRatios(managers[, 1:6, drop = FALSE], managers[, + 8, drop = FALSE]) ``` -------------------------------- ### Calculate multiple Sharpe Ratio metrics for multiple assets Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculate Standard Deviation, VaR, and ES Sharpe Ratios for multiple assets using a time-varying risk-free rate. Ensure the 'managers' dataset is loaded. ```R SharpeRatio(managers[, 1:9], Rf = managers[, 10, drop = FALSE], FUN = c("StdDev", "VaR", "ES")) ``` -------------------------------- ### Generate and display distribution statistics Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Initializes a PDF device, executes the distribution analysis on manager data, and formats the output using Hmisc for display. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) ``` ```R require("Hmisc") result <- t(table.Distributions(managers[, 1:8])) textplot(format.df(result, na.blank = TRUE, numeric.dollar = FALSE, cdec = c(3, 3, 1)), rmar = 0.8, cmar = 2, max.cex = 0.9, halign = "center", valign = "top", row.valign = "center", wrap.rownames = 20, wrap.colnames = 10, col.rownames = c("red", rep("darkgray", 5), rep("orange", 2)), mar = c(0, 0, 3, 0) + 0.1) title(main = "Portfolio Distributions statistics") ``` ```R dev.off() ``` -------------------------------- ### Load and Display Financial Data Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Loads the 'managers' dataset and displays the head and tail of cumulative product returns. This is useful for understanding the growth of an investment over time. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) ``` ```R > data(managers) > head(managers) HAM1 HAM2 HAM3 HAM4 HAM5 HAM6 EDHEC LS EQ SP500 TR 1996-01-31 0.0074 NA 0.0349 0.0222 NA NA NA 0.0340 1996-02-29 0.0193 NA 0.0351 0.0195 NA NA NA 0.0093 1996-03-31 0.0155 NA 0.0258 -0.0098 NA NA NA 0.0096 1996-04-30 -0.0091 NA 0.0449 0.0236 NA NA NA 0.0147 1996-05-31 0.0076 NA 0.0353 0.0028 NA NA NA 0.0258 1996-06-30 -0.0039 NA -0.0303 -0.0019 NA NA NA 0.0038 US 10Y TR US 3m TR 1996-01-31 0.0038 0.0045 1996-02-29 -0.0353 0.0039 1996-03-31 -0.0105 0.0037 1996-04-30 -0.0173 0.0042 1996-05-31 -0.0054 0.0044 1996-06-30 0.0150 0.0041 > tail(cumprod(1 + managers), 1) HAM1 HAM2 HAM3 HAM4 HAM5 HAM6 EDHEC LS EQ SP500 TR 2006-12-31 4.1266 NA 4.7067 3.5294 NA NA NA 2.7616 US 10Y TR US 3m TR 2006-12-31 1.7340 1.5296 ``` ```R dev.off() ``` -------------------------------- ### Calculate Information Ratio vs. Single Benchmark (Multiple Assets) Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates the Information Ratio for multiple assets against a single benchmark using the 'managers' dataset. ```R InformationRatio(managers[, 1:6], managers[, 8, drop = FALSE]) ``` -------------------------------- ### Calculate Information Ratio vs. Multiple Benchmarks Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates the Information Ratio for multiple assets against multiple benchmarks using the 'managers' dataset. ```R InformationRatio(managers[, 1:6], managers[, 8:7]) ``` -------------------------------- ### Calculate Information Ratio vs. Single Benchmark Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates the Information Ratio of a single asset against a benchmark using the 'managers' dataset. Requires specifying assets and benchmark. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) data(managers) InformationRatio(managers[, "HAM1", drop = FALSE], + managers[, "SP500 TR", drop = FALSE]) ``` -------------------------------- ### Snapshot Price Data Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Loads and displays the head of the prices dataset. Use this to inspect historical price data. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) ``` ```R data(prices) head(prices) ``` ```R dev.off() ``` -------------------------------- ### Execute rolling function analysis Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Initializes the environment and executes the rolling mean calculation on the managers dataset. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) ``` ```R > data(managers) > apply.rolling(managers[, 1, drop = FALSE], FUN = "mean", + width = 36) ``` -------------------------------- ### Calculate Value at Risk (VaR) Source: https://context7.com/braverock/performanceanalytics/llms.txt Computes VaR using various statistical methods and supports portfolio risk decomposition. ```r data(edhec) # Historical VaR at 95% confidence VaR(edhec, p = 0.95, method = "historical") # Gaussian (parametric) VaR VaR(edhec, p = 0.95, method = "gaussian") # Modified Cornish-Fisher VaR (accounts for skewness and kurtosis) VaR(edhec, p = 0.95, method = "modified") # 99% VaR VaR(edhec, p = 0.99, method = "modified") # VaR with outlier cleaning (Boudt method) VaR(edhec, p = 0.95, clean = "boudt") # Component VaR decomposition for equal-weighted portfolio component_var <- VaR(edhec, p = 0.95, clean = "boudt", portfolio_method = "component") component_var$hVaR # Total portfolio VaR component_var$contribution # Each asset's VaR contribution component_var$pct_contrib_hVaR # Percentage contribution # Custom portfolio weights weights <- rep(1/ncol(edhec), ncol(edhec)) VaR(edhec, p = 0.95, method = "modified", weights = weights, portfolio_method = "single") # Marginal VaR VaR(edhec, p = 0.95, method = "gaussian", weights = weights, portfolio_method = "marginal") ``` -------------------------------- ### Calculate VaR Sharpe Ratio with Gaussian method Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculate the Sharpe Ratio using VaR with the 'gaussian' method and a specified risk-free rate. Ensure the 'edhec' dataset is loaded. ```R SharpeRatio(edhec[, 6, drop = FALSE], Rf = 0.04/12, FUN = "VaR", method = "gaussian") ``` -------------------------------- ### Calculate ActivePremium Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates the active premium for portfolio returns against a benchmark. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) ``` ```R dev.off() ``` -------------------------------- ### Return.portfolio Source: https://context7.com/braverock/performanceanalytics/llms.txt Calculates weighted portfolio returns with support for rebalancing, transaction costs, and detailed contribution analysis. ```APIDOC ## Return.portfolio ### Description Calculates weighted portfolio returns with support for rebalancing, transaction costs, and detailed contribution analysis. ### Parameters #### Request Body - **R** (xts/zoo/data.frame) - Required - Asset return series - **weights** (numeric) - Optional - Asset weights - **rebalance_on** (string) - Optional - Rebalancing frequency (e.g., "quarters", "months") - **rebal_cost** (numeric) - Optional - Transaction cost per rebalance - **verbose** (boolean) - Optional - If TRUE, returns detailed contribution and weight data ### Request Example Return.portfolio(edhec["1997", 1:5], rebalance_on = "quarters", rebal_cost = 0.002) ### Response #### Success Response (200) - **returns** (xts) - Portfolio returns - **contribution** (xts) - Per-period contribution by asset (if verbose=TRUE) ``` -------------------------------- ### Calculate Portfolio Returns Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates portfolio returns for a given period. Ensure the 'edhec' dataset is loaded and the 'Return.portfolio' function is available. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) ``` ```R data(edhec) Return.portfolio(edhec["1997", 1:5], rebalance_on = "quarters") ``` -------------------------------- ### Calculate Portfolio Returns with Rebalancing Costs Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculate portfolio returns with quarterly rebalancing and specific transaction costs. ```R > Return.portfolio(edhec["1997", 1:5], rebalance_on = "quarters", + rebal_cost = 0.002) ``` -------------------------------- ### Visualize Performance Summary Source: https://context7.com/braverock/performanceanalytics/llms.txt Generates a multi-panel chart displaying cumulative returns, periodic returns, and drawdowns. ```r data(edhec) # Basic performance summary chart charts.PerformanceSummary(edhec[, c(1, 13)]) # With geometric returns and wealth index charts.PerformanceSummary(edhec[, 1:3], geometric = TRUE, wealth.index = TRUE, main = "EDHEC Performance") # Using ggplot2 engine charts.PerformanceSummary(edhec[, c(1, 13)], plot.engine = "ggplot2") # Using plotly for interactive charts charts.PerformanceSummary(edhec[, c(1, 13)], plot.engine = "plotly") ``` -------------------------------- ### Calculate CAPM and Factor Metrics Source: https://context7.com/braverock/performanceanalytics/llms.txt Calculates beta sensitivity, bull/bear market betas, and timing ratios for asset managers. ```r data(managers) # Basic CAPM beta calculation SFM.beta(managers[, "HAM1"], managers[, "SP500 TR"], Rf = managers[, "US 3m TR"]) # Beta : SP500 TR # HAM1 0.366 # Multiple managers vs multiple benchmarks SFM.beta(managers[, 1:3], managers[, 8:10], Rf = 0.035/12) # Bull market beta (up-market only) SFM.beta.bull(managers[, "HAM2"], managers[, "SP500 TR"], Rf = managers[, "US 3m TR"]) # Bear market beta (down-market only) SFM.beta.bear(managers[, "HAM2"], managers[, "SP500 TR"], Rf = managers[, "US 3m TR"]) # Timing Ratio (bull beta / bear beta) TimingRatio(managers[, "HAM2"], managers[, "SP500 TR"], Rf = managers[, "US 3m TR"]) # Robust regression method (requires RobStatTM package) # SFM.beta(managers[, 1:6], managers[, 8:10], Rf = 0.035/12, # method = "Robust", family = "mopt") ``` -------------------------------- ### Calculate Component VaR using Boudt Cleaning Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates the marginal and percentage contribution to VaR for each asset in the portfolio, using the 'boudt' cleaning method and assuming an equally weighted portfolio if no weights are provided. ```R VaR(edhec, clean = "boudt", portfolio_method = "component") ``` -------------------------------- ### Analyze Portfolio with Transaction Costs Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculate portfolio returns including rebalancing costs and visualize the resulting performance and weights. ```R > x_cost <- Return.portfolio(edhec["2000::", 1:11], + weights = weights, verbose = TRUE, rebal_cost = 0.01) > chart.CumReturns(x_cost$returns) > chart.StackedBar(x_cost$BOP.Weight) > chart.StackedBar(x_cost$BOP.Value) ``` -------------------------------- ### Calculate VaR Sharpe Ratio Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculate the Sharpe Ratio using the Value at Risk (VaR) method. Ensure the 'edhec' dataset is loaded. ```R data(edhec) SharpeRatio(edhec[, 6, drop = FALSE], FUN = "VaR") ``` -------------------------------- ### Estimate Shrinkage Moments for ES Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Shows how to compute Expected Shortfall (ES) using shrinkage-based moments versus standard method-of-moments estimators. ```R > data(edhec) > f <- rowSums(edhec) > targets <- c(1, 3, 4) > sigma <- M2.shrink(edhec, targets, f)$M2sh > m3 <- M3.shrink(edhec, targets, f)$M3sh > m4 <- M4.shrink(edhec, targets, f)$M4sh > mu <- colMeans(edhec) > p <- length(mu) > ES(p = 0.95, portfolio_method = "component", weights = rep(1/p, + p), mu = mu, sigma = sigma, m3 = m3, m4 = m4) $MES [1] 0.0360 $contribution [1] 0.0047 -0.0004 0.0045 0.0065 0.0011 [6] 0.0049 0.0028 0.0011 0.0037 0.0026 [11] 0.0031 -0.0024 0.0034 $pct_contrib_MES [1] 0.1311 -0.0126 0.1256 0.1824 0.0310 0.1379 [7] 0.0789 0.0330 0.1048 0.0737 0.0873 -0.0679 [13] 0.0943 > sigma <- cov(edhec) > m3 <- M3.MM(edhec) > m4 <- M4.MM(edhec) > ES(p = 0.95, portfolio_method = "component", weights = rep(1/p, + p), mu = mu, sigma = sigma, m3 = m3, m4 = m4) $MES [1] 0.0362 $contribution [1] 0.0059 -0.0028 0.0052 0.0062 0.0009 [6] 0.0058 0.0034 0.0001 0.0036 0.0034 [11] 0.0037 -0.0031 0.0034 $pct_contrib_MES [1] 0.1648 -0.0774 0.1456 0.1724 0.0250 [6] 0.1626 0.0955 0.0036 0.1000 0.0954 [11] 0.1042 -0.0869 0.0948 ``` -------------------------------- ### Execute Return.locScaleRob with edhec data Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Loads the edhec dataset and computes robust location and scale estimates using the RobStatTM package if available. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) ``` ```R data(edhec, package = "PerformanceAnalytics") class(edhec) names(edhec) = c("CA", "CTA", "DIS", "EM", "EMN", "ED", "FIA", "GM", "LS", "MA", "RV", "SS", "FOF") if (suppressMessages(suppressWarnings(requireNamespace("RobStatTM", quietly = TRUE)))) { outRob <- suppressMessages(Return.locScaleRob(edhec$CA)) } ``` -------------------------------- ### Calculate Portfolio Returns with Return.portfolio Source: https://context7.com/braverock/performanceanalytics/llms.txt Computes weighted portfolio returns with support for rebalancing, transaction costs, and contribution analysis. ```r data(edhec) # Simple equal-weighted portfolio with quarterly rebalancing portfolio_returns <- Return.portfolio(edhec["1997", 1:5], rebalance_on = "quarters") head(portfolio_returns) # Custom weights with verbose output showing contributions weights <- c(0.4, 0.3, 0.2, 0.1) result <- Return.portfolio(edhec["1997:1999", 1:4], weights = weights, rebalance_on = "months", verbose = TRUE) # Access detailed portfolio analytics head(result$returns) # Portfolio returns head(result$contribution) # Per-period contribution by asset head(result$BOP.Weight) # Beginning of period weights head(result$EOP.Weight) # End of period weights head(result$BOP.Value) # Beginning of period values head(result$EOP.Value) # End of period values # Add transaction costs (20 basis points per rebalance) portfolio_with_costs <- Return.portfolio(edhec["1997", 1:5], rebalance_on = "quarters", rebal_cost = 0.002) # Time-varying weights using xts object data(weights) chart.StackedBar(weights) x <- Return.portfolio(edhec["2000::", 1:11], weights = weights, verbose = TRUE) chart.CumReturns(x$returns) ``` -------------------------------- ### Calculate VaR using Historical Method Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates Value at Risk using the historical simulation method. Ensure the 'edhec' dataset is loaded and the 'VaR' function is available. ```R data(edhec) VaR(edhec, p = 0.95, method = "historical") ``` -------------------------------- ### Create a unified diff patch Source: https://github.com/braverock/performanceanalytics/wiki/How-to-Contribute-to-PerformanceAnalytics Generate a patch file from changes made to a source file using the diff utility in a shell environment. ```bash diff -u original.R revised.R > original.patch ``` -------------------------------- ### Summary Tables Source: https://context7.com/braverock/performanceanalytics/llms.txt Function to create a summary table of annualized returns, standard deviation, and Sharpe Ratio. ```APIDOC ## table.AnnualizedReturns ### Description Creates a summary table with annualized return, standard deviation, and Sharpe Ratio. ### Method table.AnnualizedReturns ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r data(managers) # Summary statistics for all managers table.AnnualizedReturns(managers[, 1:8]) ``` ### Response #### Success Response (200) - **Annualized Return** (numeric) - The annualized return. - **Annualized Std Dev** (numeric) - The annualized standard deviation. - **Annualized Sharpe (Rf=0%)** (numeric) - The annualized Sharpe Ratio with a risk-free rate of 0%. #### Response Example ``` # HAM1 HAM2 HAM3 HAM4 # Annualized Return 0.1411 0.0974 0.0869 0.0377 # Annualized Std Dev 0.0876 0.0736 0.0756 0.0611 # Annualized Sharpe (Rf=0%) 1.6106 1.3239 1.1488 0.6169 ``` ``` -------------------------------- ### Calculate Returns with Return.calculate Source: https://context7.com/braverock/performanceanalytics/llms.txt Converts price series into discrete or log returns. Typically the initial step in financial data analysis. ```r library(PerformanceAnalytics) # Load sample price data data(prices) # Calculate discrete (simple) returns from prices returns_discrete <- Return.calculate(prices, method = "discrete") head(returns_discrete) # IBM # 2007-01-03 NA # 2007-01-04 -0.0129199 # 2007-01-05 -0.0056573 # 2007-01-08 0.0092949 # Calculate log (continuous) returns returns_log <- Return.calculate(prices, method = "log") head(returns_log) # IBM # 2007-01-04 -0.0130042 # 2007-01-05 -0.0056734 # 2007-01-08 0.0092519 ``` -------------------------------- ### Calculate Sharpe Ratio for multiple assets with a fixed risk-free rate Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculate the Sharpe Ratio for multiple assets simultaneously using a constant risk-free rate. Ensure the 'managers' dataset is loaded. ```R SharpeRatio(managers[, 1:6], Rf = 0.035/12, FUN = "StdDev") ``` -------------------------------- ### Return.calculate Source: https://context7.com/braverock/performanceanalytics/llms.txt Calculates simple (discrete) or log (compound) returns from a price series. ```APIDOC ## Return.calculate ### Description Calculates simple (discrete) or log (compound) returns from a price series. This is typically the first function used to convert price data into returns for further analysis. ### Parameters #### Request Body - **prices** (xts/zoo/data.frame) - Required - Price series data - **method** (string) - Optional - Calculation method: "discrete" or "log" ### Request Example Return.calculate(prices, method = "discrete") ### Response #### Success Response (200) - **returns** (xts) - Calculated return series ``` -------------------------------- ### Calculate multiple Sharpe Ratio metrics for all assets with a fixed risk-free rate Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculate Standard Deviation, VaR, and ES Sharpe Ratios for all assets in the 'edhec' dataset using a fixed risk-free rate. Ensure the 'edhec' dataset is loaded. ```R SharpeRatio(edhec, Rf = 0.04/12, FUN = c("StdDev", "VaR", "ES")) ``` -------------------------------- ### Calculate VaR with Boudt Cleaning Method Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates Value at Risk using the 'boudt' cleaning method, which applies specific adjustments to the data. ```R VaR(edhec, clean = "boudt") ``` -------------------------------- ### Calculate Annualized Sharpe Ratio Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Demonstrates calculating the annualized Sharpe ratio using different risk-free rate inputs and geometric settings. ```R > data(managers) > SharpeRatio.annualized(managers[, 1, drop = FALSE], + Rf = 0.035/12) HAM1 Annualized Sharpe Ratio (Rf=3.5%, p=95%): 1.1091 > SharpeRatio.annualized(managers[, 1, drop = FALSE], + Rf = managers[, 10, drop = FALSE]) HAM1 Annualized Sharpe Ratio (Rf=3.9%, p=95%): 1.0679 > SharpeRatio.annualized(managers[, 1:6], Rf = 0.035/12) HAM1 HAM2 HAM3 HAM4 Annualized Sharpe Ratio (Rf=3.5%, p=95%): 1.1091 1.0592 0.9041 0.5274 HAM5 HAM6 Annualized Sharpe Ratio (Rf=3.5%, p=95%): 0.0887 1.1838 > SharpeRatio.annualized(managers[, 1:6], Rf = managers[, + 10, drop = FALSE]) HAM1 HAM2 HAM3 HAM4 Annualized Sharpe Ratio (Rf=3.9%, p=95%): 1.0679 1.0417 0.8809 0.5063 HAM5 HAM6 Annualized Sharpe Ratio (Rf=3.9%, p=95%): 0.1226 1.3132 > SharpeRatio.annualized(managers[, 1:6], Rf = managers[, + 10, drop = FALSE], geometric = FALSE) HAM1 HAM2 HAM3 HAM4 Annualized Sharpe Ratio (Rf=3.9%, p=95%): 1.0679 1.0417 0.8809 0.5063 HAM5 HAM6 Annualized Sharpe Ratio (Rf=3.9%, p=95%): 0.1226 1.3132 ``` -------------------------------- ### Calculate PainRatio for a Portfolio Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Use PainRatio to calculate the 'Pain Index' for a given portfolio's monthly returns. Ensure the portfolio data is correctly formatted. ```r pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) ``` ```r data(portfolio_bacon) print(PainRatio(portfolio_bacon[, 1])) ``` ```r data(managers) print(PainRatio(managers["1996"])) ``` ```r print(PainRatio(managers["1996", 1])) ``` ```r dev.off() ``` -------------------------------- ### Chart Capture Ratios Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Generates a capture ratio chart comparing managers to a benchmark. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) ``` ```R data(managers) chart.CaptureRatios(managers[, 1:6], managers[, 7, + drop = FALSE]) ``` -------------------------------- ### Calculate Calmar and Sterling Ratios Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates the Calmar Ratio and Sterling Ratio. Requires portfolio data. Sterling Ratio includes an excess return parameter. ```R pdf(file = NULL) suppressWarnings(try({ source(ex_file, echo = TRUE, max.deparse.length = Inf) }, silent = TRUE)) ``` ```R data(managers) CalmarRatio(managers[, 1, drop = FALSE]) ``` ```R CalmarRatio(managers[, 1:6]) ``` ```R SterlingRatio(managers[, 1, drop = FALSE]) ``` ```R SterlingRatio(managers[, 1:6]) ``` ```R dev.off() ``` -------------------------------- ### Calculate MES and Contributions with Boudt Cleaning Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates the Marginal Expected Shortfall (MES) and its contributions using the Boudt cleaning method. Requires the 'robustbase' package and the 'edhec' dataset. Assumes equal weights if none are provided. ```R if (requireNamespace("robustbase", quietly = TRUE)) { ES(edhec, clean = "boudt") ES(edhec, clean = "boudt", portfolio_method = "component") } ``` -------------------------------- ### Calculate VaR using Modified Method Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculates Value at Risk using the modified VaR method, which accounts for skewness and kurtosis in the return distribution. ```R VaR(edhec, p = 0.95, method = "modified") ``` -------------------------------- ### Generate Drawdown Summary Table Source: https://context7.com/braverock/performanceanalytics/llms.txt Creates a table summarizing worst drawdowns with metrics like depth and duration. ```r data(edhec) data(managers) # Top 5 worst drawdowns for first EDHEC index table.Drawdowns(edhec[, 1, drop = FALSE]) # From Trough To Depth Length To Trough Recovery # 1 2007-11-30 2008-10-31 2009-05-31 -0.1903 19 12 7 # 2 2000-04-30 2000-05-31 2000-07-31 -0.0349 4 2 2 # 3 2002-05-31 2002-07-31 2002-11-30 -0.0272 7 3 4 # Top 10 worst drawdowns table.Drawdowns(managers[, 1, drop = FALSE], top = 10) ``` -------------------------------- ### Calculate NetSelectivity Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Computes the net selectivity measure for portfolios using the portfolio_bacon or managers datasets. ```R data(portfolio_bacon) print(NetSelectivity(portfolio_bacon[, 1], portfolio_bacon[, 2])) ``` ```R data(managers) print(NetSelectivity(managers["1996", 1], managers["1996", 8])) ``` ```R print(NetSelectivity(managers["1996", 1:5], managers["1996", 8])) ``` -------------------------------- ### Calculate VaR Sharpe Ratio with a specified risk-free rate Source: https://github.com/braverock/performanceanalytics/blob/master/tests/testthat/_snaps/all_snapshots.md Calculate the Sharpe Ratio using VaR with a specific risk-free rate. Ensure the 'edhec' dataset is loaded. ```R SharpeRatio(edhec[, 6, drop = FALSE], Rf = 0.04/12, FUN = "VaR") ```