# ApaLibNET Online Help (Version 3.0.0) > Reference for all 1,200 worksheet functions of the ApaLibNET Excel add-in by Andreas Steiner Consulting GmbH: result, syntax, algorithm and remarks for each function. Online version: https://www.andreassteiner.net/help/ # Online Help URL: https://www.andreassteiner.net/help/online-help/ The ApaLibNET online help at [www.andreassteiner.net/help](https://www.andreassteiner.net/help/) is the documentation of the add-in. It contains one page per worksheet function with result, syntax and remarks, and the guides on installation, activation, updating and licensing. The online help always describes the latest release. In the Excel function wizard (Insert Function dialog), the link “Help on this function” opens the online help page of the selected function. The search field on the help pages finds functions by name. The complete function reference is also available as a single plain-text file at [www.andreassteiner.net/help/llms-full.txt](https://www.andreassteiner.net/help/llms-full.txt), for example to provide it to an AI assistant. # Installation and Deinstallation URL: https://www.andreassteiner.net/help/installation-and-deinstallation/ ApaLibNET installation is a guided setup process. After you have downloaded the add-in, just double-click Setup.exe to start the setup wizard. Restrictive **security settings** can cause various security alerts to show during installation; press “continue”, “trust” or similar when asked. In certain ***installation scenarios***, the add-in has to be loaded manually… 1. **Scenario A: multiple Excel versions, multiple add-in versions** Install the add-in from Setup.exe as usual, but then deselect “Launch Excel to activate the add-in”; load the correct XLL in the correct Excel version manually (see below). 2. **Scenario B: multiple Excel versions, one add-in ** Install the add-in from Setup.exe as usual, but then deselect “Launch Excel to activate the add-in”; load the correct XLL in the correct Excel version manually (see below). It is not possible to run multiple add-in versions in the same Excel version. **Manually loading the add-in in Excel**… 1. Open Excel, press Alt + t + I (press one key after the other) 2. “Browse…” to the directory in which ApaLibNET.xll is stored 3. Select ApaLibNET.xll and press OK ![Figure](https://www.andreassteiner.net/help/assets/img/image1.png) If you would like to **deinstall** the add-in, go to Windows Settings \| Apps \| Installed Apps and select Uninstall. This will delete the add-in and all related files from your computer. Depending on your settings, you will be prompted by Excel to remove the entry in the Add-Ins menu or you will have to remove the entry manually. # Activation URL: https://www.andreassteiner.net/help/activation/ When the add-in is loaded the first time on a computer, you will be asked for your license code in order to activate the add-in… ![Figure](https://www.andreassteiner.net/help/assets/img/image2.png) Your **license code** can be found in the email sent to you after purchasing the add-in. Restrictive **security settings** (e.g. firewall) can cause activation to fail. We do not recommend switching off system security on a permanent basis, but it might be required to relax security settings temporarily in order for the add-in to update correctly. The add-in communicates with the license server at https://www.andreassteiner.net/license/ over HTTPS (port 443); allowing this address in the firewall or proxy is the preferred alternative. After being prompted for your license code, you will be asked to provide a **name** for your computer… ![Figure](https://www.andreassteiner.net/help/assets/img/image3.png) Naming allows you to deactivate your computer when transferring the license to a new computer. # Starting Up URL: https://www.andreassteiner.net/help/starting-up/ In order to be able to use the add-in, **you have to be connected to the Internet when Excel starts up**. Once you have started Excel, the add-in will continue to operate even if you put your computer in sleep/hibernate mode. When for example going on business trips with a laptop computer, make sure you start Excel at home when connected to the Internet; the add-in will be available when traveling as long as Excel is not closed. Restrictive **security settings** (e.g. firewall) can cause starting up to fail. We do not recommend switching off system security on a permanent basis, but it might be required to relax security settings temporarily in order for the add-in to start up. The add-in communicates with the license server at https://www.andreassteiner.net/license/ over HTTPS (port 443); allowing this address in the firewall or proxy is the preferred alternative. # Updating URL: https://www.andreassteiner.net/help/updating/ The add-in will check for new releases upon startup and prompts the user to install them automatically. The installed update will be available *the next time* Excel or the add-in is started. ![Figure](https://www.andreassteiner.net/help/assets/img/image4.png) Installing updates requires an Internet connection, security settings that allow incoming and outgoing traffic to the domain [www.andreassteiner.net](http://www.andreassteiner.net) in order to download new versions and sufficient user privileges to install them. Restrictive **security settings** (e.g. firewall) can cause updates to fail. We do not recommend switching off system security on a permanent basis, but it might be required to relax security settings temporarily in order for the add-in to update correctly. The add-in communicates with the license server at https://www.andreassteiner.net/license/ over HTTPS (port 443); allowing this address in the firewall or proxy is the preferred alternative. It is possible that restrictive **user privileges** are preventing the installation of updates. In these cases, we recommend to uninstall the add-in, delete all files and folders (important!) and finally download and reinstall the latest version. As a temporary workaround, running Excel as an administrator (“Run as administrator” in Windows Explorer, see screenshot below) might help. ![Figure](https://www.andreassteiner.net/help/assets/img/image5.png) A **backup** of the release currently used will be created. It is therefore possible to manually roll back to the previous version. Close Excel, go to the installation folder, delete ApaLibNET.xll (the updated version) and then rename ApaLibNET.old to ApaLibNET.xll. The next time Excel is started, choose not to update. # Moving to a New Excel Version URL: https://www.andreassteiner.net/help/moving-to-a-new-excel-version/ It is possible to continue using the ApaLibNET add-in when installing **new Excel version with identical bitness** (e.g. moving from Excel 2007 32-bit to Excel 2010 32-bit) on the same computer. In your new Excel version, just manually load the add-in (see above, section “Installation” for step-by-step instructions) Moving to **Excel versions with different** **bitness** (e.g. switching from Excel 2007 32-bit to Excel 2010 64-bit) requires a fresh installation of the add-in. First uninstall the add-in on your computer (make sure all files and folders have been deleted), download the latest version and install it as described above under “Installation”. The license is transferred automatically when moving to an Excel version with different bitness on the same computer. # Deactivating Old Computers URL: https://www.andreassteiner.net/help/deactivating-old-computers/ Although the ApaLibNET license is tied to your computer, it is possible to assign it to a new computer when retiring an activated computer. You can deactivate computers by calling the function **apaLicense.Computer.Deactivate()** on the computer you would like to deactivate***.*** If you already do not have access to your old computer anymore, you can deactivate any of your computers with the online **License Manager** on [andreassteiner.net/licensemanager](https://www.andreassteiner.net/licensemanager). To login to the License Manager, you need to submit your license code and your email address used when purchasing the license. On your new computer, install and activate the add-in as described in the sections “Installation” and “Activation” above. If the number of computers of your license is exceeded, you will be prompted whether you would like to deactivate a computer during activation. **Important*: **Deactivation is permanent**, i.e. you cannot run the add-in on a deactivated computer at a future point in time. Switching computers is not covered by the scope of the license agreement*. # Changing Email Address URL: https://www.andreassteiner.net/help/changing-email-address/ You can assign a new email address to your license in the online License Manager on [andreassteiner.net/licensemanager](https://www.andreassteiner.net/licensemanager). To login to the **License Manager**, you need to submit your license code and your current email address. If you have not changed the email address before, your current email address is the one you used when purchasing the license. # At the End of the Subscription Period URL: https://www.andreassteiner.net/help/at-the-end-of-the-subscription-period/ One year after the purchase date, the subscription period will end and the add-in will stop to work. If you would like to continue using the add-in, you have to **purchase another subscription** on [andreassteiner.net/apalibnet](http://www.andreassteiner.net/apalibnet). You will not receive any notification to renew your license, neither by email nor by the add-in itself. **apaLicense.ExpiryDate()** returns the expiry date of your current license. # Information About Your License URL: https://www.andreassteiner.net/help/information-about-your-license/ You find general information about your license (expiry date, number of computers, email address, names of activated computers, deactivated computers) in online **License Manager** on [andreassteiner.net/licensemanager](https://www.andreassteiner.net/licensemanager). To login to the License Manager, you need to submit your license code and your email address used when purchasing the license. As described above, you can change your email address and deactivate computers in the License Manager. # General Features URL: https://www.andreassteiner.net/help/general-features/ Most functionality in ApaLibNET is calculated from return **time series**. A “time series” is a set of return observations organized in a vector (a range consisting of one column and a certain number of rows). Note that time series data is ordered data: The first entry in the vector is assumed to be the first observation. A “time series matrix” is a set of time series, each column containing one series and each row containing observations at a particular point in time. **Returns** are percentage figures, i.e. r = 2.54% = 0.0254. Returns can be of any **frequency**, i.e. daily, monthly. The results will be of the same frequency (i.e. daily, monthly). All input returns are assumed to be of the same frequency (e.g. portfolio returns and risk-free rate when calculating a Sharpe Ratio). Functions returning more than one result (e.g. apaMaxDrawdown) have to be entered as so-called “**array formulas**”. With the help of the function apaResize(), array formulas are adjusted automatically to display all results. We are offering **example spreadsheets** illustrating the use of the function. We are also offering video tutorials on how to work with the functions efficiently. Please visit [www.andreassteiner.net/apalib](http://www.andreassteiner.net/apalib) for more information. When performing invalid calculations, functions will return system-level **error messages** whenever possible. Compared to Excel’s \#VALUE, explicit error messages help users debugging their spreadsheets. The add-in does not make use of Microsoft’s built-in random number generator, but the “**Multiply-With-Carry**” generator developed by George Marsaglia. This random generator invokes simple integer arithmetic only and leads to very fast generation of sequences of random numbers (about 15% faster than the internal generator) with an immense period, passing all tests in the DIEHARD tests of randomness. Several numerical intense functions can be “switched off” with an optional Boolean parameter “**DoSwitchOff**”. If DoSwitchOff=TRUE, the functions will return an error-like string “#OFF” Several numerical intense functions will not perform calculations in Excel’s function wizard. “**\#WIZARD**” will be shown instead of the result. A check for **available updates** is performed whenever the add-in is loaded and the computer is connected to the Internet. The user can control whether new releases are installed or not. Note that the new version is available when the add-in is loaded *the next time*. **Jagged functions** can handle non-numeric input data, i.e. blanks, Excel error messages, text data etc. # apaAbsorptionRatio(Returns, nEigenvectors) URL: https://www.andreassteiner.net/help/apaabsorptionratio/ ## Result Calculates the absorption ratio, i.e. the fraction of total variance explained by a given number of eigenvectors. ## Syntax *Returns*: nObs x nAssets matrix of returns, each column containing a time series *nEigenvectors*: number of eigenvectors to include ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image6.svg) ## Remarks The Absorption Ratio measures the fraction of total variance of a set of assets explained by a certain number of eigenvectors, i.e. statistical factors. This measure can be used to quantify systemic risk or degree of diversification in the sense of concentration in statistical factor exposures. See for example Kritzman/Li/Page/Rigobon (2010): “Principal Components as a Measure of Systemic Risk”, SSRN Working Paper. Uses sample covariances (denominator n − 1); population moments give the same ratio. # apaActiveShare(PortfolioWeights, BenchmarkWeights) URL: https://www.andreassteiner.net/help/apaactiveshare/ ## Result Calculates the active share, i.e. half the sum of absolute differences between portfolio and benchmark weights. ## Syntax *PortfolioWeights*: vector containing portfolio weights *BenchmarkWeights*: vector containing benchmark weights ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image7.svg) # apaActivePassiveRatio(Weights, Returns) URL: https://www.andreassteiner.net/help/apaactivepassiveratio/ ## Result Calculates Lo’s active/passive ratio of a portfolio, i.e. the share of the average portfolio return due to active management (time-varying weights). ## Syntax *Weights*: r x n matrix of constituent weights over time *Returns*: r x n matrix of constituent returns, each column containing a time series ## Algorithm Passive component: ![Formula](https://www.andreassteiner.net/help/assets/eq/image8.svg) Active component: ![Formula](https://www.andreassteiner.net/help/assets/eq/image9.svg) Active-Passive Ratio: ![Formula](https://www.andreassteiner.net/help/assets/eq/image10.svg) ## Remarks See Andrew Lo (2008): “Where Do Alphas Come From? A Measure of the Value of Active Investment Management”, Journal of Investment Management. # apaAdjustedSharpeRatio(PortfolioReturns, RiskfreeReturns) URL: https://www.andreassteiner.net/help/apaadjustedsharperatio/ ## Result Calculates the adjusted Sharpe ratio, a risk-adjusted performance measure, i.e. the Sharpe ratio with adjustments for skewness and kurtosis. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *RiskfreeReturns*: r x 1 vector of riskfree returns (i.e. a time series) or a single riskfree rate ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image11.svg) ## Remarks Uses sample volatility, sample skewness and sample excess kurtosis (as Excel STDEV.S, SKEW and KURT). # apaARIMA.AutoFit(Series, maxP, maxD, maxQ, Criterion, IncludeConstant) URL: https://www.andreassteiner.net/help/apaarima.autofit/ ## Result Selects the integration order d with sequential KPSS stationarity tests, then fits the best ARIMA(p,d,q) model over a user-defined grid of AR and MA orders using AIC, AICc or BIC, and returns the selected model and key fit statistics. Model selection by information criterion chooses the model with the lowest criterion value, balancing fit against model complexity. ## Syntax *Series*: n x 1 or 1 x n range containing the time series *maxP*: maximum AR order *maxD*: maximum integration order; d is chosen by sequential KPSS tests at the 5% level *maxQ*: maximum MA order *Criterion*: AIC, AICc, or BIC *IncludeConstant*: TRUE to include an intercept (d = 0) or a drift (d = 1) (optional, default TRUE). For d ≥ 2 no constant is estimated regardless of this argument, because a constant in the twice or more differenced series would induce a quadratic or higher-order polynomial trend in the forecasts. ## Algorithm The series is flattened to a vector; at least 10 observations are required. maxP, maxD and maxQ are rounded to integers and must be non-negative. The integration order d is determined first. Starting with d = 0, the KPSS level-stationarity statistic of the d-times differenced series is computed; if it exceeds the 5% critical value of 0.463 and d \< maxD, d is increased by one and the test is repeated. The long-run variance in the KPSS statistic uses a Bartlett kernel with floor(3·√n / 13) lags. The grid p = 0, …, maxP and q = 0, …, maxQ is then searched at this fixed d. ARIMA(0,0,0) is excluded. For each admissible model, the parameters are estimated as in apaARIMA.Estimate, but all candidates condition on the first maxP observations of the differenced series, so that every criterion value is computed on the same sample and the values are comparable. The model with the smallest criterion value is selected and re-estimated on its own sample; the reported statistics refer to this re-estimation. The result contains the best model, the deterministic term type and value, the innovation variance, the log-likelihood, AIC, AICc, BIC, the number of evaluations and the termination reason. Two-column result table: - BestModel - DeterministicTermType - DeterministicTermValue - InnovationVariance - LogLikelihood - AIC - AICc - BIC - Evaluations - TerminationReason # apaARIMA.Diagnostics(Series, p, d, q, maxLag, IncludeConstant) URL: https://www.andreassteiner.net/help/apaarima.diagnostics/ ## Result Returns residual diagnostics for an ARIMA(p,d,q) model. ## Syntax *Series*: n x 1 or 1 x n range containing the time series *p*: AR order *d*: integration order *q*: MA order *maxLag*: maximum lag for the residual autocorrelations and the Ljung–Box test (optional, default 20) *IncludeConstant*: TRUE to include an intercept (d = 0) or a drift (d = 1) (optional, default TRUE). For d ≥ 2 no constant is estimated regardless of this argument, because a constant in the twice or more differenced series would induce a quadratic or higher-order polynomial trend in the forecasts. ## Algorithm The series is flattened to a vector; at least 10 observations are required. p, d, q and maxLag are rounded to integers; the orders are validated and maxLag must be at least 1. An ARIMA(p,d,q) model is fitted as in apaARIMA.Estimate. The first p observations of the differenced series are conditioned on and have no residuals; they are excluded from the diagnostics. Residual diagnostics are computed up to maxLag. Two-column result table with: - Mean and variance of the residuals. - Ljung–Box Q statistic and its degrees of freedom. - Residual autocorrelations for lags 1 to maxLag. # apaARIMA.Estimate(Series, p, d, q, IncludeConstant) URL: https://www.andreassteiner.net/help/apaarima.estimate/ ## Result Estimates an ARIMA(p,d,q) model and returns model details, coefficients and the residual series. ## Syntax *Series*: n x 1 or 1 x n range containing the time series *p*: AR order *d*: integration order *q*: MA order *IncludeConstant*: TRUE to include an intercept (d = 0) or a drift (d = 1) (optional, default TRUE). For d ≥ 2 no constant is estimated regardless of this argument, because a constant in the twice or more differenced series would induce a quadratic or higher-order polynomial trend in the forecasts. ## Algorithm The series is flattened to a vector; at least 10 observations are required. p, d and q are rounded to the nearest integers; orders must be non-negative and at least one must be positive. The series is differenced d times. The ARMA(p,q) model of the differenced series is fitted by the conditional Gaussian likelihood (conditional sum of squares) using Nelder–Mead optimization with restarts. The likelihood conditions on the first p observations of the differenced series, and the pre-sample errors are set to zero; the innovation variance, the log-likelihood and the information criteria are based on the remaining n − d − p observations. Stationarity requires all roots of 1 − φ1z − … − φpz^p, and invertibility all roots of 1 + θ1z + … + θqz^q, to lie outside the unit circle. Parameter vectors that violate either condition are rejected. The deterministic term type (none, intercept or drift) and its value are determined. The result table contains: - Model structure (ARIMA(p,d,q)), deterministic term type and value. - Innovation variance and unconditional mean of the differenced series. - Log-likelihood, negative log-likelihood, AIC, AICc and BIC. - Number of evaluations, number of restarts and termination reason. - AR coefficients, MA coefficients, the working series, the fitted values, the residuals and the standardized residuals. For the first p observations, which are conditioned on, the fitted values and residuals are shown as \#N/A. # apaARIMA.Forecast(Series, p, d, q, Horizons, IncludeConstant) URL: https://www.andreassteiner.net/help/apaarima.forecast/ ## Result Forecasts an ARIMA(p,d,q) model and returns point forecasts together with forecast error variances and 95% prediction intervals. ## Syntax *Series*: n x 1 or 1 x n range containing the time series *p*: AR order *d*: integration order *q*: MA order *Horizons*: 1 x m or m x 1 vector of positive forecast horizons *IncludeConstant*: TRUE to include an intercept (d = 0) or a drift (d = 1) (optional, default TRUE). For d ≥ 2 no constant is estimated regardless of this argument, because a constant in the twice or more differenced series would induce a quadratic or higher-order polynomial trend in the forecasts. ## Algorithm The series is flattened to a vector; at least 10 observations are required. Horizons are converted to positive integers; empty or invalid horizons are rejected. p, d and q are rounded to integers and the ARIMA orders are validated. The ARIMA(p,d,q) model is fitted with the chosen deterministic term setting. Forecasts are computed recursively for the requested horizons, replacing future observations with forecasts and future errors with zero. The forecast error variance at horizon h is σ²·(ψ0² + ψ1² + … + ψh−1²), where ψj are the moving-average weights of the integrated model φ(B)(1 − B)^d·yt = c + θ(B)·εt. For d ≥ 1 the variance therefore grows with the horizon, as the integration of the forecast errors requires; for a random walk it equals h·σ². Result table with the columns: - Horizon - MeanForecast - ForecastErrorVariance - Lower95 - Upper95 The 95% interval has the standard form forecast mean $`\pm 1.96 \times`$forecast standard error. # apaAttribution.Consolidate.Level(SegmentNames, Level, PortfolioWeights, PortfolioReturns, BenchmarkWeights, BenchmarkReturns, IsBottomUpOtherwiseTopDown) URL: https://www.andreassteiner.net/help/apaattribution.consolidate.level/ ## Result Consolidates all portfolio segments up to a certain level. ## Syntax *SegmentNames*: segment structure of portfolio. Each column contains a level, rows contain segments. *Level*: level in the structure to consolidate *PortfolioWeights*: n x 1 vector of portfolio segment weights *PortfolioReturns*: n x 1 vector of portfolio segment returns *BenchmarkWeights*: n x 1 vector of benchmark segment weights *BenchmarkReturns*: n x 1 vector of benchmark segment returns *IsBottomUpOtherwiseTopDown*: TRUE to consolidate bottom-up, FALSE to consolidate top-down. Affects the consolidation result # apaAttribution.Consolidate.Segment(SegmentNames, Level, Segment, PortfolioWeights, PortfolioReturns, BenchmarkWeights, BenchmarkReturns, IsRescaled) URL: https://www.andreassteiner.net/help/apaattribution.consolidate.segment/ ## Result Consolidates the portfolio constituents within a certain segment of a level. ## Syntax *SegmentNames*: segment structure of portfolio. Each column contains a level, rows contain segments. *Level*: level in the structure to consolidate *Segment*: number of the segment in the level chosen *PortfolioWeights*: n x 1 vector of portfolio segment weights *PortfolioReturns*: n x 1 vector of portfolio segment returns *BenchmarkWeights*: n x 1 vector of benchmark segment weights *BenchmarkReturns*: n x 1 vector of benchmark segment returns *IsRescaled*: TRUE to rescale weights such that they sum up to 100%, FALSE to simply sum up the weights # apaAttribution.Link.Frongello.Absolute(Attributes) URL: https://www.andreassteiner.net/help/apaattribution.link.frongello.absolute/ ## Result Cumulative chain-linking of absolute attributes (e.g. performance contributions) with the Frongello method. ## Syntax *Attributes*: n x 1 vector of absolute attributes (time series) ## Algorithm Frongello method. # apaAttribution.Link.Frongello.Relative(Attributes, Benchmark) URL: https://www.andreassteiner.net/help/apaattribution.link.frongello.relative/ ## Result Cumulative chain-linking of relative attributes (e.g. performance attribution effects) with the Frongello method. ## Syntax *Attributes*: n x 1 vector of relative attributes (time series) *Benchmark*: n x 1 vector of benchmark totals (time series) ## Algorithm Frongello method. # apaAutoCorrel(Returns, Lag, DoNotShowConfidenceBandsOtherwiseShow) URL: https://www.andreassteiner.net/help/apaautocorrel/ ## Result Returns the autocorrelation coefficients up to a certain lag for one or several time series. If only one time series is provided, the +/-95% confidence bands are reported as well. ## Syntax *Returns*: n x m time series matrix, each column containing a time series *Lag*: maximum lag to shift the data *DoNotShowConfidenceBandsOtherwiseShow*: optional; TRUE (default) to return the coefficients only, FALSE to add the lower and upper confidence bands in the last two columns. ## Algorithm Pearson correlation coefficients are calculated from the lagged time series. ## Remarks More than one time series can be processed. The confidence bands are the approximate 95% white-noise bands −1/n ± 2/√n, where n is the number of observations. # apaAutoCorrel.Spearman(Returns, lag) URL: https://www.andreassteiner.net/help/apaautocorrel.spearman/ ## Result Returns the autocorrelation coefficients and their +/-95% confidence bands up to a certain lag. The autocorrelation coefficients are calculated as Spearman rank correlations. ## Syntax *Returns*: r x 1 vector of returns *lag*: maximum lag ## Algorithm Spearman rank correlation coefficients are calculated from the lagged time series. ## Remarks While Pearson correlations capture linear dependencies, Spearman rank correlations also capture non-linear monotonic dependencies. The confidence bands are the approximate 95% white-noise bands −1/n ± 2/√n, where n is the number of observations. # apaAutoCovar(Returns, Lag, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apaautocovar/ ## Result Returns the autocovariances up to a certain lag for one or several time series. ## Syntax *Returns*: n x m time series matrix, each column containing a time series *Lag*: maximum lag to shift the data *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: FALSE ## Algorithm Covariances are calculated from the lagged time series. ## Remarks If more than one time series is provided, the autocovariances of all time series are calculated. # apaBenfordLaw(TimeSeries) URL: https://www.andreassteiner.net/help/apabenfordlaw/ ## Result Tests Benford’s law (a fraud indicator) for the first digits of a series of figures. ## Syntax *TimeSeries*: r x 1 data vector ## Algorithm See “Benford’s law” on Wikipedia. # apaBeta(PortfolioReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/apabeta/ ## Result Returns the beta of one or several portfolios relative to a benchmark. ## Syntax *PortfolioReturns*: r x c matrix of portfolios returns, each column containing a portfolio. All portfolios are assumed to have the same benchmark. *BenchmarkReturns*: r x 1 vector of benchmark returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image12.svg) ## Remarks Ratio of sample covariance to sample variance (denominator n − 1); population moments give the same beta. # apaBeta.ExpWeighted(TimeSeriesX, TimeSeriesY, HalfLife) URL: https://www.andreassteiner.net/help/apabeta.expweighted/ ## Result Returns the beta of Y relative to X from exponentially weighted observations. ## Syntax *TimeSeriesX*: r x 1 vector containing the X time series data (e.g. benchmark returns) *TimeSeriesY*: r x 1 vector containing the Y time series data (e.g. portfolio returns) *HalfLife*: half-life of the exponential weighting scheme, i.e. the number of past observations after which an observation gets half the weight of the most recent observation ## Remarks Exponentially weighted moments; the weights sum to one (population-type, no small-sample correction). # apaBeta.Semi.Concordant(PortfolioReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/apabeta.semi.concordant/ ## Result Returns the concordant semi-betas, i.e. the betas calculated from observations where portfolio and benchmark returns are both positive or both negative. ## Syntax *PortfolioReturns*: r x c matrix of portfolios returns, each column containing a portfolio. All portfolios are assumed to have the same benchmark. *BenchmarkReturns*: r x 1 vector of benchmark returns ## Remarks Built from sample (n − 1) semi-covariance and variance; population moments give the same beta. # apaBeta.Semi.Mneg(PortfolioReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/apabeta.semi.mneg/ ## Result Returns the Mneg semi-betas, i.e. the betas calculated from observations where portfolio returns are positive and benchmark returns are negative (mixed-sign, negative benchmark). ## Syntax *PortfolioReturns*: r x c matrix of portfolios returns, each column containing a portfolio. All portfolios are assumed to have the same benchmark. *BenchmarkReturns*: r x 1 vector of benchmark returns ## Remarks Built from sample (n − 1) semi-covariance and variance; population moments give the same beta. # apaBeta.Semi.Mpos(PortfolioReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/apabeta.semi.mpos/ ## Result Returns the Mpos semi-betas, i.e. the betas calculated from observations where portfolio returns are negative and benchmark returns are positive (mixed-sign, positive benchmark). ## Syntax *PortfolioReturns*: r x c matrix of portfolios returns, each column containing a portfolio. All portfolios are assumed to have the same benchmark. *BenchmarkReturns*: r x 1 vector of benchmark returns ## Remarks Built from sample (n − 1) semi-covariance and variance; population moments give the same beta. # apaBeta.Semi.Neg(PortfolioReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/apabeta.semi.neg/ ## Result Returns the negative semi-betas, i.e. the betas calculated from observations where portfolio and benchmark returns are both negative. ## Syntax *PortfolioReturns*: r x c matrix of portfolios returns, each column containing a portfolio. All portfolios are assumed to have the same benchmark. *BenchmarkReturns*: r x 1 vector of benchmark returns ## Remarks Built from sample (n − 1) semi-covariance and variance; population moments give the same beta. # apaBeta.Semi.NonConcordant(PortfolioReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/apabeta.semi.nonconcordant/ ## Result Returns the non-concordant semi-betas, i.e. the betas calculated from observations where portfolio and benchmark returns have opposite signs. ## Syntax *PortfolioReturns*: r x c matrix of portfolios returns, each column containing a portfolio. All portfolios are assumed to have the same benchmark. *BenchmarkReturns*: r x 1 vector of benchmark returns ## Remarks Built from sample (n − 1) semi-covariance and variance; population moments give the same beta. # apaBeta.Semi.Pos(PortfolioReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/apabeta.semi.pos/ ## Result Returns the positive semi-betas, i.e. the betas calculated from observations where portfolio and benchmark returns are both positive. ## Syntax *PortfolioReturns*: r x c matrix of portfolios returns, each column containing a portfolio. All portfolios are assumed to have the same benchmark. *BenchmarkReturns*: r x 1 vector of benchmark returns ## Remarks Built from sample (n − 1) semi-covariance and variance; population moments give the same beta. # apaBiasRatio(TimeSeries, nStDevs) URL: https://www.andreassteiner.net/help/apabiasratio/ ## Result Calculates the bias ratio, a fraud indicator, i.e. the number of returns between 0 and +nStDevs standard deviations divided by 1 plus the number of returns between -nStDevs and 0. ## Syntax *TimeSeries*: r x 1 vector of returns *nStDevs*: number of standard deviations defining the return interval ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image13.svg) ## Remarks The threshold uses the sample standard deviation (denominator n − 1). # apaBiNormalOutliers(XY, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apabinormaloutliers/ ## Result Identifies bivariate outliers outside the confidence ellipse of a bivariate normal distribution. Returns a matrix consisting of bivariate outliers, univariate outliers and the confidence region. ## Syntax *XY*: r x 2 data matrix, each column containing a variable *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks Uses population covariances and volatilities (denominator n). # apaBlackLitterman.ImpliedConfidence(RiskAversion, Weights, Covariances, ViewExposures, ViewPayoffs, Tau) URL: https://www.andreassteiner.net/help/apablacklitterman.impliedconfidence/ ## Result Returns the implied confidence in the views, given the views and an allocation. ## Syntax *RiskAversion*: risk aversion coefficient *Weights*: 1 x n vector of constituent weights *Covariances*: n x n covariance matrix *ViewExposures*: k x n matrix of view exposures, each row containing a view *ViewPayoffs*: k x 1 vector of view payoffs (expected returns of the views) *Tau*: optional; scalar tau, the uncertainty of the prior returns. Default value: 0.025. ## Algorithm > ![Formula](https://www.andreassteiner.net/help/assets/eq/image14.svg) > > w_(posterior) and w_(posterior,100%) are implied weights calculated from the posterior returns and posterior returns with 100% confidence, respectively. ## Remarks - The parameters τ and Ω are constants, respectively calculated from the inputs - The basis for our implementation of the Black-Litterman model is “A Step-by-Step Guide to the Black-Litterman Model” by Thomas M. Idzorek. See this article for conceptual issues and notation. # apaBlackLitterman.ImpliedWeights(RiskAversion, Returns, Covariances) URL: https://www.andreassteiner.net/help/apablacklitterman.impliedweights/ ## Result Returns the implied asset weights (given expected returns) from an unrestricted mean-variance optimization problem, i.e. (RiskAversion \* Covariances)^-1 \* Returns. ## Syntax *RiskAversion*: risk aversion coefficient *Returns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image15.svg) ## Remarks - The basis for our implementation of the Black-Litterman model is “A Step-by-Step Guide to the Black-Litterman Model” by Thomas M. Idzorek. See this article for conceptual issues and notation. # apaBlackLitterman.ImpliedReturns(RiskAversion, Weights, Covariances) URL: https://www.andreassteiner.net/help/apablacklitterman.impliedreturns/ ## Result Returns the implied equilibrium returns from an unrestricted mean-variance optimization problem, i.e. RiskAversion \* Covariances \* Weights. ## Syntax *RiskAversion*: risk aversion coefficient *Weights*: 1 x n vector of constituent weights of the mean-variance efficient benchmark portfolio (market portfolio) *Covariances*: n x n covariance matrix ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image16.svg) ## Remarks - The basis for our implementation of the Black-Litterman model is “A Step-by-Step Guide to the Black-Litterman Model” by Thomas M. Idzorek. See this article for conceptual issues and notation. # apaBlackLitterman.PosteriorReturns.Tau.FullConf(PriorReturns, Covariances, ViewExposures, ViewPayoffs, Tau) URL: https://www.andreassteiner.net/help/apablacklitterman.posteriorreturns.tau.fullconf/ ## Result Returns the vector of Black-Litterman posterior returns for a given tau, assuming 100% confidence in all views. ## Syntax *PriorReturns*: 1 x n vector of prior (e.g. implied equilibrium) returns (Π) *Covariances*: n x n covariance matrix (Σ) *ViewExposures*: k x n matrix of view exposures, each row containing a view (P) *ViewPayoffs*: k x 1 vector of view payoffs, i.e. the expected returns of the views (Q) *Tau*: optional; scalar tau, the uncertainty of the prior returns (default value 0.025) ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image17.svg) ## Remarks - The parameters τ and Ω are constants, respectively calculated from the inputs - The basis for our implementation of the Black-Litterman model is “A Step-by-Step Guide to the Black-Litterman Model” by Thomas M. Idzorek. See this article for conceptual issues and notation. # apaBlackLitterman.PosteriorReturns.Tau(PriorReturns, Covariances, ViewExposures, ViewPayoffs, Tau) URL: https://www.andreassteiner.net/help/apablacklitterman.posteriorreturns.tau/ ## Result Returns the vector of Black-Litterman posterior returns for a given tau (Idzorek, 2005). ## Syntax *PriorReturns*: 1 x n vector of prior (e.g. implied equilibrium) returns (Π) *Covariances*: n x n covariance matrix (Σ) *ViewExposures*: k x n matrix of view exposures, each row containing a view (P) *ViewPayoffs*: k x 1 vector of view payoffs, i.e. the expected returns of the views (Q) *Tau*: optional; scalar tau, the uncertainty of the prior returns (default value 0.025) ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image17.svg) ## Remarks - The parameters τ and Ω are constants, respectively calculated from the inputs - The basis for our implementation of the Black-Litterman model is “A Step-by-Step Guide to the Black-Litterman Model” by Thomas M. Idzorek. See this article for conceptual issues and notation. # apaBlackLitterman.PosteriorReturns.Confidence(PriorReturns, Covariances, RiskAversion, ViewExposures, ViewPayoffs, ViewConfidenceLevels) URL: https://www.andreassteiner.net/help/apablacklitterman.posteriorreturns.confidence/ ## Result Returns the vector of Black-Litterman posterior returns with user-specified confidence levels for each view. ## Syntax *PriorReturns*: 1 x n vector of prior (e.g. implied equilibrium) returns (Π) *Covariances*: n x n covariance matrix (Σ) *RiskAversion*: risk aversion coefficient *ViewExposures*: k x n matrix of view exposures, each row containing a view (P) *ViewPayoffs*: k x 1 vector of view payoffs, i.e. the expected returns of the views (Q) *ViewConfidenceLevels*: k x 1 vector of view confidence levels between 0 and 1 (i.e. 0-100%) ## Remarks - The basis for our implementation is “Black-Litterman Model with Explicit View Confidence” by Tamas Blummer. See this article for formulas and interpretations. # apaBlundellWardFilter(Returns) URL: https://www.andreassteiner.net/help/apablundellwardfilter/ ## Result Removes first-order autocorrelation (unsmoothing) by applying the Blundell/Ward filter. ## Syntax *Returns*: r x 1 vector of returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image18.svg) with ρ(1) being the first-order autocorrelation coefficient of the smoothed return time series. ## Remarks The AR(1) coefficient is a ratio of sample covariance to sample variance (denominator n − 1); population moments give the same coefficient. # apaBonds.Simulate.Factors(nScenarios, HorizonYears, FactorVols, FactorCorrels, StressProbability, StressVolMultiplier, StressMeanShifts, StressFactorCorrels, nIssuers, IssuerVol, Seed) URL: https://www.andreassteiner.net/help/apabonds.simulate.factors/ ## Result Simulates scenarios of the common risk factors that drive bond total returns over a horizon: a parallel change of interest rates, a change of the slope of the yield curve, a market-wide change of credit spreads, a stress regime flag and, optionally, one spread shock per issuer. The result is a nScenarios x (4 + nIssuers) matrix. Its columns are, in this order: level change L, slope change K, market spread change M, stress flag F (1 = stress scenario, 0 = normal scenario) and the issuer spread shocks u(1) to u(nIssuers). The factor scenarios are the input of apaBonds.TotalReturns.FromFactors, which turns them into bond total returns; apaBonds.Simulate.TotalReturns does both steps in one call. The function is non-volatile: with the same inputs and seed it always returns the same scenarios. ## Syntax *nScenarios*: number of scenarios (rows of the result) *HorizonYears*: horizon in years, e.g. 1/12 for monthly returns; all volatilities are scaled by the square root of HorizonYears *FactorVols*: 3 annualized volatilities in decimals (0.01 = 100 basis points) of the level, slope and market spread factor, as a row or column *FactorCorrels*: optional 3 x 3 correlation matrix of level, slope and market spread changes in normal scenarios; default: identity matrix (uncorrelated factors) *StressProbability*: optional probability in \[0, 1\] that a scenario is a stress scenario; default: 0 (no stress regime) *StressVolMultiplier*: optional factor by which all factor and issuer volatilities are multiplied in stress scenarios; default: 1 *StressMeanShifts*: optional 3 mean shifts of level, slope and market spread in stress scenarios, as decimal changes over the horizon (not annualized, not scaled), e.g. -0.0015, 0.0005, 0.0015; default: 0, 0, 0 *StressFactorCorrels*: optional 3 x 3 correlation matrix of the three factors in stress scenarios; default: FactorCorrels *nIssuers*: optional number of issuer spread shock columns appended to the result; must be at least the number of distinct issuers used in apaBonds.TotalReturns.FromFactors; default: 0 (no issuer shocks) *IssuerVol*: optional annualized volatility in decimals of the issuer spread shocks; default: 0 *Seed*: optional integer seed of the random number generator; default: 1 ## Algorithm The function simulates a small factor model of the yield curve and of credit spreads. The idea is that the returns of a bond portfolio over a short horizon are driven by a few common movements: rates go up or down for all maturities (level), long rates move differently from short rates (slope), and credit spreads widen or tighten for all issuers together (market spread). On top of these come issuer-specific spread movements. The function only simulates these factors; apaBonds.TotalReturns.FromFactors then translates them into the returns of each individual bond via its duration, convexity and credit sensitivity. Scenarios are independent and equally likely. For each scenario s, the function first decides whether the scenario is a stress scenario. With U(s) a uniform random number in (0, 1) and p the StressProbability: ``` math F_{s} = \left\{ \begin{matrix} 1 & \text{if}\quad U_{s} < p \\ 0 & \text{otherwise} \end{matrix} \right.\ ``` Then three independent standard normal numbers ε(s) are drawn and correlated with the lower Cholesky factor Λ of the correlation matrix of the regime, i.e. FactorCorrels in normal scenarios and StressFactorCorrels in stress scenarios: ``` math z_{s} = \Lambda_{F_{s}}\,\varepsilon_{s},\quad\quad\Lambda_{F_{s}}\Lambda_{F_{s}}^{\top} = {Corr}_{F_{s}},\quad\quad\varepsilon_{s} \sim N(0,I_{3}) ``` The three common factors X = (L, K, M) are the correlated normals scaled to the horizon, multiplied by m (the StressVolMultiplier) in stress scenarios and shifted by the stress mean shifts δ in stress scenarios: ``` math X_{s,j} = \sigma_{j}\sqrt{h}\mspace{6mu} m^{F_{s}}\, z_{s,j} + F_{s}\,\delta_{j},\quad\quad j \in \{ L,K,M\} ``` With σ(j) the annualized FactorVols, h the HorizonYears and δ(j) the StressMeanShifts. The issuer spread shocks are independent normals with the issuer volatility σ(I), also scaled up by m in stress: ``` math u_{s,k} = \sigma_{I}\sqrt{h}\mspace{6mu} m^{F_{s}}\,\eta_{s,k},\quad\quad\eta_{s,k} \sim N(0,1),\quad\quad k = 1,\ldots,n_{Issuers} ``` Interpretation of the factors (all values are decimal yield changes over the horizon, e.g. 0.001 = +10 basis points): Level L: parallel shift of the risk-free yield curve. A positive L means higher rates and therefore losses on all bonds, proportional to their duration. Slope K: change of the steepness of the curve. In apaBonds.TotalReturns.FromFactors a bond with duration D experiences the rate change L + K x (D - D0) / D0, where D0 is the pivot duration. A positive K steepens the curve: bonds longer than the pivot see rates rise by more than L, shorter bonds by less. Bonds at the pivot are not affected by K. Market spread M: common change of credit spreads. Each bond responds with the beta of its credit bucket (e.g. 0.3 for AAA, 1 for A, 3 for BB), so a market spread widening of 10 basis points widens BB spreads by 30 basis points in that example. This captures the empirical fact that spreads of lower-rated bonds move by a multiple of those of high-grade bonds. Stress flag F: identifies the regime of the scenario. It is returned so that results can be analyzed by regime (e.g. average returns in stress scenarios) It is not used by apaBonds.TotalReturns.FromFactors, because the stress effects are already contained in L, K, M and u. Issuer shocks u: spread movements specific to one issuer, shared by all bonds of that issuer. They generate concentration risk, which is why issuer limits matter in the optimization. Why a stress regime: with StressProbability = 0 all factors are jointly normal, and portfolio returns are close to normal. Real bond returns have fat tails and a negative skew, driven by episodes in which volatility jumps, spreads widen sharply and correlations change. The stress regime makes the scenario distribution a mixture of two normal distributions: most scenarios come from the calm regime, a fraction p from a regime with higher volatility (StressVolMultiplier), a shifted mean (StressMeanShifts) and different correlations (StressFactorCorrels). A typical "flight to quality" stress has a negative level shift (government yields fall), a positive spread shift (credit spreads widen) and a more negative correlation between level and spread. As a result, high-grade, long-duration bonds can gain in stress while lower-rated bonds lose, which is exactly the diversification effect that a tail risk measure such as CVaR rewards. Calibration: the volatilities are annualized and scaled by the square root of the horizon. An annualized level volatility of 0.015 (150 basis points) corresponds to a monthly standard deviation of 0.015 x √(1/12) ≈ 0.0043 (43 basis points). The stress mean shifts, by contrast, are changes over the horizon and are not scaled. Note that the stress mean shifts also shift the unconditional mean of the factors: with p = 10% and a spread shift of 0.0015 per month, the average spread change is 0.1 x 0.0015 = 0.00015 per month, which reduces the average return of a bond with spread duration 6 by about 0.1% per month. Keep the shifts moderate or compensate the carry accordingly if average returns should stay close to the yields. Random numbers: the function uses its own random number generator (xoshiro256\*\* seeded via SplitMix64 from Seed, normal numbers via Box-Muller), so results are reproducible, independent of other calculations and thread-safe. For every scenario the random numbers are drawn in a fixed order: one uniform number, three normal numbers for the factors and nIssuers normal numbers for the issuers. The draws therefore do not depend on the parameter values: if you change e.g. StressVolMultiplier, the same random numbers are used and only the effect of the parameter change is visible (common random numbers). Changing nScenarios keeps the first scenarios unchanged; changing nIssuers changes the sequence and therefore all scenarios. ## Remarks Example: =apaBonds.Simulate.Factors(600, 1/12, {0.015, 0.008, 0.006}, CorrNormal, 0.1, 2, {-0.0015, 0.0005, 0.0015}, CorrStress, 15, 0.004, 145) returns 600 monthly scenarios in a 600 x 19 range: level, slope, spread, stress flag and 15 issuer shocks. The example workbook ApaLibExample_BondTotalReturnSimulation.xlsx shows the complete process from factors to the mean-CVaR efficient frontier. Correlation matrices must be symmetric, have ones on the diagonal and be positive definite. The output is a fixed-size array: enter the formula as an array formula over nScenarios rows and 4 + nIssuers columns. Check of a simulation: in the normal scenarios (F = 0) the standard deviation of L divided by √h should be close to the level volatility, and the share of scenarios with F = 1 close to StressProbability; the deviations shrink with the number of scenarios. # apaBonds.TotalReturns.FromFactors(Factors, HorizonYears, Yields, Durations, Convexities, CreditBuckets, BucketBetas, Issuers, SpreadDurations, IdioVols, PDs, LGDs, SlopePivotDuration, Seed) URL: https://www.andreassteiner.net/help/apabonds.totalreturns.fromfactors/ ## Result Calculates the total returns of a set of bonds over the horizon for each factor scenario produced by apaBonds.Simulate.Factors. The result is a nScenarios x nBonds matrix of simple total returns in decimals (0.01 = +1%), one row per scenario and one column per bond, which can be used directly as scenario input of the mean-CVaR, mean-CDaR or other scenario-based optimization functions. Each return is the sum of carry, the price effect of the rate change, the price effect of the spread change and a convexity adjustment; optionally, idiosyncratic spread noise and issuer defaults are added. ## Syntax *Factors*: nScenarios x (4 + nIssuers) output of apaBonds.Simulate.Factors (level, slope, market spread, stress flag, issuer shocks); a matrix with only 4 columns means no issuer shocks *HorizonYears*: horizon in years; must be the horizon used to simulate the factors *Yields*: nBonds annual yields to maturity in decimals, as a row or column *Durations*: nBonds modified durations, as a row or column *Convexities*: nBonds convexities (as used in ΔP/P ≈ -D Δy + ½ C Δy²), or one value for all bonds *CreditBuckets*: nBonds credit bucket labels (e.g. AAA, A, BB) which are looked up in BucketBetas; alternatively nBonds numeric spread betas if BucketBetas is omitted *BucketBetas*: optional two-column table with the bucket label in the first and the beta to the market spread factor in the second column (a two-row table is accepted as well); labels are compared case-insensitively and without leading or trailing blanks; omit if CreditBuckets contains the betas *Issuers*: optional nBonds issuer labels; bonds with the same label share the issuer spread shock and default together; issuers are numbered in the order of their first appearance, i.e. the first distinct issuer uses the first issuer column of Factors; default: every bond is its own issuer *SpreadDurations*: optional nBonds spread durations, or one value for all bonds; default: Durations *IdioVols*: optional nBonds annualized volatilities in decimals of bond-specific spread noise, or one value for all bonds; default: 0 *PDs*: optional nBonds annual default probabilities in \[0, 1\], or one value for all bonds; default: 0 (no defaults) *LGDs*: optional nBonds losses given default in \[0, 1\], or one value for all bonds; default: 0.6 *SlopePivotDuration*: optional duration D0 at which the slope factor has no effect; default: average of Durations *Seed*: optional integer seed for the idiosyncratic noise and the default draws; default: 2, which together with seed 1 for the factors reproduces apaBonds.Simulate.TotalReturns with its default seed ## Algorithm The function reprices every bond i in every scenario s with a second-order (duration and convexity) approximation of the bond price. Over a short horizon, the total return of a bond consists of the income it earns (carry) and the price change caused by the change of its yield. The yield of a corporate bond is the risk-free rate plus the credit spread, so its yield change is the sum of a rate change Δr and a spread change Δc. Step 1, rate change: the risk-free rate change of bond i is the level change plus the slope change weighted by the distance of the bond duration D(i) from the pivot duration D0: ``` math \Delta r_{s,i} = L_{s} + K_{s}\,\frac{D_{i} - D_{0}}{D_{0}} ``` A bond with duration 2D0 sees the rate change L + K, a bond at the pivot sees L, a bond with a very short duration about L - K. Duration is used as a proxy for the maturity bucket of the bond on the curve. Step 2, spread change: the credit spread change of bond i combines the market spread factor scaled by the beta β of its credit bucket, the shock of its issuer k(i) and bond-specific noise: ``` math \Delta c_{s,i} = \beta_{b(i)}\, M_{s} + u_{s,k(i)} + \sigma_{e,i}\sqrt{h}\mspace{6mu}\xi_{s,i},\quad\quad\xi_{s,i} \sim N(0,1) ``` With β(b(i)) from BucketBetas, u(s, k(i)) from the issuer columns of Factors (0 if Factors has only 4 columns) and σ(e, i) the annualized IdioVols. The market component makes all credit bonds move together, the issuer component makes bonds of the same issuer move together, and the noise term captures everything specific to one bond (liquidity, technicals). Step 3, total return: the return over the horizon is the carry, minus duration times the rate change, minus spread duration times the spread change, plus the convexity adjustment on the total yield change: ``` math R_{s,i} = y_{i}\, h - D_{i}\,\Delta r_{s,i} - {SD}_{i}\,\Delta c_{s,i} + \frac{1}{2}\, C_{i}\left( \Delta r_{s,i} + \Delta c_{s,i} \right)^{2} ``` With y(i) the yield, h the horizon in years, D(i) the duration, SD(i) the spread duration and C(i) the convexity. The carry y x h is the return the bond earns if neither rates nor spreads change; it is the deterministic part of the return and the main source of differences in expected returns between bonds. The duration terms are the first-order price sensitivities: a bond with duration 6 loses about 6% if its yield rises by 1 percentage point. The convexity term is always positive and makes the price-yield relationship curved: large yield moves in either direction are slightly better for the bondholder than the linear approximation suggests, which matters in stress scenarios with large moves. Step 4, defaults (only if PDs are not 0): each issuer k defaults in a scenario if a uniform random number V(s, k) drawn for that issuer falls below the default probability over the horizon, which is derived from the annual probability PD(i): ``` math q_{i} = 1 - (1 - {PD}_{i})^{h},\quad\quad R_{s,i} = - {LGD}_{i}\quad\quad\text{if}\quad V_{s,k(i)} < q_{i} ``` Because the uniform number belongs to the issuer, all bonds of an issuer default in the same scenario (with different PDs per bond, a bond with a higher PD defaults whenever a bond of the same issuer with a lower PD defaults). The return of a defaulted bond is -LGD, i.e. the investor recovers 1 - LGD of the bond value and earns no carry. Defaults are independent across issuers; they create rare, large losses and are therefore relevant for CVaR, but they require many scenarios to be represented reliably: with an annual PD of 1% and monthly scenarios, a single issuer defaults in only about one of 1200 scenarios. Putting it together, the variance of a bond return in normal scenarios is driven by its exposures to the common factors. Ignoring convexity, for a bond at the pivot duration (D = D0, so the slope factor drops out) with correlation ρ between level and market spread: ``` math Var(R_{i}) \approx h\left( D_{i}^{2}\sigma_{L}^{2} + {SD}_{i}^{2}\beta_{i}^{2}\sigma_{M}^{2} + 2\, D_{i}\,{SD}_{i}\,\beta_{i}\,\rho_{LM}\,\sigma_{L}\sigma_{M} + {SD}_{i}^{2}\left( \sigma_{I}^{2} + \sigma_{e,i}^{2} \right) \right) ``` This formula helps to calibrate the volatilities to observed return volatilities of bond indices by duration and rating, and it shows the main diversification lever: with a negative correlation between rates and spreads (spreads widen when rates fall), rate and spread risk partially offset each other, the more so the higher the spread beta of the bond. Random numbers: the noise and default draws use a generator seeded with Seed (see apaBonds.Simulate.Factors). For each scenario, the function first draws one uniform number per issuer and then one normal number per bond, regardless of whether PDs and IdioVols are 0, so changing these parameters does not change the other random numbers. ## Remarks Example: with factors in Factors!B2:T601 and the bond data in columns of sheet Bonds, =apaBonds.TotalReturns.FromFactors(Factors!B2:T601, 1/12, Bonds!G2:G31, Bonds!E2:E31, Bonds!F2:F31, Bonds!C2:C31, Parameters!A22:B24, Bonds!B2:B31, Bonds!H2:H31, Bonds!I2:I31, Bonds!K2:K31, Bonds!L2:L31, , 146) returns 600 x 30 monthly total return scenarios (see ApaLibExample_BondTotalReturnSimulation.xlsx). Separating factor simulation and repricing has three advantages: the factor scenarios can be inspected and analyzed (e.g. returns by regime via the stress flag), the same factors can be applied to different bond universes so that their scenarios are consistent, and factor scenarios from other sources (historical factor changes, hand-made stress scenarios, other simulation models) can be used. Any matrix with the same column layout is accepted, for example historical monthly changes of a government yield, a curve slope and a credit spread index, with the stress flag column set to 0. Check: with all factors equal to 0 and no noise or defaults, every bond return equals its carry y x h. Limitations: the duration-convexity approximation is accurate for short horizons and moderate yield changes. The model ignores roll-down along the curve, changes of duration over the horizon, embedded options (callable bonds), currency effects and the term structure of spreads. Defaulted bonds return -LGD without carry. Scenarios are equally likely. # apaBonds.Simulate.TotalReturns(nScenarios, HorizonYears, Yields, Durations, Convexities, CreditBuckets, BucketBetas, FactorVols, FactorCorrels, Issuers, StressProbability, StressVolMultiplier, StressMeanShifts, StressFactorCorrels, IssuerVol, SpreadDurations, IdioVols, PDs, LGDs, SlopePivotDuration, Seed) URL: https://www.andreassteiner.net/help/apabonds.simulate.totalreturns/ ## Result Simulates bond total return scenarios over a horizon in one step: it simulates the common factors as apaBonds.Simulate.Factors and reprices the bonds on them as apaBonds.TotalReturns.FromFactors. The result is a nScenarios x nBonds matrix of simple total returns in decimals, one row per equally likely scenario and one column per bond, typically used as input of the mean-CVaR optimization (e.g. apaMeanCVaR.Restricted.Bounded.Axb.Frontier). ## Syntax *nScenarios*: number of scenarios *HorizonYears*: horizon in years, e.g. 1/12 for monthly returns *Yields*: nBonds annual yields in decimals, as a row or column *Durations*: nBonds modified durations, as a row or column *Convexities*: nBonds convexities, or one value for all bonds *CreditBuckets*: nBonds credit bucket labels looked up in BucketBetas, or nBonds numeric spread betas if BucketBetas is empty *BucketBetas*: two-column table with bucket label and beta to the market spread factor; leave the argument empty if CreditBuckets contains the betas *FactorVols*: 3 annualized volatilities in decimals of the level, slope and market spread factor *FactorCorrels*: optional 3 x 3 factor correlation matrix in normal scenarios; default: identity matrix *Issuers*: optional nBonds issuer labels; bonds of the same issuer share issuer shocks and defaults; default: every bond is its own issuer *StressProbability*: optional probability of a stress scenario; default: 0 *StressVolMultiplier*: optional volatility multiplier in stress scenarios; default: 1 *StressMeanShifts*: optional 3 mean shifts of level, slope and market spread in stress scenarios (changes over the horizon); default: 0, 0, 0 *StressFactorCorrels*: optional 3 x 3 factor correlation matrix in stress scenarios; default: FactorCorrels *IssuerVol*: optional annualized volatility of the issuer spread shocks; default: 0 *SpreadDurations*: optional nBonds spread durations, or one value; default: Durations *IdioVols*: optional nBonds annualized idiosyncratic spread volatilities, or one value; default: 0 *PDs*: optional nBonds annual default probabilities, or one value; default: 0 *LGDs*: optional nBonds losses given default, or one value; default: 0.6 *SlopePivotDuration*: optional duration at which the slope factor has no effect; default: average of Durations *Seed*: optional integer seed; default: 1 ## Algorithm The function runs the complete scenario generation process: 1\. Factor scenarios: for each scenario, draw the regime (stress with probability StressProbability), draw the correlated level, slope and market spread changes with the volatilities, correlations and mean shifts of that regime, and draw one spread shock per distinct issuer. The number of issuer shocks equals the number of distinct labels in Issuers (or the number of bonds if Issuers is omitted). The factor random numbers use Seed. See apaBonds.Simulate.Factors for the formulas. 2\. Bond repricing: for each scenario and bond, compute the rate change from level and slope, the spread change from the market spread (times the bucket beta), the issuer shock and the bond noise, and the total return from carry, duration, spread duration and convexity; apply defaults if PDs are given. The noise and default random numbers use Seed + 1. See apaBonds.TotalReturns.FromFactors for the formulas. ``` math R_{s,i} = y_{i}\, h - D_{i}\,\Delta r_{s,i} - {SD}_{i}\,\Delta c_{s,i} + \frac{1}{2}\, C_{i}\left( \Delta r_{s,i} + \Delta c_{s,i} \right)^{2} ``` 3\. Output: the nScenarios x nBonds matrix of total returns. The factor scenarios themselves are not returned; use the two-step route if you want to analyze them. The result is identical to apaBonds.Simulate.Factors with Seed and nIssuers = number of distinct issuers, followed by apaBonds.TotalReturns.FromFactors with Seed + 1, so the one-step and two-step routes can be used interchangeably. ## Remarks Example: =apaBonds.Simulate.TotalReturns(600, 1/12, Yields, Durations, Convexities, Ratings, BucketBetas, {0.015, 0.008, 0.006}, CorrNormal, Issuers, 0.1, 2, {-0.0015, 0.0005, 0.0015}, CorrStress, 0.004, , 0.002, , , , 145) returns 600 monthly scenarios for all bonds, with a stress regime in 10% of the scenarios, issuer shocks, bond-specific noise and no defaults. The workbook ApaLibExample_BondTotalReturnSimulation.xlsx contains this setup, the two-step route, summary statistics by bond and regime, checks, and the mean-CVaR efficient frontier on the simulated scenarios with duration, issuer and high-yield constraints. Practical guidance: use enough scenarios for the tail measure you optimize; with 600 scenarios and a 95% confidence level, CVaR is the average of the 30 worst scenarios. Keep the seed fixed while comparing portfolios or constraints, so that differences are not caused by different random numbers, and vary the seed to assess the sampling uncertainty of the results. # apaBurkeRatio(PortfolioReturns, RiskfreeReturns, nDrawdowns) URL: https://www.andreassteiner.net/help/apaburkeratio/ ## Result Calculates the Burke ratio, a risk-adjusted performance measure, i.e. the average excess return divided by the square root of the sum of the squared depths of the *nDrawdowns* largest drawdown episodes. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *RiskfreeReturns*: r x 1 vector of riskfree returns (i.e. a time series) or a single riskfree rate *nDrawdowns*: number of largest drawdown episodes to use (at least 1) ## Algorithm BR = (r̄P − r̄f) / √(D1² + … + DK²) where D1, …, DK are the depths of the K deepest drawdown episodes, K = min(*nDrawdowns*, number of episodes). ## Remarks A drawdown episode is a run of observations below the running high-water mark of the cumulative return; its depth is the lowest value of the underwater curve within the run. If fewer than *nDrawdowns* episodes exist, all episodes are used. \#N/A is returned if the series has no drawdown. # apaCalmarRatio(PortfolioReturns, RiskfreeReturns) URL: https://www.andreassteiner.net/help/apacalmarratio/ ## Result Calculates the Calmar ratio, a risk-adjusted performance measure, i.e. the average excess return divided by the maximum drawdown. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *RiskfreeReturns*: r x 1 vector of riskfree returns (i.e. a time series) or a single riskfree rate ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image20.svg) # apaCaptureRatio.Downside.Continuous(PortfolioReturns, BenchmarkReturns, Threshold) URL: https://www.andreassteiner.net/help/apacaptureratio.downside.continuous/ ## Result Calculates the downside capture ratio from continuous mean returns, i.e. the mean portfolio return divided by the mean benchmark return in periods where the benchmark return is below the threshold. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *Threshold*: benchmark return threshold defining up and down markets ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image21.svg) # apaCaptureRatio.Downside.Discrete(PortfolioReturns, BenchmarkReturns, Threshold) URL: https://www.andreassteiner.net/help/apacaptureratio.downside.discrete/ ## Result Calculates the downside capture ratio from discrete mean returns, i.e. the mean portfolio return divided by the mean benchmark return in periods where the benchmark return is below the threshold. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *Threshold*: benchmark return threshold defining up and down markets ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image22.svg) # apaCaptureRatio.Upside.Continuous(PortfolioReturns, BenchmarkReturns, Threshold) URL: https://www.andreassteiner.net/help/apacaptureratio.upside.continuous/ ## Result Calculates the upside capture ratio from continuous mean returns, i.e. the mean portfolio return divided by the mean benchmark return in periods where the benchmark return is above the threshold. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *Threshold*: benchmark return threshold defining up and down markets ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image23.svg) # apaCaptureRatio.Upside.Discrete(PortfolioReturns, BenchmarkReturns, Threshold) URL: https://www.andreassteiner.net/help/apacaptureratio.upside.discrete/ ## Result Calculates the upside capture ratio from discrete mean returns, i.e. the mean portfolio return divided by the mean benchmark return in periods where the benchmark return is above the threshold. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *Threshold*: benchmark return threshold defining up and down markets ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image24.svg) # apaCategories.FromIndices(Indices) URL: https://www.andreassteiner.net/help/apacategories.fromindices/ ## Result Returns the category indices and the constituent indices, sorted by category. ## Syntax *Indices*: 1 x nCols vector with category indices # apaCategories.FromIndices.Categories(Indices) URL: https://www.andreassteiner.net/help/apacategories.fromindices.categories/ ## Result Returns the category indices of the constituents, sorted by category. ## Syntax *Indices*: 1 x nCols vector with category indices # apaCategories.FromIndices.Constituents(Indices) URL: https://www.andreassteiner.net/help/apacategories.fromindices.constituents/ ## Result Returns the constituent indices, sorted by category. ## Syntax *Indices*: 1 x nCols vector with category indices # apaCategories.Constituents.ReverseOrder(Order) URL: https://www.andreassteiner.net/help/apacategories.constituents.reverseorder/ ## Result Reverses an order of constituent indices. ## Syntax *Order*: 1 x nCols vector with constituent indices defining an order # apaCategories.FromLabels(Labels) URL: https://www.andreassteiner.net/help/apacategories.fromlabels/ ## Result Returns the category indices and the constituent indices, sorted by category. ## Syntax *Labels*: 1 x nCols vector with category labels (can be string or numerical) # apaCategories.FromLabels.Categories(Labels) URL: https://www.andreassteiner.net/help/apacategories.fromlabels.categories/ ## Result Returns the category indices of the constituents, sorted by category. ## Syntax *Labels*: 1 x nCols vector with category labels (can be string or numerical) # apaCategories.FromLabels.Constituents(Labels) URL: https://www.andreassteiner.net/help/apacategories.fromlabels.constituents/ ## Result Returns the constituent indices, sorted by category. ## Syntax *Labels*: 1 x nCols vector with category labels (can be string or numerical) # apaCategories.FromRegimes.Mean(ConditioningVariables) URL: https://www.andreassteiner.net/help/apacategories.fromregimes.mean/ ## Result Derives categories (regimes) from conditioning variables, depending on whether an observation is above or below the arithmetic mean. ## Syntax *ConditioningVariables*: nObs x nSeries matrix of data, each column containing a conditioning variable # apaCategories.FromRegimes.Quantiles(ConditioningVariables, Quantiles) URL: https://www.andreassteiner.net/help/apacategories.fromregimes.quantiles/ ## Result Derives categories (regimes) from conditioning variables, each regime being a quantile. Quantiles are stated in ascending order. ## Syntax *ConditioningVariables*: nObs x nSeries matrix of data, each column containing a conditioning variable *Quantiles*: number of quantiles # apaCategories.FromRegimes.Threshold(ConditioningVariables, Threshold) URL: https://www.andreassteiner.net/help/apacategories.fromregimes.threshold/ ## Result Derives categories (regimes) from conditioning variables, depending on whether an observation is below or above a threshold value. Observations equal to the threshold are considered above. ## Syntax *ConditioningVariables*: nObs x nSeries matrix of data, each column containing a conditioning variable *Threshold*: threshold value # apaCategories.FromRegimes.Sigmas(ConditioningVariables, IsSigned) URL: https://www.andreassteiner.net/help/apacategories.fromregimes.sigmas/ ## Result Derives categories (regimes) from conditioning variables, each regime being defined by the number of standard deviations (sigmas) away from the arithmetic mean of each series. ## Syntax *ConditioningVariables*: nObs x nSeries matrix of data, each column containing a conditioning variable *IsSigned*: TRUE to retain the sign of the sigmas, i.e. observations below the mean get negative signs ## Remarks Standardizes with the population volatility (denominator n). # apaCategories.GroupMembership.FromIndices(Indices) URL: https://www.andreassteiner.net/help/apacategories.groupmembership.fromindices/ ## Result Returns the group membership matrix from category indices. ## Syntax *Indices*: 1 x nCols vector with category indices # apaCategories.GroupMembership.FromLabels(Labels) URL: https://www.andreassteiner.net/help/apacategories.groupmembership.fromlabels/ ## Result Returns the group membership matrix from category labels. ## Syntax *Labels*: 1 x nCols vector with category labels (can be string or numerical) # apaCategories.GroupMembershipToIndices(GroupMembership) URL: https://www.andreassteiner.net/help/apacategories.groupmembershiptoindices/ ## Result Converts a group membership matrix into a category index vector. ## Syntax *GroupMembership*: nGroups x nConstituents matrix with group membership indicators # apaCategories.LabelsToIndices(Labels) URL: https://www.andreassteiner.net/help/apacategories.labelstoindices/ ## Result Turns category labels into category indices. ## Syntax *Labels*: 1 x nCols vector with category labels (can be string or numerical) # apaCategories.Structure.FromIndices(Indices) URL: https://www.andreassteiner.net/help/apacategories.structure.fromindices/ ## Result Returns the category structure, i.e. the number of constituents in each category and the sorted constituents. ## Syntax *Indices*: 1 x nCols vector with category indices # apaCategories.Structure.FromLabels(Labels) URL: https://www.andreassteiner.net/help/apacategories.structure.fromlabels/ ## Result Returns the category structure, i.e. the number of constituents in each category and the sorted constituents. ## Syntax *Labels*: 1 x nCols vector with category labels (can be string or numerical) # apaCauchyCdf(x, location, scale) URL: https://www.andreassteiner.net/help/apacauchycdf/ ## Result Cumulative distribution function of the Cauchy distribution. ## Syntax *x*: value at which to evaluate the function *location*: location parameter *scale*: scale parameter ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image25.svg) # apaCauchyInv(p, location, scale) URL: https://www.andreassteiner.net/help/apacauchyinv/ ## Result Inverse of the cumulative distribution function of the Cauchy distribution, i.e. the quantile for a given probability. ## Syntax *p*: probability *location*: location parameter *scale*: scale parameter ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image26.svg) # apaCauchyPdf(x, location, scale) URL: https://www.andreassteiner.net/help/apacauchypdf/ ## Result Probability density function of the Cauchy distribution. ## Syntax *x*: value at which to evaluate the function *location*: location parameter *scale*: scale parameter ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image27.svg) # apaCauchySim(nSims, location, scale) URL: https://www.andreassteiner.net/help/apacauchysim/ ## Result Simulates several random drawings from a Cauchy distribution. ## Syntax *nSims*: number of observations to simulate *location*: location parameter *scale*: scale parameter # apaCDaR.Empirical(Returns, ConfidenceLevel, IsSmooth) URL: https://www.andreassteiner.net/help/apacdar.empirical/ ## Result Calculates empirical conditional drawdown at risk (CDaR) figures from a time series matrix of returns. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *ConfidenceLevel*: confidence level, e.g. 95%. *IsSmooth*: TRUE for the smoothed estimate (see apaCVaR.Empirical, applied to the drawdowns), FALSE for the average of the drawdowns below the DaR ## Algorithm Same calculations as the empirical CVaR, except that the input data are not the returns, but the drawdowns of the return time series. ## Remarks The result is 0 if the series has no drawdown. \#N/A is returned if *IsSmooth* = FALSE and no drawdown lies below the DaR. # apaCDaRRatio(Returns, ConfidenceLevel, RiskfreeReturns, PeriodsPerYear) URL: https://www.andreassteiner.net/help/apacdarratio/ ## Result Returns the conditional drawdown at risk ratio, the mean excess return divided by the absolute empirical CDaR. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *ConfidenceLevel*: confidence level of the CDaR, e.g. 95% *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 *PeriodsPerYear*: optional; number of return periods per year used to annualize the mean excess return, e.g. 12 for monthly data; default: 1 (per-period result) ## Algorithm CDaR ratio = PeriodsPerYear · mean(r − rf) / \|CDaR\|, with the CDaR of apaCDaR.Empirical (IsSmooth = FALSE). ## Remarks The result is a 1 x c row vector with one value per column of Returns. \#N/A is returned if the CDaR is 0 or undefined. # apaCertaintyEquivalentReturn(Returns, RiskAversion, RiskfreeReturns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apacertaintyequivalentreturn/ ## Result Returns the mean-variance certainty-equivalent excess return. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *RiskAversion*: risk aversion coefficient λ (at least 0) *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 *IsSampleOtherwisePopulation*: optional; TRUE for sample variance (division by n-1), FALSE for population variance (division by n); default: TRUE ## Algorithm CER = mean(r − rf) − λ/2 · var(r − rf). ## Remarks The result is a 1 x c row vector with one value per column of Returns. The result has the frequency of the input data. # apaCFcal(moments) URL: https://www.andreassteiner.net/help/apacfcal/ ## Result Returns the parameters of the Cornish-Fisher expansion (location, scale, skewness and excess kurtosis parameters) calibrated to target moments. ## Syntax *moments*: 4 x 1 vector of target moments: mean, volatility (not variance), skewness and excess kurtosis ## Algorithm See the remarks below. ## Remarks - Calibrated parameters have the property that sampling from the Cornish-Fisher distribution reproduces the target moments exactly. For more information, see our research note “Fitting Non-Normal Distributions With Calibrated Cornish-Fisher Expansions” available on www.andreassteiner.net/consulting. # apaCFinv(p, mu, sigma, skewness, kurtosis) URL: https://www.andreassteiner.net/help/apacfinv/ ## Result Inverse of the Cornish-Fisher expansion distribution, i.e. the quantile for a given probability. ## Syntax *p*: probability *mu*: location parameter *sigma*: scale parameter *skewness*: skewness parameter *kurtosis*: Excess kurtosis parameter of the Cornish-Fisher expansion (see apaCFmom for the resulting moments) ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image28.svg) μ, σ, S and K are the Cornish-Fisher parameters (location, scale, skewness and excess kurtosis parameters). They are close to, but not equal to, the mean, volatility, skewness and excess kurtosis of the resulting distribution; apaCFcal returns parameters that reproduce given target moments. q_(p) is the quantile of a standard normal distribution at probability p # apaCFmom(mu, sigma, skewness, kurtosis) URL: https://www.andreassteiner.net/help/apacfmom/ ## Result Returns the moments of the Cornish-Fisher expansion from its parameters: mean, volatility, skewness and excess kurtosis. ## Syntax *mu*: location parameter *sigma*: scale parameter *skewness*: skewness parameter *kurtosis*: excess kurtosis parameter ## Remarks - For more information, see our research note “Fitting Non-Normal Distributions With Calibrated Cornish-Fisher Expansions” available on www.andreassteiner.net/consulting. # apaCFrnd(mu, sigma, skewness, kurtosis) URL: https://www.andreassteiner.net/help/apacfrnd/ ## Result Returns a random drawing from a distribution based on the Cornish-Fisher expansion. ## Syntax *mu*: location parameter *sigma*: scale parameter *skewness*: skewness parameter *kurtosis*: Excess kurtosis parameter of the Cornish-Fisher expansion (see apaCFmom for the resulting moments) # apaCFsim(n, mu, sigma, skewness, kurtosis) URL: https://www.andreassteiner.net/help/apacfsim/ ## Result Simulates random drawings from a distribution based on the Cornish-Fisher expansion. ## Syntax *n*: number of observations to simulate *mu*: location parameter *sigma*: scale parameter *skewness*: skewness parameter *kurtosis*: Excess kurtosis parameter of the Cornish-Fisher expansion (see apaCFmom for the resulting moments) # apaCFsim.Correlated(nSims, CFparameters, Correlations) URL: https://www.andreassteiner.net/help/apacfsim.correlated/ ## Result Simulates correlated random drawings from distributions based on the Cornish-Fisher expansion. ## Syntax *nSims*: number of observations to simulate *CFparameters*: 4 x c matrix of Cornish-Fisher parameters (location, scale, skewness and excess kurtosis parameters, e.g. from apaCFcal), each column containing a variable *Correlations*: c x c rank correlation matrix ## Remarks Correlations are measured in unit space, i.e. the resulting drawings are rank correlated in return space. # apaCharts.Boxes(X, Y, DoShowAverages) URL: https://www.andreassteiner.net/help/apacharts.boxes/ ## Result Box representation (minimum/maximum) of bivariate data, as input data for an Excel XY chart. ## Syntax *X*: r x c matrix of X values, each column representing a series *Y*: r x c matrix of Y values, each column representing a series *DoShowAverages*: TRUE for also showing averages as a separate series # apaCharts.Categories(X, Y, CategoryLabels) URL: https://www.andreassteiner.net/help/apacharts.categories/ ## Result Returns a structured table for plotting category data. 1st column: category index, 2nd column: constituent index, 3rd column: x value, 4th and subsequent columns: y values. ## Syntax *X*: 1 x c vector of X values *Y*: 1 x c vector of Y values *CategoryLabels*: 1 x c vector of category labels # apaCharts.ConvexLayers(X, Y) URL: https://www.andreassteiner.net/help/apacharts.convexlayers/ ## Result Creates input data to plot all convex layers (convex polygons) of a dataset in an Excel XY chart. ## Syntax *X*: r x 1 vector of observations in dataset X *Y*: r x 1 vector of observations in dataset Y ## Remarks See [Convex layers - Wikipedia](https://en.wikipedia.org/wiki/Convex_layers) # apaCharts.Dendrogram(ClusteringResult, IsWeighted, nClusters, GroupLabels, ElementLabels, IsRadial) URL: https://www.andreassteiner.net/help/apacharts.dendrogram/ ## Result Creates input data for a dendrogram of hierarchical clustering results, grouped into k groups, to be plotted as an Excel XY chart with straight lines. The first column contains the element labels, the second column the x values, columns 3 to k + 2 the y values of groups 1 to k and, for k \> 1, column k + 3 the y values of the tree above the groups, and the last column the y values of the elements. The first row contains the label Element labels, an empty string, the k group labels, for k \> 1 the label Above group cut, and the label Elements. Below, the output has the same layout as apaCharts.Scatter.XY: one block of rows per series, stacked vertically. These are followed by one row per element, in dendrogram (leaf) order, with the element label in the first column, the x value of its leaf in the second column and 0 in the last column; all other cells contain \#N/A. ## Syntax *ClusteringResult*: result matrix from a hierarchical clustering algorithm *IsWeighted*: TRUE to use the distance information, FALSE to use unit distances *nClusters*: optional; number of groups k, an integer between 1 and the number of elements; default: 1 (the whole tree as one series) *GroupLabels*: optional; row or column vector of k group labels; default: Group 1, Group 2, … *ElementLabels*: optional; row or column vector of n element labels, in the order of the elements (rows of the distance matrix); default: Element 1, Element 2, … *IsRadial*: optional; TRUE for a radial dendrogram, FALSE for a standard dendrogram; default: FALSE ## Remarks Groups 1 to k are numbered from left to right as in apaClustering.Hierarchical.Clusters.k. The series of a group is its subtree, starting at the top merge of the group; series k + 1 is the tree above the groups, including the links down to their top merges. Each series is drawn as one continuous line that retraces its links. A group with a single element has no points of its own: its column contains only \#N/A, and its link is drawn down to the leaf as part of series k + 1, so with k equal to the number of elements, the whole tree is in series k + 1. For k = 1, the whole tree is in series 1 and there is no column for the tree above the groups, so the output has four columns. The last series marks the elements at height 0. Excel charts allow at most 255 series, so k should not exceed 253. Leaves are placed at x = 1, 3, 5, …, each merge between its two children. With IsWeighted TRUE, the height of a merge is its distance; otherwise, the j-th merge is at height j, so the last merge is at height n - 1, where n is the number of elements. With IsRadial TRUE, the dendrogram is drawn in polar coordinates, with the root at the centre and the elements on the unit circle, clockwise from the top. A node at position x and height h, as above, lies at the angle π/2 - 2π(x - 1)/(2n) and the radius 1 - h/H, where H is the height of the last merge. Each link is a radial line from the child to the height of its parent, followed by an arc to the parent, drawn with points at most 2 degrees apart. The second column then contains the x coordinates and the series columns the y coordinates; the element rows contain the coordinates of the elements on the unit circle, with y in the last column. Equal scales on both chart axes keep the circle round. # apaCharts.Draw(Layout, Points, GenerateSingleSeries) URL: https://www.andreassteiner.net/help/apacharts.draw/ ## Result Draws a list of lines defined by two or more points, as input data for an Excel XY chart. By default, each line is a separate series. With GenerateSingleSeries TRUE, all lines form a single series: the first column contains the x values, the second column the y values, and the lines are stacked vertically, separated by one row of \#N/A. ## Syntax *Layout*: r x 2 matrix of X and Y coordinates *Points*: nPoints x nNeighbors matrix of points. A point is represented as an index referring to the rows of the layout matrix *GenerateSingleSeries*: optional; TRUE to return all lines as a single series, FALSE for one series per line; default: FALSE ## Remarks Each row of Points defines one line, from the point in the first column through the points in the following columns, in this order. With GenerateSingleSeries TRUE, empty, non-numeric and unknown indices are skipped, and a row without valid points produces no line; if no row contains a valid point, the result is one row of \#N/A. To draw the lines of a single series separately, make sure that, under Select Data, Hidden and Empty Cells of the chart, empty cells are shown as gaps and Show \#N/A as an empty cell is active. Otherwise, Excel connects the end of each line with the start of the next. # apaCharts.kNearestNeighbor(k, DataMatrix, Xidx, Yidx) URL: https://www.andreassteiner.net/help/apacharts.knearestneighbor/ ## Result Creates input data for a k-nearest-neighbor (kNN) chart: for each data point, its X and Y coordinates followed by those of its k nearest neighbors, with one chart series per data point. Cells without values contain \#N/A. ## Syntax *k*: number of neighbors to consider, between 0 (data points only) and c - 1 *DataMatrix*: r x c matrix *Xidx*: index of the x-dimension to plot *Yidx*: index of the y-dimension to plot ## Remarks Neighbors are ranked by Euclidean distance; ties are broken by the lower column index. A data point is never its own neighbor, even if other data points have the same coordinates. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaCharts.Line.Split(DataVector, SeriesIndices) URL: https://www.andreassteiner.net/help/apacharts.line.split/ ## Result Creates input data for a line chart from a data vector split into several series. Each column of the result contains the data points of one series, all other cells contain \#N/A. ## Syntax *DataVector*: r x 1 data vector *SeriesIndices*: r x 1 vector of 1-based series indices, one per observation ## Algorithm Each observation is assigned to the column given by its series index. ## Remarks The number of columns of the result equals the largest series index. # apaCharts.Scatter.X(DataMatrix, IsNormalizedOtherwiseUnitSpace) URL: https://www.andreassteiner.net/help/apacharts.scatter.x/ ## Result Creates input data for a normalized or unit space scatter plot, each row representing a dataset. ## Syntax *DataMatrix*: r x c matrix of data, each column a different data series *IsNormalizedOtherwiseUnitSpace*: optional; TRUE for normalized data (i.e. values scaled to be within 0 and 1), FALSE for unit space representation; default: TRUE ## Remarks Better suited for larger datasets. # apaCharts.Scatter.X.Expanded(DataMatrix, IsNormalizedOtherwiseUnitSpace) URL: https://www.andreassteiner.net/help/apacharts.scatter.x.expanded/ ## Result Creates input data for a normalized or unit space scatter plot, each series representing a dataset. ## Syntax *DataMatrix*: r x c matrix of data, each column a different data series *IsNormalizedOtherwiseUnitSpace*: optional; TRUE for normalized data (i.e. values scaled to be within 0 and 1), FALSE for unit space representation; default: TRUE ## Remarks The output becomes very large for large datasets. # apaCharts.Scatter.XY(X, Y) URL: https://www.andreassteiner.net/help/apacharts.scatter.xy/ ## Result Creates input data for a scatter plot with several series. ## Syntax *X*: r x c matrix of data for the X dimension: either one column or the same number of columns as in Y *Y*: r x c matrix of data for the Y dimension, each column a different data series ## Remarks If X has one series, this series is used for all columns in Y. Otherwise, X and Y need to have the same number of columns/series. # apaCharts.Scatter.XY.SingleSeries(X, Y) URL: https://www.andreassteiner.net/help/apacharts.scatter.xy.singleseries/ ## Result Creates input data for a scatter plot with several series, collapsed to a single series. ## Syntax *X*: r x c matrix of data for the X dimension: either one column or the same number of columns as in Y *Y*: r x c matrix of data for the Y dimension, each column a different data series ## Remarks If X has one series, this series is used for all columns in Y. Otherwise, X and Y need to have the same number of columns/series. # apaCharts.Step(X, Y, StepPosition) URL: https://www.andreassteiner.net/help/apacharts.step/ ## Result Creates input data for a step chart, to be plotted as an Excel XY chart with straight lines, e.g. for empirical distribution functions, state paths of regime models or rating histories. The output has the same layout as apaCharts.Scatter.XY: one block of rows per series, stacked vertically, with the x values in the first column and the y values of series j in column j + 1; all other cells contain \#N/A. ## Syntax *X*: r x c matrix of x values: either one column, used for all series, or the same number of columns as Y *Y*: r x c matrix of y values, each column a different data series *StepPosition*: optional; position of the steps: 0 = post, y(i) holds from x(i) up to x(i+1); 1 = pre, y(i) holds from x(i-1) up to x(i); 2 = mid, the steps lie halfway between consecutive x values; default: 0 ## Algorithm Each pair of consecutive observations is connected by a horizontal and a vertical line segment. With StepPosition = 0, the line runs from (x(i-1), y(i-1)) horizontally to (x(i), y(i-1)) and then vertically to (x(i), y(i)); with StepPosition = 1, it runs vertically to (x(i-1), y(i)) and then horizontally to (x(i), y(i)); with StepPosition = 2, the vertical segment is placed at the midpoint of x(i-1) and x(i). Each block has 2r - 1 rows for StepPosition 0 and 1, and 2r rows for StepPosition 2. ## Remarks The observations are used in the given order, so x should normally be sorted in ascending order. Points derived from a non-numeric x or y value are returned as \#N/A. # apaClassificationAccuracy URL: https://www.andreassteiner.net/help/apaclassificationaccuracy/ ## Result Returns the overall classification accuracy from observed and predicted class labels. ## Syntax YObserved: $`n \times 1`$vector of observed class labels (1..K). YPredicted: $`n \times 1`$vector of predicted class labels (1..K). ## Algorithm Inputs are validated: non-empty column vectors with the same number of rows. The accuracy is the fraction of rows where the observed and the predicted class labels are identical. The accuracy is returned as a scalar between 0 and 1. # apaClustering.CDC(Features, K, Ratio) URL: https://www.andreassteiner.net/help/apaclustering.cdc/ ## Result Clustering by measuring local direction centrality (CDC), following Peng et al. (2022). Every data point is assigned to a cluster. Returns a 1 x n row of cluster labels numbered from 1. ## Syntax *Features*: m x n data matrix with m features (at least 2) in rows and n data points in columns *K*: number of nearest neighbors used to measure the direction centrality; integer between 2 and the number of distinct data points minus 1; with m \> 2 features at least m + 1. Typical values: 10 to 30 *Ratio*: share of internal points; larger than 0 and at most 1. Typical values: 0.7 to 0.95 ## Remarks The direction centrality metric (DCM) of a data point measures how evenly its K nearest neighbors surround it. With 2 features, it is the variance of the K angles between consecutive neighbor directions, divided by its maximum (K - 1) · 4π² / K². With m \> 2 features, the neighbor directions are projected onto the unit sphere and the DCM is the sample variance of the volumes of the simplices of their convex hull; if the directions do not span all m dimensions, the DCM is 0. Low values indicate internal points, high values boundary points. Data points with a DCM below the ceil(n · Ratio)-th smallest DCM are internal points, all others are boundary points. The reachable distance r of an internal point is its distance to the nearest boundary point. Two internal points i and j are connected if d(i, j) ≤ r_i + r_j; the clusters are the connected components. Each boundary point is then assigned to the cluster of its nearest internal point. Duplicate data points are clustered once and receive the same label. Distances are Euclidean, so features on different scales should be standardized first. Clusters are numbered in the order in which they first appear in the data. Neighbors are ranked by distance, ties are broken by the lower column index. If no data point has a DCM below the threshold, an error is returned. The implementation follows the authors’ MATLAB reference code: Peng, D., Gui, Z., Wang, D. et al. (2022), Clustering by measuring local direction centrality for data with heterogeneous density and weak connectivity, Nature Communications 13, 5455, https://www.nature.com/articles/s41467-022-33136-9. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaClustering.DBSCAN(DataMatrix, Epsilon, MinPoints) URL: https://www.andreassteiner.net/help/apaclustering.dbscan/ ## Result Clustering with the DBSCAN algorithm. Returns a 1 x c row of cluster labels: -1 for noise points, clusters numbered from 0. ## Syntax *DataMatrix*: r x c data matrix. Objects are in columns, features in rows. *Epsilon*: neighborhood radius (Euclidean distance); must be positive *MinPoints*: minimum number of points within distance Epsilon, including the point itself, for a point to be a core point; integer, at least 1 ## Remarks A good first guess for Epsilon is half the median Euclidean distance between all data points. The labels follow the scikit-learn convention. apaClustering.CDC numbers clusters from 1 and has no noise label. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaClustering.DBSCAN.Epsilon(DataMatrix, MinPoints) URL: https://www.andreassteiner.net/help/apaclustering.dbscan.epsilon/ ## Result Calibrates Epsilon to the knee of the sorted distances of the data points to their (MinPoints - 1)‑th nearest neighbor. Since apaClustering.DBSCAN counts the point itself towards MinPoints, this neighbor determines whether a point is a core point. ## Syntax *DataMatrix*: r x c data matrix. Objects are in columns, features in rows. *MinPoints*: minimum number of points within distance Epsilon, including the point itself, for a point to be a core point; at least 2 ## Remarks The knee is the point of the sorted distance curve with the largest distance to the straight line through its first and last point. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaClustering.Evaluation.Agreement(Clustering1, Clustering2) URL: https://www.andreassteiner.net/help/apaclustering.evaluation.agreement/ ## Result Compares two clusterings using the confusion matrix and the Hungarian algorithm. Returns the number of agreements divided by the number of elements (mismatches plus agreements). ## Syntax *Clustering1*: r x 1 vector of cluster assignments *Clustering2*: r x 1 vector of cluster assignments # apaClustering.Evaluation.ARI(Clustering1, Clustering2) URL: https://www.andreassteiner.net/help/apaclustering.evaluation.ari/ ## Result Calculates the adjusted Rand index (ARI), a metric for evaluating the similarity between two clusterings when the cluster labels do not necessarily correspond. ## Syntax *Clustering1*: r x 1 vector of cluster assignments *Clustering2*: r x 1 vector of cluster assignments # apaClustering.Evaluation.Centroids(DataMatrix, ClusteringResult) URL: https://www.andreassteiner.net/help/apaclustering.evaluation.centroids/ ## Result Evaluates the assignments of a clustering algorithm: cluster centroids. ## Syntax *DataMatrix*: r x c data matrix *ClusteringResult*: r x 1 vector of cluster labels. The labels can be any integer values; points labelled -1 (noise, e.g. from apaClustering.DBSCAN) are excluded. ## Remarks Returns a c x K matrix with one column per cluster, containing the mean of each feature. The clusters are arranged in ascending order of their labels. # apaClustering.Evaluation.InternalMetrics(DataMatrix, ClusteringResult) URL: https://www.andreassteiner.net/help/apaclustering.evaluation.internalmetrics/ ## Result Evaluates the assignments of a clustering algorithm: various internal metrics. ## Syntax *DataMatrix*: r x c data matrix *ClusteringResult*: r x 1 vector of cluster labels. The labels can be any integer values; points labelled -1 (noise, e.g. from apaClustering.DBSCAN) are excluded. ## Remarks Returns a table with the measures WCSS (within-cluster sum of squares), Silhouette, Davies-Bouldin, Calinski-Harabasz, BCSS (between-cluster sum of squares), Dunn and Connectivity. The column Global contains the measure for the whole clustering; WCSS and Silhouette are also reported per cluster, in columns headed with the cluster labels in ascending order. Euclidean distances are used throughout. The silhouette value of a point is (b - a) / max(a, b), where a is the mean distance to the other members of its own cluster and b the mean distance to the members of the nearest other cluster. Points in single-member clusters have a silhouette value of 0. Connectivity sums 1/j over the j = 1, ..., 10 nearest neighbours of each point that belong to a different cluster; lower values are better. # apaClustering.Evaluation.SilhouetteValues(DataMatrix, ClusteringResult) URL: https://www.andreassteiner.net/help/apaclustering.evaluation.silhouettevalues/ ## Result Evaluates the assignments of a clustering algorithm: silhouette values for all data points. ## Syntax *DataMatrix*: r x c data matrix *ClusteringResult*: r x 1 vector of cluster labels. The labels can be any integer values; points labelled -1 (noise, e.g. from apaClustering.DBSCAN) are excluded. ## Remarks Returns three columns: the observation index (0-based row number in DataMatrix), the cluster label and the silhouette value. The rows are sorted by cluster label and, within each cluster, by ascending silhouette value. The silhouette value of a point is (b - a) / max(a, b), where a is the mean distance to the other members of its own cluster and b the mean Euclidean distance to the members of the nearest other cluster. Points in single-member clusters have a silhouette value of 0. # apaClustering.Hierarchical.AverageLinkage(DistanceMatrix) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.averagelinkage/ ## Result Performs a hierarchical cluster analysis based on the average-linkage (UPGMA) algorithm. Returns a (NumberOfElements-1) x 4 matrix with one row per merge. Column 1 is the index of the cluster, column 2 the index of the first cluster constituent, column 3 the index of the second cluster constituent and column 4 the height of the cluster, i.e. the distance at which the two constituents are merged, on the scale of the input distances. ## Syntax *DistanceMatrix*: n x n distance matrix, e.g. from apaDistances.Euclidian ## Algorithm See [https://en.wikipedia.org/wiki/UPGMA](https://en.wikipedia.org/wiki/UPGMA) ## Remarks The distance between two clusters is the mean of all pairwise distances between the members of the first and the members of the second cluster (unweighted pair group method with arithmetic mean). After a merge of clusters A and B, the distance to any other cluster C is updated as (nA·d(A,C) + nB·d(B,C)) / (nA + nB), where nA and nB are the numbers of elements in A and B. The results correspond to the average-linkage method of standard statistical software (e.g. scipy or R). # apaClustering.Hierarchical.ClusterCompositions(ClusteringResult) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.clustercompositions/ ## Result Derives the composition of the clusters as calculated by a hierarchical clustering algorithm. Returns a nElements x nClusters matrix, in which each row represents a cluster. The element indices are listed in the order of their inclusion. ## Syntax *ClusteringResult*: output of a hierarchical clustering function, e.g. apaClustering.Hierarchical.SingleLinkage # apaClustering.Hierarchical.ClusterCompositions.Matrix(ClusteringResult) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.clustercompositions.matrix/ ## Result Derives the composition of the clusters as calculated by a hierarchical clustering algorithm. Returns a nElements x nClusters matrix, in which each row represents a cluster and each column an element. If an element is part of a cluster, its entry is 1 (TRUE), otherwise 0 (FALSE). ## Syntax *ClusteringResult*: output of a hierarchical clustering function, e.g. apaClustering.Hierarchical.SingleLinkage # apaClustering.Hierarchical.Clusters.k(ClusteringResult, k) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.clusters.k/ ## Result Cluster assignments based on the result of a hierarchical clustering algorithm and an imposed number of clusters k. ## Syntax *ClusteringResult*: output of a hierarchical clustering function, e.g. apaClustering.Hierarchical.SingleLinkage *k*: number of clusters to form (numbered from the top of the dendrogram down) # apaClustering.Hierarchical.Result.Matrix(ClusteringResult) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.result.matrix/ ## Result Reformats the result of a hierarchical clustering algorithm as a 1/0 (TRUE/FALSE) matrix. Each row represents a cluster. The first n columns represent the n elements, the next n-1 columns the clusters. ## Syntax *ClusteringResult*: output of a hierarchical clustering function, e.g. apaClustering.Hierarchical.SingleLinkage # apaClustering.Hierarchical.CompleteLinkage(DistanceMatrix) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.completelinkage/ ## Result Performs a hierarchical cluster analysis based on the complete-linkage algorithm. Returns a (NumberOfElements-1) x 4 matrix with one row per merge. Column 1 is the index of the cluster, column 2 the index of the first cluster constituent, column 3 the index of the second cluster constituent and column 4 the height of the cluster, i.e. the distance at which the two constituents are merged, on the scale of the input distances. ## Syntax *DistanceMatrix*: n x n distance matrix, e.g. from apaDistances.Euclidian ## Algorithm See [https://en.wikipedia.org/wiki/Complete-linkage_clustering](https://en.wikipedia.org/wiki/Complete-linkage_clustering) ## Remarks The height of a merge is the largest distance between a member of the first and a member of the second constituent. The results correspond to the complete-linkage method of standard statistical software (e.g. scipy or R). # apaClustering.Hierarchical.CopheneticCorrelationCoefficient(DistanceMatrix, CopheneticMatrix) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.copheneticcorrelationcoefficient/ ## Result Calculates the cophenetic correlation coefficient, a measure to assess the quality of the results of hierarchical clustering algorithms. ## Syntax *DistanceMatrix*: n x n distance matrix used in the clustering algorithm, e.g. from apaDistances.Euclidian *CopheneticMatrix*: n x n cophenetic matrix, e.g. from apaClustering.Hierarchical.CophenticMatrix. # apaClustering.Hierarchical.CophenticMatrix(ClusteringResult) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.cophenticmatrix/ ## Result Calculates the cophenetic matrix from the result of a hierarchical clustering algorithm. ## Syntax *ClusteringResult*: output of a hierarchical clustering function, e.g. apaClustering.Hierarchical.SingleLinkage # apaClustering.kMeans(DataMatrix, nClusters, nMultiStarts) URL: https://www.andreassteiner.net/help/apaclustering.kmeans/ ## Result Statistical classification with the k-means algorithm. ## Syntax *DataMatrix*: r x c data matrix, each column containing a feature *nClusters*: number of clusters *nMultiStarts*: optional; number of k-means++ starts, integer, at least 1; the solution with the lowest within-cluster sum of squares is used; default: 10 ## Algorithm Various descriptions of the k-means algorithm can be found in the statistical literature, see e.g. Wikipedia. ## Remarks The Euclidean distance is used as the grouping criterion. # apaClustering.kMeans.FromDistances(Distances, nClusters, nMultiStarts) URL: https://www.andreassteiner.net/help/apaclustering.kmeans.fromdistances/ ## Result Statistical classification with the k-means algorithm, starting from a distance matrix instead of a data matrix. Returns an n x 1 vector with the cluster label of each object, numbered from 0 to nClusters - 1. ## Syntax *Distances*: n x n symmetric distance matrix with zero diagonal and non-negative entries, e.g. from apaDistances.Euclidian *nClusters*: number of clusters, integer between 1 and n *nMultiStarts*: optional; number of k-means++ starts, integer, at least 1; the solution with the lowest within-cluster sum of squares is used; default: 10 ## Algorithm k-means only needs squared distances between objects and cluster centroids, so the algorithm is carried out on the distance matrix alone: the squared distance of object i to the centroid of cluster C is the mean of d(i,j)² over j in C minus half the mean of d(j,l)² over all pairs j, l in C, and the within-cluster sum of squares of C is the sum of d(j,l)² over all pairs j \< l in C divided by the size of C. The k-means++ initialization draws new starting objects with probability proportional to the squared distance to the nearest object already chosen. ## Remarks If Distances contains the Euclidean distances between the rows of a data matrix, the function returns the same partition as apaClustering.kMeans applied to that data matrix; when several starts reach the same optimum, the numbering of the clusters can differ. Other distance measures can be used as well; the result is then the k-means classification of the objects embedded with these distances. The random starts use a fixed seed, so results are reproducible. # apaClustering.kMeans.Bisecting(DataMatrix, nClusters, nMultiStarts, DoShowStructureOtherwiseFinalGrouping) URL: https://www.andreassteiner.net/help/apaclustering.kmeans.bisecting/ ## Result Statistical classification with the bisecting k-means algorithm. ## Syntax *DataMatrix*: r x c data matrix, each column containing a feature *nClusters*: number of clusters *nMultiStarts*: optional; number of k-means++ starts, integer, at least 1; the solution with the lowest within-cluster sum of squares is used; default: 10 *DoShowStructureOtherwiseFinalGrouping*: optional; TRUE: n x nClusters matrix showing all levels of the bisection, column c containing the grouping into c clusters; FALSE: n x 1 vector with the final grouping; default: FALSE ## Algorithm Various descriptions of the k-means algorithm can be found in the statistical literature, see e.g. Wikipedia. ## Remarks The Euclidean distance is used as the grouping criterion. With DoShowStructureOtherwiseFinalGrouping = TRUE, the first column contains 0 for all objects and each further column is the grouping after one more split: one cluster of the previous column is divided in two, the objects of the other clusters keep their labels and the new cluster gets the label c - 1. The last column equals the final grouping. Columns for levels that cannot be reached because no cluster with more than one object is left are shown as \#N/A. # apaClustering.kMeans.Bisecting.FromDistances(Distances, nClusters, nMultiStarts, DoShowStructureOtherwiseFinalGrouping) URL: https://www.andreassteiner.net/help/apaclustering.kmeans.bisecting.fromdistances/ ## Result Statistical classification with the bisecting k-means algorithm, starting from a distance matrix instead of a data matrix. Returns an n x 1 vector with the cluster label of each object, numbered from 0 to nClusters - 1. ## Syntax *Distances*: n x n symmetric distance matrix with zero diagonal and non-negative entries, e.g. from apaDistances.Euclidian *nClusters*: number of clusters, integer between 1 and n *nMultiStarts*: optional; number of k-means++ starts per bisection, integer, at least 1; the split with the lowest within-cluster sum of squares is used; default: 10 *DoShowStructureOtherwiseFinalGrouping*: optional; TRUE: n x nClusters matrix showing all levels of the bisection, column c containing the grouping into c clusters; FALSE: n x 1 vector with the final grouping; default: FALSE ## Algorithm The algorithm starts with all objects in one cluster and repeatedly splits the cluster with the largest within-cluster sum of squares into two with k-means, until nClusters clusters are formed. Because k-means only needs squared distances between objects and cluster centroids, the procedure is carried out on the distance matrix alone: the squared distance of object i to the centroid of cluster C is the mean of d(i,j)² over j in C minus half the mean of d(j,l)² over all pairs j, l in C, and the within-cluster sum of squares of C is the sum of d(j,l)² over all pairs j \< l in C divided by the size of C. ## Remarks If Distances contains the Euclidean distances between the rows of a data matrix, the function returns the same cluster labels as apaClustering.kMeans.Bisecting applied to that data matrix. Other distance measures can be used as well; the result is then the bisecting k-means classification of the objects embedded with these distances. The random starts use a fixed seed, so results are reproducible. With DoShowStructureOtherwiseFinalGrouping = TRUE, the first column contains 0 for all objects and each further column is the grouping after one more split: one cluster of the previous column is divided in two, the objects of the other clusters keep their labels and the new cluster gets the label c - 1. The last column equals the final grouping. Columns for levels that cannot be reached because no cluster with more than one object is left are shown as \#N/A. # apaClustering.Hierarchical.SingleLinkage(DistanceMatrix) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.singlelinkage/ ## Result Performs a hierarchical cluster analysis based on the single-linkage algorithm. Returns a (NumberOfElements-1) x 4 matrix with one row per merge. Column 1 is the index of the cluster, column 2 the index of the first cluster constituent, column 3 the index of the second cluster constituent and column 4 the height of the cluster, i.e. the distance at which the two constituents are merged, on the scale of the input distances. ## Syntax *DistanceMatrix*: n x n distance matrix, e.g. from apaDistances.Euclidian ## Algorithm See [https://en.wikipedia.org/wiki/Single-linkage_clustering](https://en.wikipedia.org/wiki/Single-linkage_clustering%20) ## Remarks The height of a merge is the smallest distance between a member of the first and a member of the second constituent. The results correspond to the single-linkage method of standard statistical software (e.g. scipy or R). # apaClustering.Hierarchical.SortCorrsOrDists(ClusteringResult, CorrOrDistMatrix) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.sortcorrsordists/ ## Result Sorts a correlation or distance matrix according to the order generated by a clustering algorithm: rows and columns are arranged in the leaf order of the dendrogram, so that elements of the same cluster appear in adjacent blocks. ## Syntax *ClusteringResult*: output of a hierarchical clustering function, e.g. apaClustering.Hierarchical.SingleLinkage *CorrOrDistMatrix*: n x n correlation or distance matrix to be sorted # apaClustering.Hierarchical.WardLinkage(DistanceMatrix) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.wardlinkage/ ## Result Performs a hierarchical cluster analysis based on Ward’s linkage method. Returns a (NumberOfElements-1) x 4 matrix with one row per merge. Column 1 is the index of the cluster, column 2 the index of the first cluster constituent, column 3 the index of the second cluster constituent and column 4 the height of the cluster, i.e. the distance at which the two constituents are merged, on the scale of the input distances. ## Syntax *DistanceMatrix*: n x n distance matrix, e.g. from apaDistances.Euclidian ## Remarks DistanceMatrix should contain Euclidean distances. At each step, the two clusters whose merge causes the smallest increase in the within-cluster sum of squares are merged. The Lance-Williams update of Ward’s method is applied to the squared distances, and the reported heights are their square roots, so they are on the scale of the input distances. The results correspond to the Ward method of scipy and to ward.D2 in R. # apaClustering.Hierarchical.WaterfallAllocation(ClusteringResult) URL: https://www.andreassteiner.net/help/apaclustering.hierarchical.waterfallallocation/ ## Result Derives the “waterfall allocation” from the output of a hierarchical clustering algorithm. ## Syntax *ClusteringResult*: output of a hierarchical clustering function, e.g. apaClustering.Hierarchical.SingleLinkage ## Algorithm ## ![Formula](https://www.andreassteiner.net/help/assets/eq/image29.svg)![Formula](https://www.andreassteiner.net/help/assets/eq/image30.svg)Remarks See Papenbrock (2011): “Asset Clusters and Asset Networks in Financial Risk Management and Portfolio Optimization”. # apaClustering.Spectral.BiPartition(LaplacianMatrix) URL: https://www.andreassteiner.net/help/apaclustering.spectral.bipartition/ ## Result Bi-partitioning by the sign of the entries of the Fiedler vector, i.e. the eigenvector of the second smallest eigenvalue of a Laplacian matrix. Returns an n x 1 vector of labels: 0 for positive entries, 1 for zero or negative entries. ## Syntax *LaplacianMatrix*: n x n Laplacian matrix: L (apaGraph.LaplacianMatrix), L_sym (apaGraph.LaplacianMatrix.Sym) or L_rw (apaGraph.LaplacianMatrix.RW) ## Remarks Symmetric matrices (L, L_sym) are decomposed directly, by Householder tridiagonalization followed by the implicit QL algorithm. The random-walk Laplacian L_rw = D^-1 L is not symmetric; its eigenvectors are computed from the similar symmetric matrix D^1/2 L_rw D^-1/2 and transformed back with D^-1/2. The node weights D are recovered from L_rw itself. A non‑symmetric matrix that is not of the form D^-1 W with a symmetric W returns an error. Eigenvectors are scaled to unit length; their sign is arbitrary. Since the sign of the Fiedler vector is arbitrary, which group receives label 0 is arbitrary as well. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaClustering.Spectral.DBSCAN(LaplacianMatrix, nEigenvectors) URL: https://www.andreassteiner.net/help/apaclustering.spectral.dbscan/ ## Result DBSCAN clustering on the spectral embedding of a Laplacian matrix. MinPoints is set to nEigenvectors + 1, Epsilon is calibrated as in apaClustering.DBSCAN.Epsilon. Returns an n x 1 vector of labels: -1 for noise points, clusters numbered from 0. ## Syntax *LaplacianMatrix*: n x n Laplacian matrix: L (apaGraph.LaplacianMatrix), L_sym (apaGraph.LaplacianMatrix.Sym) or L_rw (apaGraph.LaplacianMatrix.RW) *nEigenvectors*: dimension s of the spectral embedding, i.e. the number of eigenvectors used, excluding the trivial eigenvector of the smallest eigenvalue; integer between 1 and n - 2. It does not set the number of clusters, which DBSCAN determines itself. ## Remarks The spectral embedding consists of the eigenvectors of the 2nd to (s + 1)-th smallest eigenvalues of LaplacianMatrix; the eigenvector of the smallest eigenvalue (constant for L and L_rw) carries no cluster information and is skipped. Symmetric matrices (L, L_sym) are decomposed directly, by Householder tridiagonalization followed by the implicit QL algorithm. The random-walk Laplacian L_rw = D^-1 L is not symmetric; its eigenvectors are computed from the similar symmetric matrix D^1/2 L_rw D^-1/2 and transformed back with D^-1/2. The node weights D are recovered from L_rw itself. A non‑symmetric matrix that is not of the form D^-1 W with a symmetric W returns an error. Eigenvectors are scaled to unit length; their sign is arbitrary. MinPoints = s + 1 follows the rule of thumb of at least one more point than the embedding dimension; Epsilon is the knee of the sorted distances of each point to its s-th nearest neighbor (DBSCAN counts the point itself). The data points are the rows of the embedding. With the calibrated Epsilon and the small MinPoints, the method tends to split elongated or ring-shaped clusters into many small clusters; apaClustering.Spectral.kMeans is usually more robust when the number of clusters is known. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaClustering.Spectral.kMeans(LaplacianMatrix, nEigenvectors, nStarts, DoNormalizeRows) URL: https://www.andreassteiner.net/help/apaclustering.spectral.kmeans/ ## Result k-means clustering on the spectral embedding of a Laplacian matrix with k = nEigenvectors + 1 clusters. Returns an n x 1 vector of cluster labels from 0 to k - 1. ## Syntax *LaplacianMatrix*: n x n Laplacian matrix: L (apaGraph.LaplacianMatrix), L_sym (apaGraph.LaplacianMatrix.Sym) or L_rw (apaGraph.LaplacianMatrix.RW) *nEigenvectors*: number of eigenvectors s, excluding the trivial eigenvector of the smallest eigenvalue; integer between 1 and n - 2. Determines the number of clusters k = s + 1; for k clusters, set nEigenvectors to k - 1. With DoNormalizeRows = TRUE the embedding has s + 1 columns, since the trivial eigenvector is included. *nStarts*: optional; number of k-means++ starts; the solution with the lowest within-cluster sum of squares is returned; default: 10 *DoNormalizeRows*: optional; TRUE to scale each row of the embedding to unit length, with the embedding then also including the trivial eigenvector (Ng–Jordan–Weiss); FALSE to use the eigenvectors as they are; default: FALSE ## Remarks The spectral embedding consists of the eigenvectors of the 2nd to (s + 1)-th smallest eigenvalues of LaplacianMatrix; the eigenvector of the smallest eigenvalue (constant for L and L_rw) carries no cluster information and is skipped. Symmetric matrices (L, L_sym) are decomposed directly, by Householder tridiagonalization followed by the implicit QL algorithm. The random-walk Laplacian L_rw = D^-1 L is not symmetric; its eigenvectors are computed from the similar symmetric matrix D^1/2 L_rw D^-1/2 and transformed back with D^-1/2. The node weights D are recovered from L_rw itself. A non‑symmetric matrix that is not of the form D^-1 W with a symmetric W returns an error. Eigenvectors are scaled to unit length; their sign is arbitrary. Row normalization is recommended for L_sym, whose embedding rows scale with the square root of the node degree. The random starts use a fixed seed, so results are reproducible. The cluster labels are numbered in the order found and carry no meaning. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaCokurts(Returns) URL: https://www.andreassteiner.net/help/apacokurts/ ## Result Calculates the cokurtosis matrix (population fourth central comoments, division by n). ## Syntax *Returns*: nObs x nAssets matrix of returns, each column containing a time series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image31.svg) # apaCoskews(R) URL: https://www.andreassteiner.net/help/apacoskews/ ## Result Calculates the coskewness matrix (joint third moments). ## Syntax *R*: nObs x nAssets matrix of returns, each column containing a time series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image32.svg) ## Remarks Population coskewness (denominator n). # apaCoLPM(Returns1, Returns2, Threshold, Degree) URL: https://www.andreassteiner.net/help/apacolpm/ ## Result Calculates the co-lower partial moment (co-LPM) risk measure between two return series. ## Syntax *Returns1*: r x 1 vector of returns *Returns2*: r x 1 vector of returns *Threshold*: return threshold *Degree*: degree (order) of the lower partial moment ## Algorithm If Degree \> 1: ![Formula](https://www.andreassteiner.net/help/assets/eq/image33.svg) If Degree = 1: ![Formula](https://www.andreassteiner.net/help/assets/eq/image34.svg) If Degree \< 1: ![Formula](https://www.andreassteiner.net/help/assets/eq/image35.svg) ## Remarks - Denisa Cumova (2004): “Asset Allocation Based on Shortfall Risk”. - Lingwen Kong (2005): “The UPM/LPM Framework on Portfolio Performance Measurement and Optimization”. Partial moments divide by the total number of observations n (population-type). # apaCoLPMs.Asymmetrical(ReturnsMatrix, Threshold, Degree) URL: https://www.andreassteiner.net/help/apacolpms.asymmetrical/ ## Result Calculates the asymmetric co-lower partial moment (co-LPM) matrix. ## Syntax *ReturnsMatrix*: r x c matrix of returns, each column containing a time series *Threshold*: return threshold *Degree*: degree (order) of the lower partial moments ## Remarks Partial moments divide by the total number of observations n (population-type). # apaCoLPMs.Asymmetrical.Symmetrized(ReturnsMatrix, Threshold, Degree) URL: https://www.andreassteiner.net/help/apacolpms.asymmetrical.symmetrized/ ## Result Calculates the symmetrized asymmetric co-lower partial moment (co-LPM) matrix. ## Syntax *ReturnsMatrix*: r x c matrix of returns, each column containing a time series *Threshold*: return threshold *Degree*: degree (order) of the lower partial moments ## Remarks Partial moments divide by the total number of observations n (population-type). # apaCoLPMs.Symmetrical(ReturnsMatrix, Threshold, Degree) URL: https://www.andreassteiner.net/help/apacolpms.symmetrical/ ## Result Calculates the symmetric co-lower partial moment (co-LPM) matrix. ## Syntax *ReturnsMatrix*: r x c matrix of returns, each column containing a time series *Threshold*: return threshold *Degree*: degree (order) of the lower partial moments ## Remarks Partial moments divide by the total number of observations n (population-type). # apaConditionalSerialCorrelation(TimeSeries, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaconditionalserialcorrelation/ ## Result Calculates the conditional serial correlation, a fraud indicator, by regressing returns on lagged returns and on lagged returns below the mean. Returns the coefficients and their confidence bounds. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *ConfidenceLevel*: confidence level for the statistical hypothesis tests, e.g. 0.95 ## Algorithm OLS estimation of the following regression: ![Formula](https://www.andreassteiner.net/help/assets/eq/image36.svg) The result consists of the parameter values, t-tests at the given confidence level and p-values. ## Remarks Residual variance is SSE/(n − k), i.e. degrees-of-freedom corrected. # apaConditionalSharpeRatio(PortfolioReturns, RiskfreeReturns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaconditionalsharperatio/ ## Result Calculates the conditional Sharpe ratio, a risk-adjusted performance measure, i.e. the average excess return divided by the historical CVaR. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *RiskfreeReturns*: r x 1 vector of riskfree returns (i.e. a time series) or a single riskfree rate *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image37.svg) # apaCone.Linear(TimeSeries, FirstIdx, SecondIdx, nForecasts, Sigma1, Sigma2, IsStacked) URL: https://www.andreassteiner.net/help/apacone.linear/ ## Result Calculates forecast intervals (cone) for an imposed linear trend through two observations of a time series. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *FirstIdx*: index of the first observation *SecondIdx*: index of the second observation *nForecasts*: number of out-of-sample forecasts *Sigma1*: first confidence level, defined as number of standard deviations away from the mean *Sigma2*: second confidence level, defined as number of standard deviations away from the mean *IsStacked*: TRUE to return the relative differences between the confidence levels (e.g. for stacked area charts), FALSE to return absolute levels ## Remarks The residual volatility uses the denominator (number of fitted points − 1). # apaCone.Polynomial(TimeSeries, Order, StartIdx, EndIdx, nForecasts, Sigma1, Sigma2, IsStacked) URL: https://www.andreassteiner.net/help/apacone.polynomial/ ## Result Calculates forecast intervals (cone) for a polynomial trend fitted to a time series. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *Order*: order of the polynomial *StartIdx*: index of the beginning observation *EndIdx*: index of the ending observation *nForecasts*: number of out-of-sample forecasts *Sigma1*: first confidence level, defined as number of standard deviations away from the mean *Sigma2*: second confidence level, defined as number of standard deviations away from the mean *IsStacked*: TRUE to return the relative differences between the confidence levels (e.g. for stacked area charts), FALSE to return absolute levels ## Remarks The residual volatility is the sample standard deviation of the residuals (denominator n − 1). # apaConfusionMatrix(YObserved, YPredicted) URL: https://www.andreassteiner.net/help/apaconfusionmatrix/ ## Result Returns the confusion matrix for observed and predicted class labels, with rows representing actual classes and columns representing predicted classes. ## Syntax *YObserved*: n x 1 vector of observed class labels (1..K) *YPredicted*: n x 1 vector of predicted class labels (1..K) ## Algorithm Inputs are validated: non-empty column vectors with the same number of rows. Compute the $`K \times K`$confusion matrix where entry $`\left( i,j \right)`$is the count of observations with actual class $`i`$and predicted class $`j`$. Return a table with: - Header row: “Actual \\ Pred” plus predicted class labels $`1..K`$. - Header column: actual class labels $`1..K`$. - Inner cells: confusion counts. # apaContours(Xseries, Yseries, OutlierCutoff, nContours, BandwidthAdjust, IsEmpiricalOtherwiseGaussian, IsCopulaScale) URL: https://www.andreassteiner.net/help/apacontours/ ## Result Calculates either the contour lines of the bivariate Gaussian kernel density of two series or the Gaussian ellipses implied by their sample means, variances and correlation, together with the observations outside the outermost contour, as inputs for an X-Y scatter chart with density contours, i.e. a scatter plot overlaid with seaborn.kdeplot contours. The result is a matrix that can be charted directly as an X-Y scatter chart. The first row contains the series names: X, one column per contour line labeled “Contour m” with the probability mass m it encloses, from the outermost to the innermost contour, and Outliers. The first column contains the x values of all points; each further column contains the y values of its series in the rows of its points. Each contour line is followed by a row of \#N/A; the outliers follow in consecutive rows. All remaining cells show \#N/A. ## Syntax *Xseries*: n x 1 vector of observations shown on the horizontal axis *Yseries*: n x 1 vector of observations shown on the vertical axis, with the same number of observations as Xseries *OutlierCutoff*: optional; probability mass enclosed by the outermost contour; the observations outside it are returned as outliers, e.g. 0.98 for the outer 2% of the probability mass; must be \> 0 and \<= 1; default: 0.98 *nContours*: optional; number of contour lines; contour k = 1, …, nContours encloses the probability mass OutlierCutoff × k / nContours, so each band between two neighbouring contours holds OutlierCutoff / nContours of the mass; default: 10 *BandwidthAdjust*: optional; multiplier of the Scott’s rule bandwidth factor n^(−1/6), e.g. 2 for smoother contours; must be \> 0; not used for Gaussian contours; default: 1 *IsEmpiricalOtherwiseGaussian*: optional; TRUE for the empirical kernel density contours, FALSE for the Gaussian ellipses implied by the sample means, variances and correlation (denominator n − 1); default: TRUE *IsCopulaScale: optional; TRUE to draw the contours on the copula scale: Xseries and Yseries are converted to pseudo-observations rank / (n + 1) in (0, 1), the contours are estimated on the corresponding normal scores and mapped back to the unit square; FALSE to use the observations as they are; default: FALSE* ## Algorithm The density is estimated with a Gaussian kernel whose covariance matrix equals the sample covariance matrix of Xseries and Yseries (denominator n − 1) multiplied by (BandwidthAdjust × n^(−1/6))², the bivariate Scott’s rule. It is evaluated on a 200 x 200 grid that extends the data range by three kernel standard deviations on each side. Contour k encloses the probability mass m = OutlierCutoff × k / nContours. In empirical mode, m is converted to the density value at which the grid points with higher density hold the share m of the total density mass. The contour lines at these density values are traced with the marching squares algorithm and linear interpolation along the grid edges. The results correspond to seaborn.kdeplot with gridsize 200, cut 3, levels = nContours + 1, thresh = 1 − OutlierCutoff and bw_adjust = BandwidthAdjust. A contour that would enclose the whole mass (m = 1) is not drawn. If IsEmpiricalOtherwiseGaussian is FALSE, the contours are the ellipses of the bivariate normal distribution with the sample means and the sample covariance matrix (denominator n − 1). The ellipse for the mass m consists of the points with squared Mahalanobis distance −2 ln(1 − m) from the means, so that exactly the share m of the normal probability mass lies inside it. Each ellipse is drawn with 200 segments. Comparing both modes shows where the empirical distribution deviates from the normal one, e.g. through fat tails, skewness or asymmetric dependence. Outliers are the observations outside the outermost contour under the selected model. In empirical mode, these are the observations whose kernel density, evaluated exactly at the observation, is below the density value of the outermost contour. In Gaussian mode, these are the observations whose squared Mahalanobis distance from the means exceeds −2 ln(1 − OutlierCutoff). Hence no outlier lies inside the outermost contour. If IsCopulaScale is TRUE, each series is first replaced by its pseudo-observations u = rank / (n + 1), with tied values receiving their average rank, and then by the normal scores z = Φ⁻¹(u). The density, the contour levels, the contour lines and the outliers are computed on the normal scores exactly as described above, in empirical or Gaussian mode. Finally, every contour vertex is mapped back with the standard normal distribution function Φ, and the outliers are returned as pseudo-observations. Because this transformation is monotone, each contour still encloses the probability mass m, and the contours lie inside the unit square without the boundary leakage of a kernel density estimated directly on values in \[0, 1\] (probit transformation estimator). In Gaussian mode, the contours are those of the Gaussian copula with the correlation of the normal scores. ## Remarks To draw the chart, select the whole result including the first row and insert an X-Y scatter chart with straight lines and markers. Remove the markers of the contour series and the line of the Outliers series. In Hidden and Empty Cells, select Show \#N/A as an empty cell and show empty cells as Gaps, so that the \#N/A rows separate the contour lines. The observations themselves can be added as a further marker series. Outlier labels such as dates can be computed in a column next to the result, e.g. by matching the x and y values of the Outliers rows with Xseries and Yseries, and attached to the Outliers series with Data Labels, Value From Cells. The number of outliers is in general not (1 − OutlierCutoff) × n, because the share refers to the probability mass of the model, not to the observations. In empirical mode, the kernel smoothing spreads mass beyond the data, so usually fewer observations lie outside; in Gaussian mode, fat tails lead to more observations outside the outermost ellipse than the normal distribution implies. Use IsCopulaScale = TRUE to analyse the dependence between two series independently of their marginal distributions, e.g. when Xseries and Yseries are empirical distribution function values or returns with different volatilities. The result is the same whether returns or their empirical distribution function values are passed, because only the ranks are used. To overlay the observations, plot them as rank / (n + 1). The contours enclose equal probability mass on the normal-score scale and are not level sets of the copula density; tail dependence shows as contours that reach further into the lower-left and upper-right corners than the Gaussian copula contours. The function is non-volatile. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaContribution.Beta(AssetWeights, AssetReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/apacontribution.beta/ ## Result Calculates the ex post contributions to portfolio beta, based on time-variable asset weights. ## Syntax *AssetWeights*: r x n matrix of time-variable asset weights *AssetReturns*: r x n matrix of asset returns, each column containing a time series *BenchmarkReturns*: r x 1 vector of benchmark returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image38.svg) ## Remarks Ratio of sample covariance to sample variance (denominator n − 1); population moments give the same beta. # apaContribution.Correls(Weights, Returns) URL: https://www.andreassteiner.net/help/apacontribution.correls/ ## Result Returns the asset contributions to the correlation of an asset with the overall portfolio. ## Syntax *Weights*: 1 x c matrix of constituent weights *Returns*: r x c matrix of constituent returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image39.svg) ρ_(i,P) = correlation of an asset with the overall portfolio w_(j) = weight of asset j σ_(J) = volatility of asset j σ_(P) = volatility of the overall portfolio ρ_(i,P) = correlation between assets i and j ## Remarks Uses population volatilities (denominator n). # apaContribution.CVaR.Normal(Weights, Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apacontribution.cvar.normal/ ## Result Calculates the contributions to ex ante portfolio normal CVaR from portfolio constituent weights and returns. ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks The output has three rows: marginal contributions, contributions (weight times marginal contribution) and percentage contributions. The contributions sum to the portfolio measure, which is negative for losses; the percentage contributions sum to one. Uses population covariances (denominator n). # apaContribution.CVaR.Numerical(Weights, Returns, ConfidenceLevel, IsSmooth) URL: https://www.andreassteiner.net/help/apacontribution.cvar.numerical/ ## Result Calculates numerical contributions to non-parametric (historical) conditional value at risk (CVaR). ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. *IsSmooth*: TRUE for the smoothed CVaR estimate (see apaCVaR.Empirical), FALSE otherwise ## Remarks Numerical marginal contributions are calculated. # apaContribution.CVaR.Modified(Weights, Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apacontribution.cvar.modified/ ## Result Calculates the contributions to parametric modified conditional value at risk (modified CVaR). ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks The output has three rows: marginal contributions, contributions (weight times marginal contribution) and percentage contributions. The contributions sum to the portfolio measure, which is negative for losses; the percentage contributions sum to one. Uses population covariances, coskewness and cokurtosis (denominator n). # apaContribution.CDaR.Numerical(Weights, Returns, ConfidenceLevel, IsSmooth) URL: https://www.andreassteiner.net/help/apacontribution.cdar.numerical/ ## Result Calculates numerical contributions to non-parametric conditional drawdown at risk (CDaR). ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. *IsSmooth*: TRUE for smooth interpolation, FALSE otherwise ## Remarks Numerical marginal contributions are calculated. # apaContribution.DaR.Numerical(Weights, Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apacontribution.dar.numerical/ ## Result Calculates numerical contributions to non-parametric drawdown at risk (DaR). ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks Numerical marginal contributions are calculated. # apaContribution.Kurtosis(Weights, Returns) URL: https://www.andreassteiner.net/help/apacontribution.kurtosis/ ## Result Calculates the contributions of portfolio constituents to portfolio kurtosis (population moments). ## Syntax *Weights*: 1 x c matrix of constituent weights *Returns*: r x c matrix of constituent returns ## Algorithm The formulas are rather complex expressions. They can be found in Boudt/Peterson/Croux (2007): “Estimation and Decomposition of Downside Risk for Portfolios with Non-Normal Returns”. ## Remarks The population kurtosis is decomposed, not the sample version. The output has three rows: marginal contributions to kurtosis, contributions to excess kurtosis (they sum to the portfolio excess kurtosis when the weights sum to one) and percentage contributions to kurtosis (not excess kurtosis), which sum to one. # apaContribution.Return(Weights, Returns) URL: https://www.andreassteiner.net/help/apacontribution.return/ ## Result Returns the marginal contributions, constituent contributions and percentage constituent contributions to portfolio return. ## Syntax *Weights*: 1 x m vector of constituent weights *Returns*: n x m matrix of asset returns # apaContribution.SharpeRatio(Weights, ExpectedReturns, Covariances) URL: https://www.andreassteiner.net/help/apacontribution.sharperatio/ ## Result Returns the marginal contributions, component contributions and component percentage contributions to the portfolio Sharpe ratio, calculated from constituent weights, expected returns and covariances. ## Syntax *Weights*: 1 x c vector of constituent weights *ExpectedReturns*: 1 x c vector of constituent expected returns *Covariances*: c x c covariance matrix of the constituents ## Algorithm See our research note “Sharpe Ratios Are Homogeneous of Degree Zero” for details. ## Remarks Component contributions add up to zero, not to the total portfolio Sharpe ratio. Therefore, component percentage contributions add up to 0%, not to 100%. # apaContribution.SharpeRatio.Incremental(Weights, ExpectedReturns, Covariances) URL: https://www.andreassteiner.net/help/apacontribution.sharperatio.incremental/ ## Result Returns the incremental contributions to the portfolio Sharpe ratio. ## Syntax *Weights*: 1 x m vector of constituent weights *ExpectedReturns*: 1 x m vector of expected returns *Covariances*: m x m covariance matrix ## Algorithm The incremental Sharpe ratio of an asset is calculated as the difference between the original portfolio Sharpe ratio and the Sharpe ratio of the portfolio without the asset. ## Remarks Rebalancing assumption: when removing an asset, the remaining assets form a subportfolio which is scaled such that the total exposure equals 100% again. # apaContribution.Skewness(Weights, Returns) URL: https://www.andreassteiner.net/help/apacontribution.skewness/ ## Result Calculates the contributions of portfolio constituents to portfolio skewness. ## Syntax *Weights*: 1 x c matrix of constituent weights *Returns*: r x c matrix of constituent returns ## Algorithm The formulas are rather complex expressions. They can be found in Boudt/Peterson/Croux (2007): “Estimation and Decomposition of Downside Risk for Portfolios with Non-Normal Returns”. ## Remarks The population skewness is decomposed, not the sample version. Uses population covariances and coskewness (denominator n). # apaTrackingError.Contributions.ActiveWeights(ActiveWeights, Returns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apatrackingerror.contributions.activeweights/ ## Result Returns the marginal tracking errors, the contributions to tracking error and the percentage contributions to tracking error, given a vector of active weights and constituent returns. ## Syntax *ActiveWeights*: 1 x n vector of active constituent weights (portfolio weight minus benchmark weight); active weights sum up to zero *Returns*: r x n matrix of constituent returns, each column containing a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: FALSE ## Remarks It is implicitly assumed that the constituent returns in the portfolio and in the benchmark are identical. The output is a matrix consisting of three rows and as many columns as there are assets. The contributions are based on the sample (denominator n − 1) or population (denominator n) covariance matrix, set by IsSampleOtherwisePopulation (default: population); their sum equals the tracking error of the same type. # apaTrackingError.FromActiveWeights(ActiveWeights, Returns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apatrackingerror.fromactiveweights/ ## Result Calculates the tracking error from active weights and constituent returns. ## Syntax *ActiveWeights*: 1 x n vector of active weights, i.e. portfolio minus benchmark weights. *Returns*: r x n matrix of constituent returns, each column containing a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: TRUE ## Algorithm The tracking error is calculated as the volatility of the active portfolio, i.e. the portfolio with the active weights. ## Remarks Sample (denominator n − 1) or population (denominator n) covariances are used, set by IsSampleOtherwisePopulation; default: sample. # apaTrackingError.FromActiveWeightsReturns(PortfolioWeights, BenchmarkWeights, PortfolioReturns, BenchmarkReturns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apatrackingerror.fromactiveweightsreturns/ ## Result Calculates the tracking error from portfolio and benchmark weights, if the constituent returns of portfolio and benchmark are different. ## Syntax *PortfolioWeights*: 1 x n vector of portfolio constituent weights *BenchmarkWeights*: 1 x m vector of benchmark constituent weights *PortfolioReturns*: r x n matrix of portfolio constituent returns *BenchmarkReturns*: r x m matrix of benchmark constituent returns *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: TRUE ## Algorithm The tracking error is calculated as the volatility of the active return time series, i.e. the portfolio return minus the benchmark return. ## Remarks Portfolio and benchmark can have different numbers of constituents. Both return matrices must have the same number of observations. Sample (denominator n − 1) or population (denominator n) covariances are used, set by IsSampleOtherwisePopulation; default: sample. # apaContribution.TrackingError(PortfolioWeights, BenchmarkWeights, PortfolioReturns, BenchmarkReturns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apacontribution.trackingerror/ ## Result Returns the marginal tracking errors, the contributions to tracking error and the percentage contributions to tracking error, given portfolio and benchmark weights and the constituent returns of portfolio and benchmark. ## Syntax *PortfolioWeights*: 1 x n vector of portfolio weights *BenchmarkWeights*: 1 x n vector of benchmark weights *PortfolioReturns*: r x n matrix of constituent returns in the portfolio, each column containing a time series *BenchmarkReturns*: r x n matrix of constituent returns in the benchmark, each column containing a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: FALSE ## Remarks The output is a matrix consisting of twelve rows and as many columns as there are assets. The first three output rows contain risk contributions from differences in asset weights between portfolio and benchmark. The next three rows contain risk contributions from differences in asset returns. The next three rows contain residual risk contributions which cannot be assigned to differences in weights or returns. The last three rows contain the total risk contributions. Sample (denominator n − 1) or population (denominator n) covariances are used, set by IsSampleOtherwisePopulation; default: population. # apaContribution.TrackingError.VariableWeights(PortfolioWeights, AssetReturns, BenchmarkReturns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apacontribution.trackingerror.variableweights/ ## Result Calculates the contributions to ex post portfolio tracking error, taking into account time-variable portfolio weights. ## Syntax *PortfolioWeights*: r x n matrix of time-variable portfolio constituent weights, each row summing to 1, or 1 x n vector of constant weights *AssetReturns*: r x n matrix of constituent returns *BenchmarkReturns*: r x 1 vector of benchmark returns *IsSampleOtherwisePopulation*: optional; TRUE for sample volatilities (division by n-1), FALSE for population volatilities (division by n); default: FALSE ## Remarks Sample (denominator n − 1) or population (denominator n) volatilities are used, set by IsSampleOtherwisePopulation; default: population. The output has two rows and as many columns as there are assets. The first row contains the contributions c(i) = correl(a(i), a) x vol(a(i)), where a(i) is the series of active return contributions w(i,t) x (r(i,t) - b(t)) and a is the active return; the contributions sum to the tracking error. The second row contains each contribution divided by the sum of the absolute contributions. A constituent whose contribution series is constant, e.g. because its weight is zero in all periods, has a contribution of 0. If the active return is constant, all contributions are 0. # apaContribution.VaR.Normal(Weights, Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apacontribution.var.normal/ ## Result Calculates the contributions to ex ante portfolio normal VaR from portfolio constituent weights and returns. ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks The output has three rows: marginal contributions, contributions (weight times marginal contribution) and percentage contributions. The contributions sum to the portfolio measure, which is negative for losses; the percentage contributions sum to one. Uses population covariances (denominator n). # apaContribution.VaR.Numerical(Weights, Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apacontribution.var.numerical/ ## Result Calculates numerical contributions to non-parametric (historical) value at risk (VaR). ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks Numerical marginal contributions are calculated. # apaContribution.VaR.Modified(Weights, Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apacontribution.var.modified/ ## Result Calculates the contributions to parametric modified value at risk (modified VaR). ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks The output has three rows: marginal contributions, contributions (weight times marginal contribution) and percentage contributions. The contributions sum to the portfolio measure, which is negative for losses; the percentage contributions sum to one. Uses population covariances, coskewness and cokurtosis (denominator n). # apaContribution.Volatility(Weights, Covars) URL: https://www.andreassteiner.net/help/apacontribution.volatility/ ## Result Calculates the contributions of portfolio constituents to ex ante portfolio volatility, calculated from constituent covariances. ## Syntax *Weights*: 1 x c matrix of constituent weights *Covars*: c x c covariance matrix # apaContribution.Volatility.ExpWeighted(Weights, Returns, HalfLife) URL: https://www.andreassteiner.net/help/apacontribution.volatility.expweighted/ ## Result Calculates the contributions of portfolio constituents to ex ante exponentially weighted portfolio volatility. ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *HalfLife*: half-life of the exponential weighting scheme ## Remarks Exponentially weighted moments; the weights sum to one (population-type, no small-sample correction). # apaContribution.Volatility.Incremental(Weights, Covariances) URL: https://www.andreassteiner.net/help/apacontribution.volatility.incremental/ ## Result Returns the incremental contributions to portfolio volatility. ## Syntax *Weights*: 1 x m vector of constituent weights *Covariances*: m x m covariance matrix ## Algorithm The incremental volatility of an asset is calculated as the difference between the original portfolio volatility and the volatility of the portfolio without the asset. ## Remarks Rebalancing assumption: when removing an asset, the remaining assets form a subportfolio which is scaled such that the total exposure equals 100% again. # apaContribution.Volatility.VariableWeights(Weights, Returns) URL: https://www.andreassteiner.net/help/apacontribution.volatility.variableweights/ ## Result Calculates the contributions to ex post portfolio volatility, taking into account time-variable constituent weights. ## Syntax *Weights*: n x c matrix containing time-variable constituent weights *Returns*: n x c matrix of constituent returns, each column containing a time series ## Remarks Uses the population volatility (denominator n). # apaCopula.Empirical.Cdf(X, Y, nBins) URL: https://www.andreassteiner.net/help/apacopula.empirical.cdf/ ## Result Cumulative distribution function (cdf) of the bivariate empirical copula. ## Syntax *X*: n x 1 data vector X *Y*: n x 1 data vector Y *nBins*: number of bins # apaCopula.Empirical.Pdf(X, Y, nBins) URL: https://www.andreassteiner.net/help/apacopula.empirical.pdf/ ## Result Probability density function (pdf) of the bivariate empirical copula. ## Syntax *X*: n x 1 data vector X *Y*: n x 1 data vector Y *nBins*: number of bins # apaCopula.Empirical.Pdf.Multivariate(Cdfs, nBins) URL: https://www.andreassteiner.net/help/apacopula.empirical.pdf.multivariate/ ## Result Multivariate empirical copula density function: all pairwise copula densities. ## Syntax *Cdfs*: r x c matrix of cdfs, each column containing a variable *nBins*: number of bins # apaCopula.Empirical.Pdf.Multivariate.Bi(SeriesIdx1, SeriesIdx2, Cdfs, nBins) URL: https://www.andreassteiner.net/help/apacopula.empirical.pdf.multivariate.bi/ ## Result Multivariate empirical copula density function of a particular pair of data series. ## Syntax *SeriesIdx1*: index of the first data series *SeriesIdx2*: index of the second data series *Cdfs*: r x c matrix of cdfs, each column containing a variable *nBins*: number of bins # apaCopula.Empirical.Pdf.Multivariate.Uni(SeriesIdx, Cdfs, nBins) URL: https://www.andreassteiner.net/help/apacopula.empirical.pdf.multivariate.uni/ ## Result Multivariate empirical copula density functions of all pairs involving a particular data series. ## Syntax *SeriesIdx*: index of data series *Cdfs*: r x c matrix of cdfs, each column containing a variable *nBins*: number of bins # apaCopula.Empirical.Pdf.Multivariate.Pairs(Cdfs, nBins) URL: https://www.andreassteiner.net/help/apacopula.empirical.pdf.multivariate.pairs/ ## Result Multivariate empirical copula density functions of all neighboring pairs (e.g. A-B, B-C, C-D and so on). ## Syntax *Cdfs*: r x c matrix of cdfs, each column containing a variable *nBins*: number of bins # apaCopula.Empirical.Resample(nResamples, Cdfs, nBins) URL: https://www.andreassteiner.net/help/apacopula.empirical.resample/ ## Result Resamples observations from an empirical copula. ## Syntax *nResamples*: number of observations to resample *Cdfs*: r x c matrix of cdfs, each column containing a variable *nBins*: number of bins # apaCopula.Empirical.Resample.Shrink(nResamples, Cdfs, nBins, Shrinkage, TargetType, TargetParameter) URL: https://www.andreassteiner.net/help/apacopula.empirical.resample.shrink/ ## Result Resamples observations from an empirical copula and applies shrinkage towards a parametric copula. ## Syntax *nResamples*: number of observations to resample *Cdfs*: r x c matrix of cdfs, each column containing a variable *nBins*: number of bins *Shrinkage*: shrinkage parameter between 0 and 1 *TargetType*: shrinkage target, i.e. the assumed copula: “Gauss” or “Clayton” *TargetParameter*: parameter of the shrinkage target: a correlation between -1 and +1 in the case of “Gauss”, a left tail dependence parameter alpha larger than -1 in the case of “Clayton” # apaCopula.Independent.Sim(nObs, nDims) URL: https://www.andreassteiner.net/help/apacopula.independent.sim/ ## Result Simulates uniform marginals from the independence copula: an nObs x nDims matrix of independent uniform random numbers. ## Syntax *nObs*: number of observations to simulate *nDims*: optional; number of columns (dimensions), at least 2; default: 2 ## Remarks This function is volatile, i.e. it is recalculated whenever a change occurs in the workbook, even if not related to the function’s output, and when pressing F9. # apaCopula.SymJoeClayton.Estimate(Data, \[IsUniform\], \[DoMultivariateOtherwiseBivariate\]) URL: https://www.andreassteiner.net/help/apacopula.symjoeclayton.estimate/ ## Result Estimates the upper and lower tail dependence of the symmetrized Joe-Clayton copula from a sample: a 2 x 1 vector (TauUpper; TauLower) for all k columns jointly, or a k x k matrix of bivariate estimates. ## Syntax *Data*: r x k matrix of observations (k ≥ 2), e.g. returns, each column containing a variable; no missing values *IsUniform*: optional; TRUE if Data already contains uniform marginals strictly between 0 and 1, FALSE to convert each column to ranks / (r + 1) (average ranks for ties); default: FALSE *DoMultivariateOtherwiseBivariate*: optional; TRUE fits one exchangeable copula to all columns and returns 2 x 1; FALSE returns a k x k matrix with the bivariate TauUpper of columns i and j above the diagonal (row i \< column j), TauLower below the diagonal (row i \> column j), \#N/A on the diagonal; default: TRUE ## Algorithm Pseudo-observations: u_ij = rank(x_ij) / (r + 1) per column, unless IsUniform is TRUE. Composite (pairwise) log-likelihood: the sum over all k(k − 1)/2 column pairs of the log density of the bivariate symmetrized Joe-Clayton copula, with a common TauUpper and TauLower for all pairs. Maximization over logit-transformed parameters (both in (0, 1)): 9 x 9 starting grid, refined by Nelder-Mead. ## Remarks For k = 2 the composite likelihood equals the full likelihood. For k ≥ 3 the result is the exchangeable parameter set used by apaCopula.SymJoeClayton.Sim with nDims = k. If DoMultivariateOtherwiseBivariate is FALSE, each pair is fitted separately by full maximum likelihood; entries (i, j) and (j, i) equal TauUpper and TauLower for the two columns i and j alone. Patton (2006): "Modelling Asymmetric Exchange Rate Dependence", International Economic Review 47(2). # apaCopula.SymJoeClayton.Cdf(tauU, tauL, U, V) URL: https://www.andreassteiner.net/help/apacopula.symjoeclayton.cdf/ ## Result Cumulative distribution function of the symmetrized Joe-Clayton copula. ## Syntax *tauU*: upper tail dependence parameter *tauL*: lower tail dependence parameter *U*: first uniform marginal, between 0 and 1 *V*: second uniform marginal, between 0 and 1 # apaCopula.SymJoeClayton.Pdf(TauU, TauL, u, v) URL: https://www.andreassteiner.net/help/apacopula.symjoeclayton.pdf/ ## Result Probability density function of the symmetrized Joe-Clayton copula. ## Syntax *TauU*: upper tail dependence parameter *TauL*: lower tail dependence parameter *u*: first uniform marginal, between 0 and 1 *v*: second uniform marginal, between 0 and 1 # apaCopula.SymJoeClayton.Sim(n, TauUpper, TauLower, nDims) URL: https://www.andreassteiner.net/help/apacopula.symjoeclayton.sim/ ## Result Simulates uniform marginals from the symmetrized Joe-Clayton copula: an n x nDims matrix with the same upper and lower tail dependence for all pairs of columns. ## Syntax *n*: number of observations to simulate *TauUpper*: upper tail dependence parameter, between 0 and 1 (exclusive) *TauLower*: lower tail dependence parameter, between 0 and 1 (exclusive) *nDims*: optional; number of columns (dimensions), at least 2; all pairs of columns share the same dependence parameters; default: 2 ## Algorithm Each row is drawn with probability ½ from the Joe-Clayton (BB7) copula with (TauUpper, TauLower), and otherwise from the Joe-Clayton copula with (TauLower, TauUpper), flipped to 1 − u (Patton 2006). The Joe-Clayton parameters are κ = 1 / log2(2 − τU) and γ = −1 / log2(τL). nDims = 2: conditional inversion of the bivariate Joe-Clayton copula. nDims ≥ 3: exchangeable Joe-Clayton copula with generator inverse ψ(s) = 1 − (1 − (1 + s)^(−1/γ))^(1/κ), sampled with a frailty V ~ Gamma(M/γ), M ~ Sibuya(1/κ), shared by all columns of a row: U_j = ψ(E_j / V) with independent standard exponentials E_j (Marshall and Olkin 1988, Hofert 2011). ## Remarks Every pair of columns follows the bivariate symmetrized Joe-Clayton copula of apaCopula.SymJoeClayton.Cdf, with upper tail dependence TauUpper and lower tail dependence TauLower. This function is volatile, i.e. it is recalculated whenever a change occurs in the workbook, even if not related to the function’s output, and when pressing F9. # apaCopula.Clayton.Estimate(Data, \[IsUniform\], \[DoMultivariateOtherwiseBivariate\]) URL: https://www.andreassteiner.net/help/apacopula.clayton.estimate/ ## Result Estimates the parameter α of the Clayton copula (lower tail dependence) from a sample: a single value for all k columns jointly, or a k x k matrix of bivariate estimates. ## Syntax *Data*: r x k matrix of observations (k ≥ 2), e.g. returns, each column containing a variable; no missing values *IsUniform*: optional; TRUE if Data already contains uniform marginals strictly between 0 and 1, FALSE to convert each column to ranks / (r + 1) (average ranks for ties); default: FALSE *DoMultivariateOtherwiseBivariate*: optional; TRUE fits one exchangeable Clayton copula to all columns and returns a single Alpha; FALSE returns a symmetric k x k matrix with the bivariate Alpha of columns i and j off the diagonal, \#N/A on the diagonal; default: TRUE ## Algorithm Pseudo-observations: u_ij = rank(x_ij) / (r + 1) per column, unless IsUniform is TRUE. Full maximum likelihood with the k-dimensional Clayton density c(u) = Π\_{j=1}^{k−1}(1 + jα) · Π_i u_i^{−(1+α)} · (Σ_i u_i^{−α} − k + 1)^{−(k + 1/α)}. Search over log(1 + α): 61-point grid, refined by golden-section search; α in (−0.999, 200\] for 2 columns, \[0, 200\] for more columns (α = 0 is independence). ## Remarks α relates to Kendall's tau by α = 2τ / (1 − τ); the lower tail dependence is λ_L = 2^(−1/α) for α \> 0, the upper tail dependence is 0. The result can be passed directly to apaCopula.Clayton.Sim. For more than 2 columns all pairs share the same α (exchangeable copula) and negative dependence is not possible; the estimate is then 0. If DoMultivariateOtherwiseBivariate is FALSE, each pair is fitted separately and may be negative; entry (i, j) equals the result for the two columns i and j alone. Clayton (1978): "A model for association in bivariate life tables", Biometrika 65(1). # apaCopula.Clayton.Sim(nObs, Alpha, nDims) URL: https://www.andreassteiner.net/help/apacopula.clayton.sim/ ## Result Simulates uniform marginals from the Clayton copula, i.e. data with lower tail dependence: an nObs x nDims matrix with the same Alpha for all pairs of columns. ## Syntax *nObs*: number of observations to simulate *Alpha*: Clayton copula parameter α, i.e. 2 \* KendallTau / (1 - KendallTau); larger than −1 for nDims = 2, at least 0 for nDims ≥ 3; 0 gives independence; small (large) values generate small (large) lower tail dependence *nDims*: optional; number of columns (dimensions), at least 2; all pairs of columns share the same dependence parameters; default: 2 ## Algorithm nDims = 2: conditional inversion, U2 = U1·(S^(−α/(1+α)) − 1 + U1^α)^(−1/α) with independent uniforms U1 and S. nDims ≥ 3: V ~ Gamma(1/α) shared by all columns of a row, U_j = (1 + E_j / V)^(−1/α) with independent standard exponentials E_j (Marshall and Olkin 1988). ## Remarks Every pair of columns has the bivariate Clayton copula C(u, v) = (u^(−α) + v^(−α) − 1)^(−1/α), Kendall’s tau α / (α + 2) and lower tail dependence 2^(−1/α) for α \> 0. Negative α (negative dependence) is only possible with two columns. This function is volatile, i.e. it is recalculated whenever a change occurs in the workbook, even if not related to the function’s output, and when pressing F9. # apaCopula.Gaussian.Sim(nObs, p) URL: https://www.andreassteiner.net/help/apacopula.gaussian.sim/ ## Result Simulates uniformly distributed variables from the Gaussian copula: nObs x 2 for a single correlation, nObs x k for a k x k correlation matrix. ## Syntax *nObs*: number of observations to simulate *p*: single correlation (bivariate case) or k x k correlation matrix; the matrix must be symmetric with ones on the diagonal and positive semi-definite ## Algorithm Z = L·ε with independent standard normals ε and the Cholesky factor L of the correlation matrix (bivariate case: Z2 = p·Z1 + sqrt(1 − p²)·ε2); U = Φ(Z), with Φ the standard normal distribution function. ## Remarks The Gaussian copula has no tail dependence. Kendall’s tau between two columns is 2/π·arcsin(ρ). This function is volatile, i.e. it is recalculated whenever a change occurs in the workbook, even if not related to the function’s output, and when pressing F9. # apaCopula.t.Estimate.Correls(Data, \[IsUniform\], \[DoMultivariateOtherwiseBivariate\]) URL: https://www.andreassteiner.net/help/apacopula.t.estimate.correls/ ## Result Estimates the correlation matrix of the Student t copula from a sample: jointly from all k columns, or pair by pair. ## Syntax *Data*: r x k matrix of observations (k ≥ 2), e.g. returns, each column containing a variable; no missing values *IsUniform*: optional; TRUE if Data already contains uniform marginals strictly between 0 and 1, FALSE to convert each column to ranks / (r + 1) (average ranks for ties); default: FALSE *DoMultivariateOtherwiseBivariate*: optional; TRUE estimates the k x k correlation matrix jointly with ν by full maximum likelihood; FALSE returns a k x k matrix of bivariate Kendall's tau estimates, each from its column pair alone (unit diagonal); default: TRUE ## Algorithm Pseudo-observations: u_ij = rank(x_ij) / (r + 1) per column, unless IsUniform is TRUE. Multivariate (DoMultivariateOtherwiseBivariate TRUE): ρ and ν jointly maximize the t copula log-likelihood Σ_t \[log t\_{ν,ρ}(x_t) − Σ_j log t_ν(x_tj)\], x_tj = T_ν⁻¹(u_tj). Profile likelihood in ν: grid on log ν over \[1, 1000\], refined by golden-section search; for each ν, ρ is optimized by BFGS with analytic gradient over a Cholesky parameterization (rows of unit length), which keeps ρ a positive definite correlation matrix. Starting values: Kendall's tau estimate below. Bivariate (FALSE): ρ_ij = sin(π/2 · τ_ij), with τ_ij Kendall's tau (tau-b) of columns i and j. ## Remarks The multivariate correlations and apaCopula.t.Estimate.DoF come from the same joint fit, so they belong together. The output can be passed directly to apaCopula.t.Sim. The bivariate correlations depend only on Kendall's tau and do not require ν; they are the same for the Gaussian and the t copula. The k x k matrix is not corrected and may not be positive definite. The multivariate correlations differ slightly from the bivariate ones, because they adjust to ν and to the joint data. Demarta/McNeil (2005): "The t Copula and Related Copulas", International Statistical Review 73(1). # apaCopula.t.Estimate.DoF(Data, \[IsUniform\], \[DoMultivariateOtherwiseBivariate\]) URL: https://www.andreassteiner.net/help/apacopula.t.estimate.dof/ ## Result Estimates the degrees of freedom ν of the Student t copula from a sample: a single value for all k columns jointly, or a k x k matrix of bivariate estimates. ## Syntax *Data*: r x k matrix of observations (k ≥ 2), e.g. returns, each column containing a variable; no missing values *IsUniform*: optional; TRUE if Data already contains uniform marginals strictly between 0 and 1, FALSE to convert each column to ranks / (r + 1) (average ranks for ties); default: FALSE *DoMultivariateOtherwiseBivariate*: optional; TRUE estimates one ν from all columns; FALSE returns a k x k matrix with the bivariate ν of columns i and j in the lower triangle (row i \> column j), \#N/A on and above the diagonal; default: TRUE ## Algorithm Pseudo-observations: u_ij = rank(x_ij) / (r + 1) per column, unless IsUniform is TRUE. Multivariate (DoMultivariateOtherwiseBivariate TRUE): ρ and ν jointly maximize the t copula log-likelihood Σ_t \[log t\_{ν,ρ}(x_t) − Σ_j log t_ν(x_tj)\], x_tj = T_ν⁻¹(u_tj). Profile likelihood in ν: grid on log ν over \[1, 1000\], refined by golden-section search; for each ν, ρ is optimized by BFGS with analytic gradient over a Cholesky parameterization (rows of unit length), which keeps ρ a positive definite correlation matrix. Starting values: Kendall's tau estimate below. Bivariate (FALSE): for each pair, ρ_ij = sin(π/2 · τ_ij) with τ_ij Kendall's tau (tau-b), then ν maximizes the bivariate t copula log-likelihood with ρ_ij fixed (same grid and golden-section search). ## Remarks A result of 1000 (upper bound) indicates no evidence of tail dependence, i.e. the Gaussian copula is adequate; small values indicate strong joint tail dependence. The multivariate ν is one value shared by all pairs and need not equal the average of the bivariate values. Because the bivariate fit uses Kendall's tau correlations while the multivariate fit estimates ρ jointly, the bivariate ν of two columns can differ slightly from the multivariate ν of the same two columns. Demarta/McNeil (2005): "The t Copula and Related Copulas", International Statistical Review 73(1). # apaCopula.t.Sim(nObs, p, Df) URL: https://www.andreassteiner.net/help/apacopula.t.sim/ ## Result Simulates uniformly distributed variables from the Student t copula: nObs x 2 for a single correlation, nObs x k for a k x k correlation matrix. ## Syntax *nObs*: number of observations to simulate *p*: single correlation (bivariate case) or k x k correlation matrix; the matrix must be symmetric with ones on the diagonal and positive semi-definite *Df*: degrees of freedom ν; positive, need not be a whole number ## Algorithm Z = L·ε as in apaCopula.Gaussian.Sim; W ~ chi-square(ν), drawn once per observation and shared by all columns; X = Z / sqrt(W/ν); U = T_ν(X), with T_ν the Student t distribution function. ## Remarks Unlike the Gaussian copula, the t copula has symmetric lower and upper tail dependence λ = 2·T\_{ν+1}(−sqrt((ν+1)(1 − ρ)/(1 + ρ))), which increases as ν decreases; for large ν it approaches the Gaussian copula. Kendall’s tau is 2/π·arcsin(ρ), as for the Gaussian copula. To obtain returns, transform the columns with the inverse distribution functions of the desired marginals. This function is volatile, i.e. it is recalculated whenever a change occurs in the workbook, even if not related to the function’s output, and when pressing F9. # apaCorrelationSurprise(Returns) URL: https://www.andreassteiner.net/help/apacorrelationsurprise/ ## Result Calculates the correlation surprise (Kinlaw/Turkington), i.e. turbulence divided by magnitude surprise, for each observation. ## Syntax *Returns*: nObs x nAssets matrix of returns, each column containing a time series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image40.svg) ## Remarks Kinlaw/Turkington(2013): “Correlation Surprise”, Journal of Asset Management: “A correlation surprise ratio greater than one is associated with correlation breakdowns (that is, previously correlated assets diverging and/or previously negatively correlated assets converging). A correlation surprise ratio less than one is associated with relatively typical correlation outcomes. In other words, days characterized by low correlation surprise are actually less unusual than the magnitudes of the individual returns alone would suggest.” Uses population covariances (denominator n). # apaCorrel.ConfidenceIntervals(X, Y, ConfidenceLevel, nSamples) URL: https://www.andreassteiner.net/help/apacorrel.confidenceintervals/ ## Result Calculates a two-sided confidence interval for the Pearson correlation coefficient of two series by resampling. ## Syntax *X*: r x 1 data vector containing a first time series *Y*: r x 1 data vector containing a second time series *ConfidenceLevel*: confidence level strictly between 0 and 1, e.g. 0.95 *nSamples*: number of resampled datasets ## Remarks The output is a 2 x 1 vector: the lower bound in the first row and the upper bound in the second row. Observation pairs (X(t), Y(t)) are drawn with replacement to form nSamples datasets of r observations. The bounds are the (1 − ConfidenceLevel)/2 and (1 + ConfidenceLevel)/2 percentiles of the resampled correlations. Resampled datasets in which one series is constant are skipped. The Pearson correlation is the same with sample (denominator n − 1) and population (denominator n) moments, as the denominators cancel. X and Y must have the same number of observations (at least 3). The function is volatile and the results change with each recalculation. # apaCorrel.Conditional.Box.In.Data(X, Y, FromQuantile, ToQuantile) URL: https://www.andreassteiner.net/help/apacorrel.conditional.box.in.data/ ## Result Returns the observations where X is inside a box defined by a lower and an upper quantile. ## Syntax *X: data vector (row or column) containing a time series* *Y: data vector (row or column) containing a time series, same length as X* *FromQuantile: lower quantile of the box as a fraction between 0 and 1 (e.g. 0.25)* *ToQuantile: upper quantile of the box as a fraction between 0 and 1 (e.g. 0.75), larger than FromQuantile* ## Remarks Observations are selected by X only. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is inside the box if FromQuantile x n \< rank \<= ToQuantile x n, and outside otherwise; FromQuantile must be smaller than ToQuantile and both must lie between 0 and 1. Returns an n x 2 matrix with X in the first and Y in the second column, in the original order; rows that are not selected return \#N/A, so the output can be charted directly. X and Y may be row or column vectors and must have the same length n. The selection is identical to the one used by the corresponding apaCorrels.Conditional function. # apaCorrel.Conditional.Box.In.Joint.Data(X, Y, FromQuantile, ToQuantile) URL: https://www.andreassteiner.net/help/apacorrel.conditional.box.in.joint.data/ ## Result Returns the observations where both X and Y are inside a box defined by a lower and an upper quantile. ## Syntax *X: data vector (row or column) containing a time series* *Y: data vector (row or column) containing a time series, same length as X* *FromQuantile: lower quantile of the box as a fraction between 0 and 1 (e.g. 0.25)* *ToQuantile: upper quantile of the box as a fraction between 0 and 1 (e.g. 0.75), larger than FromQuantile* ## Remarks An observation is selected only if both X and Y are inside the box. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is inside the box if FromQuantile x n \< rank \<= ToQuantile x n, and outside otherwise; FromQuantile must be smaller than ToQuantile and both must lie between 0 and 1. Returns an n x 2 matrix with X in the first and Y in the second column, in the original order; rows that are not selected return \#N/A, so the output can be charted directly. X and Y may be row or column vectors and must have the same length n. The selection is identical to the one used by the corresponding apaCorrels.Conditional function. # apaCorrel.Conditional.Box.Out.Data(X, Y, FromQuantile, ToQuantile) URL: https://www.andreassteiner.net/help/apacorrel.conditional.box.out.data/ ## Result Returns the observations where X is outside a box defined by a lower and an upper quantile. ## Syntax *X: data vector (row or column) containing a time series* *Y: data vector (row or column) containing a time series, same length as X* *FromQuantile: lower quantile of the box as a fraction between 0 and 1 (e.g. 0.25)* *ToQuantile: upper quantile of the box as a fraction between 0 and 1 (e.g. 0.75), larger than FromQuantile* ## Remarks Observations are selected by X only. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is inside the box if FromQuantile x n \< rank \<= ToQuantile x n, and outside otherwise; FromQuantile must be smaller than ToQuantile and both must lie between 0 and 1. Returns an n x 2 matrix with X in the first and Y in the second column, in the original order; rows that are not selected return \#N/A, so the output can be charted directly. X and Y may be row or column vectors and must have the same length n. The selection is identical to the one used by the corresponding apaCorrels.Conditional function. # apaCorrel.Conditional.Box.Out.Joint.Data(X, Y, FromQuantile, ToQuantile) URL: https://www.andreassteiner.net/help/apacorrel.conditional.box.out.joint.data/ ## Result Returns the observations where at least one of X and Y is outside a box defined by a lower and an upper quantile. ## Syntax *X: data vector (row or column) containing a time series* *Y: data vector (row or column) containing a time series, same length as X* *FromQuantile: lower quantile of the box as a fraction between 0 and 1 (e.g. 0.25)* *ToQuantile: upper quantile of the box as a fraction between 0 and 1 (e.g. 0.75), larger than FromQuantile* ## Remarks An observation is selected if at least one of X and Y is outside the box. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is inside the box if FromQuantile x n \< rank \<= ToQuantile x n, and outside otherwise; FromQuantile must be smaller than ToQuantile and both must lie between 0 and 1. Returns an n x 2 matrix with X in the first and Y in the second column, in the original order; rows that are not selected return \#N/A, so the output can be charted directly. X and Y may be row or column vectors and must have the same length n. The selection is identical to the one used by the corresponding apaCorrels.Conditional function. # apaCorrel.Conditional.Quantile.Lower.Data(X, Y, Quantile) URL: https://www.andreassteiner.net/help/apacorrel.conditional.quantile.lower.data/ ## Result Returns the observations where X is at or below the quantile. ## Syntax *X: data vector (row or column) containing a time series* *Y: data vector (row or column) containing a time series, same length as X* *Quantile: quantile as a fraction between 0 and 1 (e.g. 0.1 for 10%)* ## Remarks Observations are selected by X only. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is at or below the quantile if its rank is at most Quantile x n, and above otherwise. Returns an n x 2 matrix with X in the first and Y in the second column, in the original order; rows that are not selected return \#N/A, so the output can be charted directly. X and Y may be row or column vectors and must have the same length n. The selection is identical to the one used by the corresponding apaCorrels.Conditional function. # apaCorrel.Conditional.Quantile.Joint.Lower.Data(X, Y, Quantile) URL: https://www.andreassteiner.net/help/apacorrel.conditional.quantile.joint.lower.data/ ## Result Returns the observations where both X and Y are at or below the quantile. ## Syntax *X: data vector (row or column) containing a time series* *Y: data vector (row or column) containing a time series, same length as X* *Quantile: quantile as a fraction between 0 and 1 (e.g. 0.1 for 10%)* ## Remarks An observation is selected only if both X and Y are at or below the quantile. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is at or below the quantile if its rank is at most Quantile x n, and above otherwise. Returns an n x 2 matrix with X in the first and Y in the second column, in the original order; rows that are not selected return \#N/A, so the output can be charted directly. X and Y may be row or column vectors and must have the same length n. The selection is identical to the one used by the corresponding apaCorrels.Conditional function. # apaCorrel.Conditional.Quantile.Upper.Data(X, Y, Quantile) URL: https://www.andreassteiner.net/help/apacorrel.conditional.quantile.upper.data/ ## Result Returns the observations where X is above the quantile. ## Syntax *X: data vector (row or column) containing a time series* *Y: data vector (row or column) containing a time series, same length as X* *Quantile: quantile as a fraction between 0 and 1 (e.g. 0.1 for 10%)* ## Remarks Observations are selected by X only. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is at or below the quantile if its rank is at most Quantile x n, and above otherwise. Returns an n x 2 matrix with X in the first and Y in the second column, in the original order; rows that are not selected return \#N/A, so the output can be charted directly. X and Y may be row or column vectors and must have the same length n. The selection is identical to the one used by the corresponding apaCorrels.Conditional function. # apaCorrel.Conditional.Quantile.Joint.Upper.Data(X, Y, Quantile) URL: https://www.andreassteiner.net/help/apacorrel.conditional.quantile.joint.upper.data/ ## Result Returns the observations where both X and Y are above the quantile. ## Syntax *X: data vector (row or column) containing a time series* *Y: data vector (row or column) containing a time series, same length as X* *Quantile: quantile as a fraction between 0 and 1 (e.g. 0.1 for 10%)* ## Remarks An observation is selected only if both X and Y are above the quantile. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is at or below the quantile if its rank is at most Quantile x n, and above otherwise. Returns an n x 2 matrix with X in the first and Y in the second column, in the original order; rows that are not selected return \#N/A, so the output can be charted directly. X and Y may be row or column vectors and must have the same length n. The selection is identical to the one used by the corresponding apaCorrels.Conditional function. # apaCorrel.Exceedance(X, Y, Quantile) URL: https://www.andreassteiner.net/help/apacorrel.exceedance/ ## Result Calculates the exceedance correlation of two series, i.e. the correlation of the observations where both series are below (Quantile \<= 0.5) or above (Quantile \> 0.5) the quantile. ## Syntax *X*: r x 1 vector of returns *Y*: r x 1 vector of returns *Quantile*: quantile threshold, e.g. 0.1 for the lower and 0.9 for the upper tail. ## Remarks The exceedances are selected based on quantiles, but the correlations are calculated with the original X and Y data. # apaCorrel.ExpWeighted(TimeSeries1, TimeSeries2, HalfLife) URL: https://www.andreassteiner.net/help/apacorrel.expweighted/ ## Result Returns the exponentially weighted correlation coefficient between two time series. ## Syntax *TimeSeries1*: vector with time series data *TimeSeries2*: vector with time series data *HalfLife*: half-life of the exponential weighting scheme # apaCorrel.Gerber(TimeSeries1, TimeSeries2, c) URL: https://www.andreassteiner.net/help/apacorrel.gerber/ ## Result Calculates the Gerber statistic, a robust co-movement measure between two time series. ## Syntax *TimeSeries1*: r x 1 vector containing the first time series *TimeSeries2*: r x 1 vector containing the second time series *c*: number of standard deviations around the mean within which observations are excluded ## Remarks The thresholds use the sample standard deviation (denominator n − 1). # apaCorrel.Gerber.Altered(TimeSeries1, TimeSeries2, c) URL: https://www.andreassteiner.net/help/apacorrel.gerber.altered/ ## Result Calculates the altered Gerber statistic between two time series. ## Syntax *TimeSeries1*: r x 1 vector containing the first time series *TimeSeries2*: r x 1 vector containing the second time series *c*: number of standard deviations around the mean within which observations are excluded ## Remarks The thresholds use the sample standard deviation (denominator n − 1). # apaCorrel.Gerber.Modified(TimeSeries1, TimeSeries2, c) URL: https://www.andreassteiner.net/help/apacorrel.gerber.modified/ ## Result Calculates the modified Gerber statistic between two time series. ## Syntax *TimeSeries1*: r x 1 vector containing the first time series *TimeSeries2*: r x 1 vector containing the second time series *c*: number of standard deviations around the mean within which observations are excluded ## Remarks The thresholds use the sample standard deviation (denominator n − 1). # apaCorrel.Implied(PortfolioVolatility, AssetWeights, AssetVolatilities) URL: https://www.andreassteiner.net/help/apacorrel.implied/ ## Result Calculates the average (constant) correlation implied by a portfolio volatility, constituent weights and constituent volatilities. ## Syntax *PortfolioVolatility*: portfolio volatility, e.g. 15.53% *AssetWeights*: 1 x n vector of constituent weights *AssetVolatilities*: 1 x n vector of constituent volatilities ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image41.svg) # apaCorrel.Kendall(X, Y) URL: https://www.andreassteiner.net/help/apacorrel.kendall/ ## Result Calculates Kendall’s tau-b for two data vectors *X* and *Y*. ## Syntax *X*: r x 1 data vector *Y*: r x 1 data vector ## Remarks Ties are accounted for (tau-b): τb = (nc − nd) / √((n0 − n1)·(n0 − n2)), where nc and nd are the numbers of concordant and discordant pairs, n0 = n(n − 1)/2, and n1 and n2 are the numbers of tied pairs in X and Y. # apaCorrel.Spearman(Returns1, Returns2) URL: https://www.andreassteiner.net/help/apacorrel.spearman/ ## Result Calculates Spearman’s rank correlation coefficient. ## Syntax *Returns1*: r x 1 vector of returns *Returns2*: r x 1 vector of returns ## Remarks The coefficient is the Pearson correlation of the ranks. Tied observations receive their average rank. # apaCorrels(TimeSeries) URL: https://www.andreassteiner.net/help/apacorrels/ ## Result Returns the correlation matrix of a matrix of time series. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series ## Remarks The time series matrix is a matrix of returns, in which each column represents a series and each row an observation. # apaCorrels.Add.LinComb(Correls, ElementIndices, Weights) URL: https://www.andreassteiner.net/help/apacorrels.add.lincomb/ ## Result Aggregates selected elements of a correlation matrix into a weighted linear combination. The linear combination is added to the correlation matrix and the selected elements are deleted. ## Syntax *Correls*: n x n correlation matrix *ElementIndices*: 1 x k vector containing the indices of the elements to combine *Weights*: 1 x k vector containing the element weights ## Remarks Useful for simplifying a correlation matrix. # apaCorrels.Add.Portfolios(Correls, Weights) URL: https://www.andreassteiner.net/help/apacorrels.add.portfolios/ ## Result Adds portfolios defined by a weight matrix as elements to a correlation matrix. ## Syntax *Correls*: n x n correlation matrix *Weights*: m x n matrix of weights, the m rows representing portfolios # apaCorrels.Analyze(Correls) URL: https://www.andreassteiner.net/help/apacorrels.analyze/ ## Result Returns a text string containing information about the validity of a correlation matrix: valid, invalid or problematic. ## Syntax *Correls*: correlation matrix ## Algorithm Six criteria are analyzed: 1. Is the matrix square? 2. Are all entries of the matrix between -1 and 1? 3. Are all entries on the main diagonal equal to 1? 4. Is the matrix symmetric, i.e. are all entries above the main diagonal equal to the entries below? 5. Is the matrix positive semi-definite? 6. Is the matrix near-singular? ## Remarks A hard criterion whether a matrix is singular or not does not exist. Singularity is considered an issue if the matrix determinant is smaller than 0.0001. Absolute numbers smaller than 1e-12 are considered zero, absolute numbers between 1e-12 and 1e-6 are considered near-zero. # apaCorrels.Average(Correls) URL: https://www.andreassteiner.net/help/apacorrels.average/ ## Result Returns the equicorrelation matrix containing the average correlation. ## Syntax *Correls*: n x n correlation matrix ## Algorithm The average correlation is calculated as the arithmetic average of the entries in the upper (or lower) triangular part of the correlation matrix. # apaCorrels.Average.Correl(Correls) URL: https://www.andreassteiner.net/help/apacorrels.average.correl/ ## Result Returns the average correlation coefficient. ## Syntax *Correls*: n x n correlation matrix ## Algorithm The average correlation is calculated as the arithmetic average of the entries in the upper (or lower) triangular part of the correlation matrix. # apaCorrels.Average.Resample.Stats(DataMatrix, nSamples, SampleSize) URL: https://www.andreassteiner.net/help/apacorrels.average.resample.stats/ ## Result Resamples a correlation matrix and reports statistics for the average correlation coefficient: 1) mean absolute deviation (from empirical correlations), 2) mean squared deviation, 3) mean maximum deviation above, 4) mean maximum deviation below. ## Syntax *DataMatrix*: r x c data matrix *nSamples*: number of samples to generate *SampleSize*: size of each sample generated # apaCorrels.Averages(Correls, IsSignedOtherwiseAbs) URL: https://www.andreassteiner.net/help/apacorrels.averages/ ## Result Calculates the average correlation of each element (i.e. asset) with all other elements. ## Syntax *Correls*: n x n correlation matrix *IsSignedOtherwiseAbs*: TRUE if the signs are preserved (negative correlations reduce the average), FALSE if absolute values are used # apaCorrels.Block(Correls, BlockStructure) URL: https://www.andreassteiner.net/help/apacorrels.block/ ## Result Creates a block correlation matrix from a correlation matrix and a block structure. ## Syntax *Correls*: n x n correlation matrix *BlockStructure*: 1 x k vector containing the number of elements per block # apaCorrels.Block.Combine(FirstBlock, SecondBlock, InterCorrel, DegreeRandom) URL: https://www.andreassteiner.net/help/apacorrels.block.combine/ ## Result Builds a correlation matrix from two correlation matrices and an inter-block correlation coefficient. The inter-block correlations are randomized if the resulting correlation matrix is valid. ## Syntax *FirstBlock*: first block of correlations *SecondBlock*: second block of correlations *InterCorrel*: inter-block correlation coefficient *DegreeRandom*: degree of randomization of the inter-block correlations, between 0% and 100%. Randomization only takes place when the starting correlation matrix is valid; otherwise, an invalid and non-randomized correlation matrix is returned # apaCorrels.Block.Averages(Correls, BlockStructure, DoShowIntraCorrelsOtherwiseOnes) URL: https://www.andreassteiner.net/help/apacorrels.block.averages/ ## Result Calculates the block averages from a correlation matrix and a block structure. ## Syntax *Correls*: n x n correlation matrix *BlockStructure*: 1 x k vector containing the number of elements per block *DoShowIntraCorrelsOtherwiseOnes*: TRUE to show the intra-block correlations on the main diagonal, FALSE to show ones # apaCorrels.Block.Build(BlockEquiCorrels, BlockStructure) URL: https://www.andreassteiner.net/help/apacorrels.block.build/ ## Result Builds an equicorrelation block correlation matrix from block correlation values and a block structure. ## Syntax *BlockEquiCorrels*: k x k matrix of equicorrelation coefficients within the blocks (main diagonal) and between the blocks (off-diagonal) *BlockStructure*: 1 x k vector containing the number of elements per block ## Remarks - The result is not necessarily a valid correlation matrix. # apaCorrels.Block.Bounds(BlockCorrels) URL: https://www.andreassteiner.net/help/apacorrels.block.bounds/ ## Result Finds the lower and upper bounds within which the inter- and intra-block correlations can be varied. The lower bounds for the inter-block correlations are located in the lower triangular part, the upper bounds in the upper triangular part. The lower bounds for the intra-block correlations are located on the main diagonal. ## Syntax *BlockCorrels*: block correlation matrix ## Remarks The precision of the result is limited to whole percentages. The upper bounds for the intra-block correlations are always one, hence not reported. # apaCorrels.Block.Maxima(Correls, BlockStructure) URL: https://www.andreassteiner.net/help/apacorrels.block.maxima/ ## Result Returns the maximum correlations per block, given a correlation matrix and a block structure. ## Syntax *Correls*: n x n correlation matrix *BlockStructure*: 1 x k vector containing the number of elements per block # apaCorrels.Block.Minima(Correls, BlockStructure) URL: https://www.andreassteiner.net/help/apacorrels.block.minima/ ## Result Returns the minimum correlations per block, given a correlation matrix and a block structure. ## Syntax *Correls*: n x n correlation matrix *BlockStructure*: 1 x k vector containing the number of elements per block # apaCorrels.Block.Replace(Correls, NewFirstBlock) URL: https://www.andreassteiner.net/help/apacorrels.block.replace/ ## Result Replaces the first block in a correlation matrix and adjusts the correlations with the remaining elements. ## Syntax *Correls*: correlation matrix *NewFirstBlock*: m x m correlation matrix which becomes the new first block ## Remarks - The first m rows of the Cholesky decomposition are replaced. # apaCorrels.Block.Set(Correls, BlockStructure, BlockIndex, IntraEquiCorrel, InterEquiCorrel, IntraShrinkage, InterShrinkage) URL: https://www.andreassteiner.net/help/apacorrels.block.set/ ## Result Sets (shrinks) the correlations within one block of a correlation matrix and its correlations with the other elements towards target values. ## Syntax *Correls*: n x n correlation matrix *BlockStructure*: 1 x k vector containing the number of elements per block *BlockIndex*: index of the block to be set *IntraEquiCorrel*: target equicorrelation coefficient within the block, between -1 and 1. If set to 2, the average intra-block correlation is targeted. If set to 3, the smallest correlation of a valid equicorrelation matrix, -1/(N-1), is targeted *InterEquiCorrel*: target equicorrelation coefficient of the block with the other elements, between -1 and 1. If set to 2, the average inter-block correlation is targeted *IntraShrinkage*: intra-block shrinkage parameter between 0 and 1 *InterShrinkage*: inter-block shrinkage parameter between 0 and 1 ## Remarks - The result is not necessarily a valid correlation matrix. # apaCorrels.Block.Structure(BlockCorrels) URL: https://www.andreassteiner.net/help/apacorrels.block.structure/ ## Result Derives the block structure from a block correlation matrix. ## Syntax *BlockCorrels*: block correlation matrix # apaCorrels.Bounds(Correls) URL: https://www.andreassteiner.net/help/apacorrels.bounds/ ## Result Returns the lower and upper bounds within which each entry of a valid correlation matrix can be varied without changing the other entries. ## Syntax *Correls*: n x n correlation matrix ## Algorithm This is a proprietary algorithm. See our research note of June 2011 for more details. # apaCorrels.Conditional.Box(TimeSeries, FromQuantile, ToQuantile, IsCorrelsOtherwiseNObs) URL: https://www.andreassteiner.net/help/apacorrels.conditional.box/ ## Result Calculates conditional correlations inside and outside a box defined by a lower and an upper quantile. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *FromQuantile: lower quantile of the box as a fraction between 0 and 1 (e.g. 0.25)* *ToQuantile: upper quantile of the box as a fraction between 0 and 1 (e.g. 0.75), larger than FromQuantile* *IsCorrelsOtherwiseNObs: TRUE to return the correlations, FALSE to return the number of observations used in their calculation (diagonal: full number of observations r)* ## Remarks The upper triangle (i \< j) holds the outside-the-box correlations and the lower triangle (j, i) the inside-the-box correlations of the same pair, both conditioning on the asset with the lower column index i. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is inside the box if FromQuantile x r \< rank \<= ToQuantile x r, and outside otherwise; FromQuantile must be smaller than ToQuantile and both must lie between 0 and 1. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series); if IsCorrelsOtherwiseNObs is FALSE, the diagonal is the full number of observations r. # apaCorrels.Conditional.Box.In(TimeSeries, FromQuantile, ToQuantile) URL: https://www.andreassteiner.net/help/apacorrels.conditional.box.in/ ## Result Calculates the conditional correlation matrix for observations where the row asset is inside a box defined by a lower and an upper quantile. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *FromQuantile: lower quantile of the box as a fraction between 0 and 1 (e.g. 0.25)* *ToQuantile: upper quantile of the box as a fraction between 0 and 1 (e.g. 0.75), larger than FromQuantile* ## Remarks Element (i, j) is computed on the observations selected by the row asset i, so the matrix is not symmetric: element (j, i) conditions on asset j. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is inside the box if FromQuantile x r \< rank \<= ToQuantile x r, and outside otherwise; FromQuantile must be smaller than ToQuantile and both must lie between 0 and 1. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series). # apaCorrels.Conditional.Box.In.Joint(TimeSeries, FromQuantile, ToQuantile) URL: https://www.andreassteiner.net/help/apacorrels.conditional.box.in.joint/ ## Result Calculates joint conditional correlations inside a box defined by a lower and an upper quantile. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *FromQuantile: lower quantile of the box as a fraction between 0 and 1 (e.g. 0.25)* *ToQuantile: upper quantile of the box as a fraction between 0 and 1 (e.g. 0.75), larger than FromQuantile* ## Remarks An observation is used for the pair (i, j) only if it is selected for both assets; the matrix is symmetric. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is inside the box if FromQuantile x r \< rank \<= ToQuantile x r, and outside otherwise; FromQuantile must be smaller than ToQuantile and both must lie between 0 and 1. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series). # apaCorrels.Conditional.Box.Joint(TimeSeries, FromQuantile, ToQuantile, IsCorrelsOtherwiseNObs) URL: https://www.andreassteiner.net/help/apacorrels.conditional.box.joint/ ## Result Calculates joint conditional correlations inside and outside a box defined by a lower and an upper quantile. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *FromQuantile: lower quantile of the box as a fraction between 0 and 1 (e.g. 0.25)* *ToQuantile: upper quantile of the box as a fraction between 0 and 1 (e.g. 0.75), larger than FromQuantile* *IsCorrelsOtherwiseNObs: TRUE to return the correlations, FALSE to return the number of observations used in their calculation (diagonal: full number of observations r)* ## Remarks The upper triangle (i \< j) holds the correlations on observations where at least one of the two assets is outside the box, and the lower triangle (j, i) those where both are inside. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is inside the box if FromQuantile x r \< rank \<= ToQuantile x r, and outside otherwise; FromQuantile must be smaller than ToQuantile and both must lie between 0 and 1. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series); if IsCorrelsOtherwiseNObs is FALSE, the diagonal is the full number of observations r. # apaCorrels.Conditional.Box.Out(TimeSeries, FromQuantile, ToQuantile) URL: https://www.andreassteiner.net/help/apacorrels.conditional.box.out/ ## Result Calculates the conditional correlation matrix for observations where the row asset is outside a box defined by a lower and an upper quantile. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *FromQuantile: lower quantile of the box as a fraction between 0 and 1 (e.g. 0.25)* *ToQuantile: upper quantile of the box as a fraction between 0 and 1 (e.g. 0.75), larger than FromQuantile* ## Remarks Element (i, j) is computed on the observations selected by the row asset i, so the matrix is not symmetric: element (j, i) conditions on asset j. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is inside the box if FromQuantile x r \< rank \<= ToQuantile x r, and outside otherwise; FromQuantile must be smaller than ToQuantile and both must lie between 0 and 1. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series). # apaCorrels.Conditional.Box.Out.Joint(TimeSeries, FromQuantile, ToQuantile) URL: https://www.andreassteiner.net/help/apacorrels.conditional.box.out.joint/ ## Result Calculates the joint conditional correlation matrix for observations where at least one of the two assets is outside a box defined by a lower and an upper quantile. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *FromQuantile: lower quantile of the box as a fraction between 0 and 1 (e.g. 0.25)* *ToQuantile: upper quantile of the box as a fraction between 0 and 1 (e.g. 0.75), larger than FromQuantile* ## Remarks An observation is used for the pair (i, j) if at least one of the two assets is outside the box; the matrix is symmetric. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is inside the box if FromQuantile x r \< rank \<= ToQuantile x r, and outside otherwise; FromQuantile must be smaller than ToQuantile and both must lie between 0 and 1. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series). # apaCorrels.Conditional.Mean(TimeSeries, IsCorrelsOtherwiseNObs) URL: https://www.andreassteiner.net/help/apacorrels.conditional.mean/ ## Result Calculates the conditional correlation matrix for observations at or below the arithmetic mean (lower triangular part) and above the arithmetic mean (upper triangular part), conditioning on the asset with the lower column index. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *IsCorrelsOtherwiseNObs: TRUE to return the correlations, FALSE to return the number of observations used in their calculation (diagonal: full number of observations r)* ## Remarks The upper triangle (i \< j) holds the upper-tail correlations and the lower triangle (j, i) the lower-tail correlations of the same pair, both conditioning on the asset with the lower column index i. The mean is the arithmetic mean of the full sample of each series; an observation is below if it is at or below the mean and above if it is strictly above. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series); if IsCorrelsOtherwiseNObs is FALSE, the diagonal is the full number of observations r. # apaCorrels.Conditional.Mean.Joint(TimeSeries, IsCorrelsOtherwiseNObs) URL: https://www.andreassteiner.net/help/apacorrels.conditional.mean.joint/ ## Result Calculates the joint conditional correlation matrix for observations below the arithmetic mean (lower triangular part) and above the arithmetic mean (upper triangular part). ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *IsCorrelsOtherwiseNObs: TRUE to return the correlations, FALSE to return the number of observations used in their calculation (diagonal: full number of observations r)* ## Remarks The upper triangle (i \< j) holds the correlations on observations where both assets are above their means, and the lower triangle (j, i) those where both are at or below. The mean is the arithmetic mean of the full sample of each series; an observation is below if it is at or below the mean and above if it is strictly above. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series); if IsCorrelsOtherwiseNObs is FALSE, the diagonal is the full number of observations r. # apaCorrels.Conditional.Mean.Joint.Lower(TimeSeries) URL: https://www.andreassteiner.net/help/apacorrels.conditional.mean.joint.lower/ ## Result Calculates the joint conditional correlation matrix for observations where both assets are at or below their arithmetic means. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series ## Remarks An observation is used for the pair (i, j) only if it is selected for both assets; the matrix is symmetric. The mean is the arithmetic mean of the full sample of each series; an observation is below if it is at or below the mean and above if it is strictly above. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series). # apaCorrels.Conditional.Mean.Lower(TimeSeries) URL: https://www.andreassteiner.net/help/apacorrels.conditional.mean.lower/ ## Result Calculates the conditional correlation matrix for observations where the row asset is at or below its arithmetic mean. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series ## Remarks Element (i, j) is computed on the observations selected by the row asset i, so the matrix is not symmetric: element (j, i) conditions on asset j. The mean is the arithmetic mean of the full sample of each series; an observation is below if it is at or below the mean and above if it is strictly above. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series). # apaCorrels.Conditional.Quantile(TimeSeries, Quantile, IsCorrelsOtherwiseNObs) URL: https://www.andreassteiner.net/help/apacorrels.conditional.quantile/ ## Result Calculates conditional correlations below and above a quantile. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *Quantile: quantile as a fraction between 0 and 1 (e.g. 0.1 for 10%)* *IsCorrelsOtherwiseNObs: TRUE to return the correlations, FALSE to return the number of observations used in their calculation (diagonal: full number of observations r)* ## Remarks The upper triangle (i \< j) holds the upper-tail correlations and the lower triangle (j, i) the lower-tail correlations of the same pair, both conditioning on the asset with the lower column index i. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is at or below the quantile if its rank is at most Quantile x r, and above otherwise, so Quantile = 0.1 selects exactly 10% of the observations when there are no ties. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series); if IsCorrelsOtherwiseNObs is FALSE, the diagonal is the full number of observations r. # apaCorrels.Conditional.Quantile.Joint(TimeSeries, Quantile, IsCorrelsOtherwiseNObs) URL: https://www.andreassteiner.net/help/apacorrels.conditional.quantile.joint/ ## Result Calculates joint conditional correlations below and above a quantile. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *Quantile: quantile as a fraction between 0 and 1 (e.g. 0.1 for 10%)* *IsCorrelsOtherwiseNObs: TRUE to return the correlations, FALSE to return the number of observations used in their calculation (diagonal: full number of observations r)* ## Remarks The upper triangle (i \< j) holds the correlations on observations where both assets are above the quantile, and the lower triangle (j, i) those where both are at or below. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is at or below the quantile if its rank is at most Quantile x r, and above otherwise, so Quantile = 0.1 selects exactly 10% of the observations when there are no ties. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series); if IsCorrelsOtherwiseNObs is FALSE, the diagonal is the full number of observations r. # apaCorrels.Conditional.Quantile.Joint.Lower(TimeSeries, Quantile) URL: https://www.andreassteiner.net/help/apacorrels.conditional.quantile.joint.lower/ ## Result Calculates the joint conditional correlation matrix for observations where both assets are at or below the quantile. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *Quantile: quantile as a fraction between 0 and 1 (e.g. 0.1 for 10%)* ## Remarks An observation is used for the pair (i, j) only if it is selected for both assets; the matrix is symmetric. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is at or below the quantile if its rank is at most Quantile x r, and above otherwise, so Quantile = 0.1 selects exactly 10% of the observations when there are no ties. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series). # apaCorrels.Conditional.Quantile.Lower(TimeSeries, Quantile) URL: https://www.andreassteiner.net/help/apacorrels.conditional.quantile.lower/ ## Result Calculates the conditional correlation matrix for observations where the row asset is at or below the quantile. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *Quantile: quantile as a fraction between 0 and 1 (e.g. 0.1 for 10%)* ## Remarks Element (i, j) is computed on the observations selected by the row asset i, so the matrix is not symmetric: element (j, i) conditions on asset j. Observations are ranked per series (rank 1 = lowest, tied values receive their average rank). An observation is at or below the quantile if its rank is at most Quantile x r, and above otherwise, so Quantile = 0.1 selects exactly 10% of the observations when there are no ties. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series). # apaCorrels.Conditional.Sigma(TimeSeries, nSigma, IsCorrelsOtherwiseNObs) URL: https://www.andreassteiner.net/help/apacorrels.conditional.sigma/ ## Result Calculates the conditional correlation matrix for observations below the arithmetic mean minus and above the arithmetic mean plus a number of standard deviations. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *nSigma: number of sample standard deviations defining the thresholds below (mean minus) and above (mean plus) the mean* *IsCorrelsOtherwiseNObs: TRUE to return the correlations, FALSE to return the number of observations used in their calculation (diagonal: full number of observations r)* ## Remarks The upper triangle (i \< j) holds the upper-tail correlations and the lower triangle (j, i) the lower-tail correlations of the same pair, both conditioning on the asset with the lower column index i. The thresholds are the arithmetic mean minus and plus nSigma times the sample standard deviation (denominator n - 1) of the full sample of each series; an observation is selected below if it is at or below the lower threshold and above if it is strictly above the upper threshold. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series); if IsCorrelsOtherwiseNObs is FALSE, the diagonal is the full number of observations r. # apaCorrels.Conditional.Sigma.Joint(TimeSeries, nSigma, IsCorrelsOtherwiseNObs) URL: https://www.andreassteiner.net/help/apacorrels.conditional.sigma.joint/ ## Result Calculates the joint conditional correlation matrix for observations below the arithmetic mean minus and above the arithmetic mean plus a number of standard deviations. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *nSigma: number of sample standard deviations defining the thresholds below (mean minus) and above (mean plus) the mean* *IsCorrelsOtherwiseNObs: TRUE to return the correlations, FALSE to return the number of observations used in their calculation (diagonal: full number of observations r)* ## Remarks The upper triangle (i \< j) holds the correlations on observations where both assets are above their upper thresholds, and the lower triangle (j, i) those where both are at or below their lower thresholds. The thresholds are the arithmetic mean minus and plus nSigma times the sample standard deviation (denominator n - 1) of the full sample of each series; an observation is selected below if it is at or below the lower threshold and above if it is strictly above the upper threshold. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series); if IsCorrelsOtherwiseNObs is FALSE, the diagonal is the full number of observations r. # apaCorrels.Conditional.Sigma.Joint.Lower(TimeSeries, nSigma) URL: https://www.andreassteiner.net/help/apacorrels.conditional.sigma.joint.lower/ ## Result Calculates the joint conditional correlation matrix for observations where both assets are at or below their arithmetic means minus nSigma sample standard deviations. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *nSigma: number of sample standard deviations defining the threshold below the mean* ## Remarks An observation is used for the pair (i, j) only if it is selected for both assets; the matrix is symmetric. The threshold is the arithmetic mean minus nSigma times the sample standard deviation (denominator n - 1) of the full sample of each series; an observation is selected if it is at or below the threshold. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series). # apaCorrels.Conditional.Sigma.Lower(TimeSeries, nSigma) URL: https://www.andreassteiner.net/help/apacorrels.conditional.sigma.lower/ ## Result Calculates the conditional correlation matrix for observations where the row asset is at or below its arithmetic mean minus nSigma sample standard deviations. ## Syntax *TimeSeries*: r x c data matrix, each column containing a time series *nSigma: number of sample standard deviations defining the threshold below the mean* ## Remarks Element (i, j) is computed on the observations selected by the row asset i, so the matrix is not symmetric: element (j, i) conditions on asset j. The threshold is the arithmetic mean minus nSigma times the sample standard deviation (denominator n - 1) of the full sample of each series; an observation is selected if it is at or below the threshold. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). Each correlation is the Pearson correlation of the selected observations. \#N/A is returned where fewer than two observations are selected or where one of the two series is constant on them; with exactly two selected observations the correlation is always +1 or -1. The diagonal is 1 (#N/A for a constant series). # apaCorrels.ConfidenceIntervals(DataMatrix, ConfidenceLevel, nSamples) URL: https://www.andreassteiner.net/help/apacorrels.confidenceintervals/ ## Result Returns resampled confidence intervals for correlations. The lower interval boundaries are in the lower triangular part, the upper boundaries in the upper triangular part. ## Syntax *DataMatrix*: r x c data matrix, each column containing a series *ConfidenceLevel*: confidence level, e.g. 95%. *nSamples*: number of samples to generate ## Remarks The bounds are the (1 − *ConfidenceLevel*)/2 and (1 + *ConfidenceLevel*)/2 percentiles of the resampled correlations, i.e. a two-sided interval. # apaCorrels.CramersV(Matrix) URL: https://www.andreassteiner.net/help/apacorrels.cramersv/ ## Result Calculates the Cramér’s V matrix between a set of categorical variables, i.e. a measure of association between 0 (no association) and 1 (perfect association) for each pair of columns. ## Syntax *Matrix*: r x c data matrix, each column containing a categorical variable with numeric category labels ## Algorithm For each pair of columns, the contingency table of the category combinations is set up. ## Remarks The diagonal elements equal one. If a variable has only one category, the corresponding associations are set to zero. # apaCorrels.Dispersion(Correls) URL: https://www.andreassteiner.net/help/apacorrels.dispersion/ ## Result Returns the dispersion of correlations in a correlation matrix. ## Syntax *Correls*: n x n correlation matrix ## Algorithm The dispersion is calculated as the standard deviation of the entries in the upper (or lower) triangular part of the correlation matrix. # apaCorrels.Dispersions(Correls, IsSignedOtherwiseAbs) URL: https://www.andreassteiner.net/help/apacorrels.dispersions/ ## Result Calculates the dispersion of the correlations of each element (i.e. asset) with all other elements. ## Syntax *Correls*: n x n correlation matrix *IsSignedOtherwiseAbs*: TRUE if the signs are preserved, FALSE if absolute values are used # apaCorrels.Drop(Correls, ElementIndex) URL: https://www.andreassteiner.net/help/apacorrels.drop/ ## Result Deletes one element (i.e. asset) from a correlation matrix. ## Syntax *Correls*: n x n correlation matrix *ElementIndex*: index of the element (i.e. asset) to drop # apaCorrels.Eigenvalues.Distribution(DataMatrix, nResamples, nBins) URL: https://www.andreassteiner.net/help/apacorrels.eigenvalues.distribution/ ## Result Calculates the empirical probability density function of the eigenvalues of the correlation matrix, based on resampled data. ## Syntax *DataMatrix*: r x c data matrix, each column containing a series *nResamples*: number of times to resample the data *nBins*: number of bins of the empirical distribution # apaCorrels.ExpWeighted(TimeSeries, HalfLife) URL: https://www.andreassteiner.net/help/apacorrels.expweighted/ ## Result Returns an exponentially weighted correlation matrix. ## Syntax *TimeSeries*: matrix of time series data, each column containing a time series *HalfLife*: half-life of the exponential weights of the observations ## Remarks - The resulting correlation matrix is not necessarily valid. # apaCorrels.Equi(nAssets, Correlation) URL: https://www.andreassteiner.net/help/apacorrels.equi/ ## Result Creates an n x n correlation matrix in which all off-diagonal entries are equal to a particular value. ## Syntax *nAssets*: number of constituents in the correlation matrix *Correlation*: the value of the (equi-) correlation coefficient ## Remarks - The resulting correlation matrix is not necessarily valid. # apaCorrels.Fix(Correls, Threshold) URL: https://www.andreassteiner.net/help/apacorrels.fix/ ## Result Fixes an invalid correlation matrix with the spectral method, i.e. eigenvalues below the threshold are raised to the threshold. ## Syntax *Correls*: correlation matrix *Threshold*: optional; minimum eigenvalue which is enforced. 0 returns a positive semi-definite, possibly singular matrix. Negative values return the unchanged correlation matrix; default: 0.0001 ## Algorithm The following problems are fixed: 1. Symmetry of the matrix. 2. All entries on the main diagonal equal to 1. 3. Positive semi-definiteness of the matrix. ## Remarks Definiteness and singularity can be controlled with the Threshold parameter. All eigenvalues below Threshold are set to the Threshold value; the larger the Threshold value, the less singular the resulting matrix (but the larger the difference to the initial correlation matrix). # apaCorrels.FromCovars(Covariances) URL: https://www.andreassteiner.net/help/apacorrels.fromcovars/ ## Result Extracts the correlation matrix from a covariance matrix. ## Syntax *Covariances*: a covariance matrix # apaCorrels.FromVecl(Vecl) URL: https://www.andreassteiner.net/help/apacorrels.fromvecl/ ## Result Turns the vector of the lower triangular part excluding the main diagonal into a correlation matrix. ## Syntax *Vecl*: vector containing the ordered elements of the lower triangular part excluding the main diagonal # apaCorrels.FromVech(Vech) URL: https://www.andreassteiner.net/help/apacorrels.fromvech/ ## Result Turns the vector of the lower triangular part including the main diagonal into a correlation matrix. Also works for covariance matrices. ## Syntax *Vech*: vector containing the ordered elements of the lower triangular part including the main diagonal # apaCorrels.Gerber(TimeSeriesMatrix, c) URL: https://www.andreassteiner.net/help/apacorrels.gerber/ ## Result Calculates the Gerber matrix, the equivalent of the correlation matrix based on the Gerber statistic. ## Syntax *TimeSeriesMatrix*: r x c data matrix, each column containing a time series *c*: number of standard deviations around the mean within which observations are excluded ## Remarks The thresholds use the sample standard deviation (denominator n − 1). # apaCorrels.Gerber.Altered(TimeSeriesMatrix, c) URL: https://www.andreassteiner.net/help/apacorrels.gerber.altered/ ## Result Calculates the altered Gerber matrix, the equivalent of the correlation matrix based on the altered Gerber statistic. ## Syntax *TimeSeriesMatrix*: r x c data matrix, each column containing a time series *c*: number of standard deviations around the mean within which observations are excluded ## Remarks The thresholds use the sample standard deviation (denominator n − 1). # apaCorrels.Gerber.Modified(TimeSeriesMatrix, c) URL: https://www.andreassteiner.net/help/apacorrels.gerber.modified/ ## Result Calculates the modified Gerber matrix, the equivalent of the correlation matrix based on the modified Gerber statistic. ## Syntax *TimeSeriesMatrix*: r x c data matrix, each column containing a time series *c*: number of standard deviations around the mean within which observations are excluded ## Remarks The thresholds use the sample standard deviation (denominator n − 1). # apaCorrels.Gerber.Table(TimeSeries1, TimeSeries2, c, IsPercentOtherwiseAbs) URL: https://www.andreassteiner.net/help/apacorrels.gerber.table/ ## Result Calculates the Gerber table, i.e. the number (or percentage) of observations in which the two time series move jointly up, jointly down, or in opposite directions beyond the threshold. ## Syntax *TimeSeries1*: r x 1 vector containing the first time series *TimeSeries2*: r x 1 vector containing the second time series *c*: number of standard deviations around the mean within which observations are excluded *IsPercentOtherwiseAbs*: TRUE to return percentages of observations, FALSE to return the absolute number of observations ## Remarks The thresholds use the sample standard deviation (denominator n − 1). # apaCorrels.Group.Select(Correls, ElementIndices) URL: https://www.andreassteiner.net/help/apacorrels.group.select/ ## Result Extracts the correlation matrix of a group of elements from a correlation matrix. ## Syntax *Correls*: n x n correlation matrix *ElementIndices*: 1 x k vector containing the indices of the elements # apaCorrels.Group.Select.ByIndicators(Correls, Indicators) URL: https://www.andreassteiner.net/help/apacorrels.group.select.byindicators/ ## Result Extracts the correlation matrix of a selected group of elements from a correlation matrix, the selection being defined by indicators. ## Syntax *Correls*: n x n correlation matrix *Indicators*: 1 x n vector with zeros (do not pick) and ones (pick) # apaCorrels.Implied(PortfolioVolatility, AssetWeights, AssetVolatilities) URL: https://www.andreassteiner.net/help/apacorrels.implied/ ## Result Returns the constant correlation matrix implied by a portfolio volatility, constituent weights and constituent volatilities. ## Syntax *PortfolioVolatility*: portfolio volatility, e.g. 15.53% *AssetWeights*: 1 x n vector of constituent weights *AssetVolatilities*: 1 x n vector of constituent volatilities ## Algorithm See apaCorrel.Implied for the calculation of the implied correlation. The implied correlation matrix is a square matrix with ones on the main diagonal and the implied correlation in all other entries. # apaCorrels.Implied.CVaR(TimeSeries, ConfidenceLevel, Weight) URL: https://www.andreassteiner.net/help/apacorrels.implied.cvar/ ## Result Calculates the implied CVaR correlation matrix: for each pair of assets, the correlation that reproduces the CVaR of a two-asset portfolio when CVaRs are aggregated like volatilities. ## Syntax *TimeSeries: nObs x nAssets matrix in which each column contains the return time series (scenarios) of an asset* *ConfidenceLevel: optional; CVaR confidence level in \[0, 1), e.g. 0.95; default: 0.95* *Weight: optional; weight of the row asset i in each two-asset portfolio, in (0, 1); the column asset j receives 1 - Weight; default: 0.5* ## Remarks For each pair (i, j), the function computes the CVaR of asset i, of asset j and of the portfolio Weight x asset i + (1 - Weight) x asset j, and returns rho_ij = (CVaR_p^2 - w_i^2 CVaR_i^2 - w_j^2 CVaR_j^2) / (2 w_i w_j CVaR_i CVaR_j), i.e. the correlation that reproduces the portfolio CVaR with the variance aggregation rule. CVaR is defined exactly as in the mean-CVaR optimizer (apaMeanCVaR functions, apaMeanCVaR.Assets): the historical Rockafellar-Uryasev CVaR of the raw returns, expressed as a positive loss, i.e. the average of the worst (1 - ConfidenceLevel) x nObs scenario returns with a fractional weight on the boundary scenario; returns are not demeaned. Because this CVaR is subadditive, the implied correlation does not exceed 1; values below 1 measure the CVaR diversification that the optimizer sees between the two assets. For normally distributed returns with zero means the implied correlation equals the Pearson correlation; non-zero means and heavy or asymmetric tails make it differ. The result depends on Weight; with Weight = 0.5 the matrix is symmetric, otherwise element (i, j) uses the weight Weight for the row asset i. The matrix is not guaranteed to be positive semi-definite. Results are clamped to \[-1, 1\]; a non-positive portfolio CVaR returns -1. \#N/A is returned for every element involving an asset whose own CVaR is zero or negative, which happens when the average of its worst scenarios is not a loss. TimeSeries must be a complete numeric matrix (empty cells are read as 0, text returns \#VALUE!). # apaCorrels.IsValid(Correls) URL: https://www.andreassteiner.net/help/apacorrels.isvalid/ ## Result Returns TRUE if the input matrix is a valid correlation matrix, otherwise FALSE. ## Syntax *Correls*: correlation matrix ## Algorithm Five criteria are tested: 4. Is the matrix square? 5. Are all entries of the matrix between -1 and 1? 6. Are all entries on the main diagonal equal to 1? 7. Is the matrix symmetric, i.e. are all entries above the main diagonal equal to the entries below? 8. Is the matrix positive semi-definite? # apaCorrels.Jagged(DataMatrix) URL: https://www.andreassteiner.net/help/apacorrels.jagged/ ## Result Calculates the correlation matrix from jagged time series data. The result is not necessarily a valid correlation matrix; check its validity before further processing and fix the correlations if desired. ## Syntax *DataMatrix*: jagged r x c data matrix, each column containing a time series ## Remarks Each correlation coefficient is the Pearson correlation of the joint observations of the pair, i.e. the rows in which both series are numeric; empty cells, text, logical values and error values are skipped. Where fewer than two joint observations exist or one of the series has zero variance on them, \#N/A is returned. The diagonal is 1 for every series with at least two observations and non-zero variance and \#N/A otherwise. # apaCorrels.Kendall(TimeSeries) URL: https://www.andreassteiner.net/help/apacorrels.kendall/ ## Result Returns the Kendall’s tau-b matrix of a matrix of time series. ## Syntax *TimeSeries*: nRows x nCols matrix of data, each column containing a time series ## Remarks The time series matrix is a matrix of returns, in which each column represents a series and each row an observation. Ties are accounted for (tau-b): τb = (nc − nd) / √((n0 − n1)·(n0 − n2)), where nc and nd are the numbers of concordant and discordant pairs, n0 = n(n − 1)/2, and n1 and n2 are the numbers of tied pairs in X and Y. # apaCorrels.LeadLag(X, Y, nLags) URL: https://www.andreassteiner.net/help/apacorrels.leadlag/ ## Result Calculates leading and lagging correlation coefficients between two time series. High correlations at positive lags mean “X leads, Y lags”, i.e. X tends to move before Y. ## Syntax *X*: r x 1 data vector containing a time series (explanatory variable) *Y*: r x 1 data vector containing a time series *nLags*: number of observations by which the data is shifted forward and backward # apaCorrels.Max(Correls) URL: https://www.andreassteiner.net/help/apacorrels.max/ ## Result Returns the maximum pairwise correlation in a correlation matrix. ## Syntax *Correls*: n x n correlation matrix ## Remarks Only the off-diagonal elements above the main diagonal are considered. # apaCorrels.Maxs(Correls, IsSignedOtherwiseAbs) URL: https://www.andreassteiner.net/help/apacorrels.maxs/ ## Result Calculates the maximum correlation of each element (i.e. asset) with all other elements. ## Syntax *Correls*: n x n correlation matrix *IsSignedOtherwiseAbs*: TRUE if the signs are preserved, FALSE if absolute values are used # apaCorrels.Min(Correls) URL: https://www.andreassteiner.net/help/apacorrels.min/ ## Result Returns the minimum pairwise correlation in a correlation matrix. ## Syntax *Correls*: n x n correlation matrix ## Remarks Only the off-diagonal elements above the main diagonal are considered. # apaCorrels.Mins(Correls, IsSignedOtherwiseAbs) URL: https://www.andreassteiner.net/help/apacorrels.mins/ ## Result Calculates the minimum correlation of each element (i.e. asset) with all other elements. ## Syntax *Correls*: n x n correlation matrix *IsSignedOtherwiseAbs*: TRUE if the signs are preserved, FALSE if absolute values are used # apaCorrels.MSD(Correls1, Correls2) URL: https://www.andreassteiner.net/help/apacorrels.msd/ ## Result Calculates the mean squared deviation between two correlation matrices. ## Syntax *Correls1*: n1 x n1 correlation matrix *Correls2*: n1 x n1 correlation matrix ## Remarks Indicates how different or similar two correlation matrices are. # apaCorrels.MultipleCorrels(CorrelMat) URL: https://www.andreassteiner.net/help/apacorrels.multiplecorrels/ ## Result Calculates the multiple correlation coefficients, i.e. the correlation of a regression of each variable on all other variables. ## Syntax *CorrelMat*: n x n correlation matrix of the variables ## Remarks Useful to assess multicollinearity. # apaCorrels.NonGroup.Select(Correls, ElementIndices) URL: https://www.andreassteiner.net/help/apacorrels.nongroup.select/ ## Result Extracts the correlation matrix of the elements not belonging to a group from a correlation matrix. ## Syntax *Correls*: n x n correlation matrix *ElementIndices*: 1 x k vector containing the indices of the elements to exclude # apaCorrels.Partial(Correls) URL: https://www.andreassteiner.net/help/apacorrels.partial/ ## Result Derives the partial correlation matrix from a correlation matrix. Partial correlations quantify the association between two variables after removing the influence that the other variables have on both. ## Syntax *Correls*: n x n correlation matrix, ideally a valid one # apaCorrels.PearsonToSpearman(Correls) URL: https://www.andreassteiner.net/help/apacorrels.pearsontospearman/ ## Result Converts Pearson correlations into Spearman rank correlations, assuming a multivariate normal distribution. ## Syntax *Correls*: n x n Pearson correlation matrix # apaCorrels.Resample.Stats(DataMatrix, nSamples, SampleSize) URL: https://www.andreassteiner.net/help/apacorrels.resample.stats/ ## Result Resamples a correlation matrix and reports statistics for the correlation matrices: 1) mean absolute deviation (from empirical correlations), 2) mean squared deviation, 3) mean maximum deviation above, 4) mean maximum deviation below. ## Syntax *DataMatrix*: r x c data matrix *nSamples*: number of samples to generate *SampleSize*: size of each sample generated # apaCorrels.Random(nAssets) URL: https://www.andreassteiner.net/help/apacorrels.random/ ## Result Generates a valid random correlation matrix. ## Syntax *nAssets*: dimension of the correlation matrix to be generated ## Remarks - The resulting correlation matrix is always valid. - The random correlation values do not follow a particular distribution (i.e. they are also not uniformly distributed in \[-1, 1\]). # apaCorrels.Randomize(CorrelMat, Degree) URL: https://www.andreassteiner.net/help/apacorrels.randomize/ ## Result Perturbs a correlation matrix in a random manner without rendering it invalid, by shrinking it towards a random correlation matrix. ## Syntax *CorrelMat*: n x n valid correlation matrix *Degree*: degree of randomization between 0 and 1 ## Remarks - The resulting correlation matrix is always valid. - The random correlation values do not follow a particular distribution (i.e. they are also not uniformly distributed in \[-1, 1\]). - A degree of 100% generates a completely random correlation matrix, as apaCorrels.Random does. # apaCorrels.Remove(TimeSeries) URL: https://www.andreassteiner.net/help/apacorrels.remove/ ## Result Removes the correlations between time series (Gram-Schmidt orthogonalization), preserving their means and volatilities. ## Syntax *TimeSeries*: matrix of time series data, each column containig a series ## Remarks The first and second moments are preserved, the higher moments are not. Rescales with population volatilities (denominator n). # apaCorrels.Reorder(Correls, Order) URL: https://www.andreassteiner.net/help/apacorrels.reorder/ ## Result Reorders a correlation matrix based on a vector of indices. ## Syntax *Correls*: n x n correlation matrix *Order*: 1 x n vector of element indices representing the new order # apaCorrels.Shift(Correls, ToIndex) URL: https://www.andreassteiner.net/help/apacorrels.shift/ ## Result Shifts the elements of a correlation matrix such that a particular element becomes the first one. ## Syntax *Correls*: correlation matrix *ToIndex*: index of the element which becomes the new first element. Can be negative ## Remarks - Shifts to the left; elements which would drop out are added on the right. - Also works with negative ToIndex values. Negative values shift to the right. # apaCorrels.Shrink(Correls, Shrinkage, Target) URL: https://www.andreassteiner.net/help/apacorrels.shrink/ ## Result Shrinks a correlation matrix towards a target: a correlation value, the average correlation or the smallest possible equicorrelation. ## Syntax *Correls*: correlation matrix *Shrinkage*: degree of shrinkage, a value between 0 and 1 *Target*: shrinkage target: a) any correlation value between -1 and +1, b) 2 for the average correlation or c) 3 for the smallest possible equicorrelation value -1/(n-1) ## Algorithm The new correlation matrix is calculated as the weighted average of the initial correlations and the target. ## Remarks Shrinking a correlation matrix towards one increases correlations. Shrinking towards zero makes the variables independent. Shrinking towards the smallest equicorrelation results in a correlation matrix with negative correlation values as large as possible. # apaCorrels.SortedBy.Averages(Correls, IsSignedOtherwiseAbs) URL: https://www.andreassteiner.net/help/apacorrels.sortedby.averages/ ## Result Sorts a correlation matrix by the average correlation of each element. ## Syntax *Correls*: n x n correlation matrix *IsSignedOtherwiseAbs*: TRUE if the signs are preserved, FALSE if absolute values are used ## Algorithm See apaCorrels.Averages. # apaCorrels.SortedBy.Dispersions(Correls, IsSignedOtherwiseAbs) URL: https://www.andreassteiner.net/help/apacorrels.sortedby.dispersions/ ## Result Sorts a correlation matrix by the correlation dispersion of each element. ## Syntax *Correls*: n x n correlation matrix *IsSignedOtherwiseAbs*: TRUE if the signs are preserved, FALSE if absolute values are used ## Algorithm See apaCorrels.Dispersions. # apaCorrels.SortedBy.LoadingsPC(Correls, PC) URL: https://www.andreassteiner.net/help/apacorrels.sortedby.loadingspc/ ## Result Sorts a correlation matrix by the loadings to a particular principal component. ## Syntax *Correls*: n x n correlation matrix *PC*: index of the principal component: 1 sorts by the loadings to the first principal component, 2 by the loadings to the second principal component, and so on # apaCorrels.SortedBy.LoadingsPC.Order(Correls, PC) URL: https://www.andreassteiner.net/help/apacorrels.sortedby.loadingspc.order/ ## Result Returns the rank order of the elements of a correlation matrix, sorted by the loadings to a particular principal component. ## Syntax *Correls*: n x n correlation matrix *PC*: index of the principal component: 1 sorts by the loadings to the first principal component, 2 by the loadings to the second principal component, and so on # apaCorrels.SortedBy.Maxs(Correls, SignedOtherwiseAbs) URL: https://www.andreassteiner.net/help/apacorrels.sortedby.maxs/ ## Result Sorts a correlation matrix by the largest value in each row/column. ## Syntax *Correls*: n x n correlation matrix *SignedOtherwiseAbs*: TRUE if the signs of the correlation coefficients are considered, FALSE if the absolute correlation values are relevant # apaCorrels.SortedBy.Mins(Correls, SignedOtherwiseAbs) URL: https://www.andreassteiner.net/help/apacorrels.sortedby.mins/ ## Result Sorts a correlation matrix by the smallest value in each row/column. ## Syntax *Correls*: n x n correlation matrix *SignedOtherwiseAbs*: TRUE if the signs of the correlation coefficients are considered, FALSE if the absolute correlation values are relevant # apaCorrels.Spearman(TimeSeries) URL: https://www.andreassteiner.net/help/apacorrels.spearman/ ## Result Returns the Spearman rank correlation matrix of a matrix of time series. ## Syntax *TimeSeries*: a time series data matrix, each column containing a time series ## Remarks The time series matrix is a matrix of returns, in which each column represents a series and each row an observation. Tied observations receive their average rank. # apaCorrels.SpearmanToPearson(Correls) URL: https://www.andreassteiner.net/help/apacorrels.spearmantopearson/ ## Result Converts Spearman rank correlations into Pearson correlations, assuming a multivariate normal distribution. ## Syntax *Correls*: n x n Spearman correlation matrix # apaCorrels.Swap(Correls, ElementIndex1, ElementIndex2) URL: https://www.andreassteiner.net/help/apacorrels.swap/ ## Result Swaps two constituents in a correlation matrix, i.e. exchanges the corresponding rows and columns. ## Syntax *Correls*: n x n correlation matrix *ElementIndex1*: 1-based index of the first constituent to exchange *ElementIndex2*: 1-based index of the second constituent to exchange ## Remarks The function is volatile. # apaCorrels.FisherTransform.ToBounded(RealCorrels) URL: https://www.andreassteiner.net/help/apacorrels.fishertransform.tobounded/ ## Result Transforms unbounded real numbers into bounded correlation coefficients in \[-1, +1\] (inverse Fisher transformation). ## Syntax *RealCorrels*: matrix of unbounded real numbers, not necessarily representing a valid correlation matrix ## Algorithm ## c = COS(0.5\*PI-ATAN(r)) # apaCorrels.FisherTransform.ToUnbounded(Correls) URL: https://www.andreassteiner.net/help/apacorrels.fishertransform.tounbounded/ ## Result Transforms bounded correlation coefficients into unbounded real numbers (Fisher transformation). ## Syntax *Correls*: a matrix of correlation coefficients, not necessarily a valid correlation matrix ## Algorithm r = TAN(0.5\*PI-ACOS(c)) # apaCorrels.Ultrametric.FromCorrels(Correls) URL: https://www.andreassteiner.net/help/apacorrels.ultrametric.fromcorrels/ ## Result Derives the ultrametric correlation matrix from a correlation matrix. Uses d = sqrt((1-c)/2) to convert correlations into distances. ## Syntax *Correls*: n x n correlation matrix # apaCoUPM(Returns1, Returns2, Threshold, Degree) URL: https://www.andreassteiner.net/help/apacoupm/ ## Result Calculates the co-upper partial moment (co-UPM) risk measure between two return series. ## Syntax *Returns1*: r x 1 vector of returns *Returns2*: r x 1 vector of returns *Threshold*: return threshold *Degree*: degree (order) of the upper partial moment ## Algorithm If Degree \> 1: ![Formula](https://www.andreassteiner.net/help/assets/eq/image42.svg) If Degree = 1: ![Formula](https://www.andreassteiner.net/help/assets/eq/image43.svg) If Degree \< 1: ![Formula](https://www.andreassteiner.net/help/assets/eq/image44.svg) ## Remarks - Denisa Cumova (2004): “Asset Allocation Based on Shortfall Risk”. - Lingwen Kong (2005): “The UPM/LPM Framework on Portfolio Performance Measurement and Optimization”. Partial moments divide by the total number of observations n (population-type). # apaCoUPMs.Asymmetrical(ReturnsMatrix, Threshold, Degree) URL: https://www.andreassteiner.net/help/apacoupms.asymmetrical/ ## Result Calculates the asymmetric co-upper partial moment (co-UPM) matrix. ## Syntax *ReturnsMatrix*: r x c matrix of returns, each column containing a time series *Threshold*: return threshold *Degree*: degree (order) of the upper partial moments ## Remarks Partial moments divide by the total number of observations n (population-type). # apaCoUPMs.Asymmetrical.Symmetrized(ReturnsMatrix, Threshold, Degree) URL: https://www.andreassteiner.net/help/apacoupms.asymmetrical.symmetrized/ ## Result Calculates the symmetrized asymmetric co-upper partial moment (co-UPM) matrix. ## Syntax *ReturnsMatrix*: r x c matrix of returns, each column containing a time series *Threshold*: return threshold *Degree*: degree (order) of the upper partial moments ## Remarks Partial moments divide by the total number of observations n (population-type). # apaCoUPMs.Symmetrical(ReturnsMatrix, Threshold, Degree) URL: https://www.andreassteiner.net/help/apacoupms.symmetrical/ ## Result Calculates the symmetric co-upper partial moment (co-UPM) matrix. ## Syntax *ReturnsMatrix*: r x c matrix of returns, each column containing a time series *Threshold*: return threshold *Degree*: degree (order) of the upper partial moments ## Remarks Partial moments divide by the total number of observations n (population-type). # apaCovar.Downside(Returns1, Returns2, Threshold) URL: https://www.andreassteiner.net/help/apacovar.downside/ ## Result Calculates the downside semi-covariance of two return series. Downside is defined as below the threshold. ## Syntax *Returns1*: r x 1 vector of returns *Returns2*: r x 1 vector of returns *Threshold*: threshold return ## Remarks Partial moments divide by the total number of observations n (population-type). # apaCovar.ExpWeighted(TimeSeries1, TimeSeries2, HalfLife) URL: https://www.andreassteiner.net/help/apacovar.expweighted/ ## Result Returns the exponentially weighted covariance between two time series. ## Syntax *TimeSeries1*: vector with time series data *TimeSeries2*: vector with time series data *HalfLife*: half-life of the exponential weighting scheme ## Remarks The means of both series are exponentially weighted with the same weights as the covariance, see apaExponentialWeights. Exponentially weighted moments; the weights sum to one (population-type, no small-sample correction). # apaCovars(TimeSeries, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apacovars/ ## Result Returns the sample or population covariance matrix of a matrix of time series. ## Syntax *TimeSeries*: a time series data matrix, each column containing a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: FALSE ## Remarks The time series matrix is a matrix of returns, in which each column represents a series and each row an observation. # apaCovars.Add.Portfolios(Covars, Weights) URL: https://www.andreassteiner.net/help/apacovars.add.portfolios/ ## Result Adds portfolios defined by a weight matrix as elements to a covariance matrix. ## Syntax *Covars*: n x n covariance matrix *Weights*: m x n matrix of weights, the m rows representing portfolios # apaCovars.Downside(Returns, Threshold) URL: https://www.andreassteiner.net/help/apacovars.downside/ ## Result Calculates the downside semi-covariance matrix of a return matrix. Downside is defined as below the threshold. ## Syntax *Returns*: r x c matrix of returns, each column containing a series *Threshold*: threshold return ## Remarks Partial moments divide by the total number of observations n (population-type). # apaCovars.Downside.Means(Returns) URL: https://www.andreassteiner.net/help/apacovars.downside.means/ ## Result Calculates the downside semi-covariance matrix of a return matrix. Downside is defined as below the mean of each series. ## Syntax *Returns*: r x c matrix of returns, each column containing a series ## Remarks Partial moments divide by the total number of observations n (population-type). # apaCovars.ExpWeighted(TimeSeries, HalfLife) URL: https://www.andreassteiner.net/help/apacovars.expweighted/ ## Result Calculates the exponentially weighted covariance matrix from a time series matrix. ## Syntax *TimeSeries*: r x c matrix of time series data, each column containing a series *HalfLife*: half-life of the exponential weighting scheme ## Remarks Exponentially weighted moments; the weights sum to one (population-type, no small-sample correction). # apaCovars.Fix(Covariances, Threshold) URL: https://www.andreassteiner.net/help/apacovars.fix/ ## Result Fixes the embedded correlation matrix of a covariance matrix if it is invalid. Spectral method: eigenvalues below the threshold are raised to the threshold. ## Syntax *Covariances*: covariance matrix *Threshold*: optional; minimum eigenvalue of the embedded correlation matrix which is enforced. 0 returns a positive semidefinite, possibly singular matrix. Negative values return the unchanged covariance matrix; default: 0.0001 # apaCovars.FromVolaCorrs(Volatilities, Correls) URL: https://www.andreassteiner.net/help/apacovars.fromvolacorrs/ ## Result Calculates the covariance matrix from a volatility vector and a correlation matrix. ## Syntax *Volatilities*: 1 x n vector of volatilities *Correls*: n x n correlation matrix # apaCovars.FromVech(Vech) URL: https://www.andreassteiner.net/help/apacovars.fromvech/ ## Result Builds the covariance matrix from a vector containing the elements of the lower triangular part including the main diagonal, i.e. covariances and variances. ## Syntax *Vech*: vector containing the ordered elements of the lower triangular part including the main diagonal ## Remarks See vech in the apaMatrix function family. # apaCovars.Jagged(DataMatrix, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apacovars.jagged/ ## Result Returns the covariance matrix of a jagged matrix of time series. Note that the underlying correlation matrix is not necessarily valid. ## Syntax *DataMatrix*: jagged r x c data matrix, each column containing a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: FALSE ## Remarks The time series matrix is a matrix of returns, in which each column represents a series and each row an observation. Volatilities are computed from all numeric observations of each series and correlations from the joint observations of each pair, which is why the resulting matrix is not necessarily positive semi-definite. Where a volatility or a correlation cannot be computed, the covariance is \#N/A. # apaCovars.Semi.Concordant(TimeSeries, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apacovars.semi.concordant/ ## Result Calculates the semi-concordant covariance matrix from time series data, i.e. the covariances of observations moving in the same direction. Sample or population calculations. ## Syntax *TimeSeries*: a time series data matrix, each column containing a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: FALSE # apaCovars.Semi.Neg(TimeSeries, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apacovars.semi.neg/ ## Result Calculates the semi-negative covariance matrix from time series data, i.e. the covariances of negative observations. Sample or population calculations. ## Syntax *TimeSeries*: a time series data matrix, each column containing a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: FALSE # apaCovars.Semi.NonConcordant(TimeSeries, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apacovars.semi.nonconcordant/ ## Result Calculates the semi-non-concordant covariance matrix from time series data, i.e. the covariances of observations moving in opposite directions. Sample or population calculations. ## Syntax *TimeSeries*: a time series data matrix, each column containing a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: FALSE # apaCovars.Semi.Pos(TimeSeries, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apacovars.semi.pos/ ## Result Calculates the semi-positive covariance matrix from time series data, i.e. the covariances of positive observations. Sample or population calculations. ## Syntax *TimeSeries*: a time series data matrix, each column containing a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: FALSE # apaCovars.Shrink(Covars, ShrinkageVols, ShrinkageCorrs) URL: https://www.andreassteiner.net/help/apacovars.shrink/ ## Result Shrinks a covariance matrix towards the average covariance matrix, with different amounts of shrinkage for volatilities and correlations. ## Syntax *Covars*: covariance matrix *ShrinkageVols*: degree of shrinkage for volatilities, a value between 0 and 1 *ShrinkageCorrs*: degree of shrinkage for correlations, a value between 0 and 1 ## Algorithm The volatilities are shrunk towards the average volatility and the correlations towards the average correlation; the covariance matrix is rebuilt from the shrunk volatilities and correlations. # apaCSVDates(CSVFileName) URL: https://www.andreassteiner.net/help/apacsvdates/ ## Result Reads the date column from an external CSV time series file. ## Syntax *CSVFileName*: name of the CSV data file including its path, for example “C:\Users\Peter Mill\Desktop\IndexReturns.csv” ## Remarks The CSV file has to be of the following format: - The first row contains the series names. - The first column contains the dates. - All series have to be complete, i.e. all series have to have data on each date. - The field delimiter is “;”. - No text qualifiers are required. - The required format is automatically generated when saving data in Excel to a \*.csv file. # apaCSVNames(CSVFileName) URL: https://www.andreassteiner.net/help/apacsvnames/ ## Result Reads the time series names from an external CSV time series file. ## Syntax *CSVFileName*: name of the CSV data file including its path, for example “C:\Users\Peter Mill\Desktop\IndexReturns.csv” ## Remarks The CSV file has to be of the following format: - The first row contains the series names. - The first column contains the dates. - All series have to be complete, i.e. all series have to have data on each date. - The field delimiter is “;”. - No text qualifiers are required. - The required format is automatically generated when saving data in Excel to a \*.csv file. # apaCSVTimeSeries(CSVFileName) URL: https://www.andreassteiner.net/help/apacsvtimeseries/ ## Result Reads the time series data from an external CSV time series file. ## Syntax *CSVFileName*: name of the CSV data file including its path, for example “C:\Users\Peter Mill\Desktop\IndexReturns.csv” ## Remarks The CSV file has to be of the following format: - The first row contains the series names. - The first column contains the dates. - All series have to be complete, i.e. all series have to have data on each date. - The field delimiter is “;”. - No text qualifiers are required. - The required format is automatically generated when saving data in Excel to a \*.csv file. # apaCVaG.Empirical(Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apacvag.empirical/ ## Result Calculates the empirical conditional value at gain (CVaG) from a time series matrix of returns. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *ConfidenceLevel*: confidence level, e.g. 95%. ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image45.svg) ## Remarks CVaG is the average of the returns above the value at gain (VaG), the ConfidenceLevel percentile of each column; for a confidence level of 0.95 this is the average of the best 5% of returns. \#N/A is returned if no return lies above the VaG. # apaCVaR.Empirical(Returns, ConfidenceLevel, IsSmooth) URL: https://www.andreassteiner.net/help/apacvar.empirical/ ## Result Calculates the empirical (historical) conditional value at risk (CVaR) from a time series matrix of returns. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *ConfidenceLevel*: confidence level, e.g. 95%. *IsSmooth*: TRUE for the smoothed estimate (see below), FALSE for the average of the returns below the VaR ## Algorithm General definition: ![Formula](https://www.andreassteiner.net/help/assets/eq/image46.svg) If IsSmooth = FALSE: ![Formula](https://www.andreassteiner.net/help/assets/eq/image47.svg) If IsSmooth = TRUE: With the returns sorted in ascending order r(1) ≤ … ≤ r(n), m = (1 − *ConfidenceLevel*)·n and k = ⌊m⌋: CVaR = (r(1) + … + r(k) + (m − k)·r(k+1)) / m ## Remarks Losses are reported as negative numbers. \#N/A is returned if *IsSmooth* = FALSE and no return lies below the VaR. # apaCVaR.Normal(Returns, ConfidenceLevel, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apacvar.normal/ ## Result Calculates the parametric normal conditional value at risk (CVaR) of a return time series. ## Syntax *Returns*: r x 1 vector of returns *ConfidenceLevel*: confidence level, e.g. 0.95. *IsSampleOtherwisePopulation*: optional; TRUE for sample volatility (division by n-1), FALSE for population volatility (division by n); default: FALSE ## Algorithm CVaR = μ − σ·φ(z) / α, where α = 1 − *ConfidenceLevel*, z = N⁻¹(α) and φ is the standard normal density. Losses are reported as negative numbers. ## Remarks The volatility is the sample (denominator n − 1) or population (denominator n) standard deviation, set by IsSampleOtherwisePopulation; default: population. # apaCVaR.Normal.FromConstituents(Weights, Returns, ConfidenceLevel, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apacvar.normal.fromconstituents/ ## Result Calculates the ex ante parametric normal conditional value at risk (CVaR) of a portfolio from constituent weights and returns. ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: FALSE ## Algorithm CVaR = μ − σ·φ(z) / α, where α = 1 − *ConfidenceLevel*, z = N⁻¹(α) and φ is the standard normal density. Losses are reported as negative numbers. ## Remarks Sample (denominator n − 1) or population (denominator n) covariances are used, set by IsSampleOtherwisePopulation; default: population. # apaCVaR.Normal.Moments(Mu, Sigma, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apacvar.normal.moments/ ## Result Calculates the parametric normal conditional value at risk (CVaR) from the mean and the volatility. ## Syntax *Mu*: the location parameter (mean) *Sigma*: the dispersion parameter (volatility) *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm CVaR = μ − σ·φ(z) / α, where α = 1 − *ConfidenceLevel*, z = N⁻¹(α) and φ is the standard normal density. Losses are reported as negative numbers. # apaCVaR.Modified(Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apacvar.modified/ ## Result Calculates the modified conditional value at risk (modified CVaR) of a return time series. ## Syntax *Returns*: r x 1 vector of returns *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm CVaR = μ − σ·φ(z) / α · (1 + z·S/6 + (1 − 2z²)·S²/36 + (z² − 1)·K/24), where α = 1 − *ConfidenceLevel*, z = N⁻¹(α), S is the skewness and K the excess kurtosis. Losses are reported as negative numbers. ## Remarks Population moments of the returns are used. # apaCVaR.Modified.FromConstituents(Weights, Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apacvar.modified.fromconstituents/ ## Result Calculates the parametric modified conditional value at risk (modified CVaR) of a portfolio from constituent weights and returns. ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks Population moments of the portfolio returns are used. Losses are reported as negative numbers. # apaCVaR.Modified.Moments(Mu, Sigma, Skewness, ExcessKurtosis, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apacvar.modified.moments/ ## Result Calculates the modified conditional value at risk (modified CVaR) from moments. ## Syntax *Mu*: mean (first moment) *Sigma*: standard deviation (square root of the second moment) *Skewness*: skewness *ExcessKurtosis*: excess kurtosis, i.e. kurtosis minus three (zero for a normal distribution) *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm CVaR = μ − σ·φ(z) / α · (1 + z·S/6 + (1 − 2z²)·S²/36 + (z² − 1)·K/24), where α = 1 − *ConfidenceLevel*, z = N⁻¹(α), S is the skewness and K the excess kurtosis. Losses are reported as negative numbers. # apaData.Datatypes(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.datatypes/ ## Result Returns the data type of each cell of a data matrix: Double, String, Boolean, ExcelEmpty or ExcelError. ## Syntax *DataMatrix*: data matrix, each column a different data series # apaData.Dates.Earliest.Month(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.dates.earliest.month/ ## Result Returns the first observation (complete row) of each calendar month. ## Syntax *DataMatrix*: nObs x nSeries data matrix, the first column containing Excel dates in ascending order ## Remarks The first column must contain Excel dates in ascending order; a header row or a non-numeric or decreasing date returns an error that states the row. Times of day are ignored when assigning a date to a period. The first and last months of the data may be incomplete, so their first observation is not necessarily at the beginning of the period. Blank cells are shown as \#N/A. # apaData.Dates.Earliest.Quarter(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.dates.earliest.quarter/ ## Result Returns the first observation (complete row) of each calendar quarter. ## Syntax *DataMatrix*: nObs x nSeries data matrix, the first column containing Excel dates in ascending order ## Remarks The first column must contain Excel dates in ascending order; a header row or a non-numeric or decreasing date returns an error that states the row. Times of day are ignored when assigning a date to a period. The first and last quarters of the data may be incomplete, so their first observation is not necessarily at the beginning of the period. Blank cells are shown as \#N/A. # apaData.Dates.Earliest.Week(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.dates.earliest.week/ ## Result Returns the first observation (complete row) of each week (Monday to Sunday). ## Syntax *DataMatrix*: nObs x nSeries data matrix, the first column containing Excel dates in ascending order ## Remarks Weeks run from Monday to Sunday, independently of the regional settings. The first column must contain Excel dates in ascending order; a header row or a non-numeric or decreasing date returns an error that states the row. Times of day are ignored when assigning a date to a period. The first and last weeks of the data may be incomplete, so their first observation is not necessarily at the beginning of the period. Blank cells are shown as \#N/A. # apaData.Dates.Earliest.Year(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.dates.earliest.year/ ## Result Returns the first observation (complete row) of each calendar year. ## Syntax *DataMatrix*: nObs x nSeries data matrix, the first column containing Excel dates in ascending order ## Remarks The first column must contain Excel dates in ascending order; a header row or a non-numeric or decreasing date returns an error that states the row. Times of day are ignored when assigning a date to a period. The first and last years of the data may be incomplete, so their first observation is not necessarily at the beginning of the period. Blank cells are shown as \#N/A. # apaData.Dates.Latest.Month(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.dates.latest.month/ ## Result Returns the last observation (complete row) of each calendar month. ## Syntax *DataMatrix*: nObs x nSeries data matrix, the first column containing Excel dates in ascending order ## Remarks The first column must contain Excel dates in ascending order; a header row or a non-numeric or decreasing date returns an error that states the row. Times of day are ignored when assigning a date to a period. The first and last months of the data may be incomplete, so their last observation is not necessarily at the end of the period. Blank cells are shown as \#N/A. # apaData.Dates.Latest.Quarter(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.dates.latest.quarter/ ## Result Returns the last observation (complete row) of each calendar quarter. ## Syntax *DataMatrix*: nObs x nSeries data matrix, the first column containing Excel dates in ascending order ## Remarks The first column must contain Excel dates in ascending order; a header row or a non-numeric or decreasing date returns an error that states the row. Times of day are ignored when assigning a date to a period. The first and last quarters of the data may be incomplete, so their last observation is not necessarily at the end of the period. Blank cells are shown as \#N/A. # apaData.Dates.Latest.Week(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.dates.latest.week/ ## Result Returns the last observation (complete row) of each week (Monday to Sunday). ## Syntax *DataMatrix*: nObs x nSeries data matrix, the first column containing Excel dates in ascending order ## Remarks Weeks run from Monday to Sunday, independently of the regional settings. The first column must contain Excel dates in ascending order; a header row or a non-numeric or decreasing date returns an error that states the row. Times of day are ignored when assigning a date to a period. The first and last weeks of the data may be incomplete, so their last observation is not necessarily at the end of the period. Blank cells are shown as \#N/A. # apaData.Dates.Latest.Year(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.dates.latest.year/ ## Result Returns the last observation (complete row) of each calendar year. ## Syntax *DataMatrix*: nObs x nSeries data matrix, the first column containing Excel dates in ascending order ## Remarks The first column must contain Excel dates in ascending order; a header row or a non-numeric or decreasing date returns an error that states the row. Times of day are ignored when assigning a date to a period. The first and last years of the data may be incomplete, so their last observation is not necessarily at the end of the period. Blank cells are shown as \#N/A. # apaData.Dates.Match.A(DataMatrixA, DataMatrixB) URL: https://www.andreassteiner.net/help/apadata.dates.match.a/ ## Result Joins two data matrices on the Excel dates in their first columns and keeps all dates of the first matrix. The output contains the date, the data columns of DataMatrixA and the data columns of DataMatrixB, with \#N/A where DataMatrixB has no row for the date. ## Syntax *DataMatrixA*: first data matrix, the first column containing Excel dates *DataMatrixB*: second data matrix, the first column containing Excel dates ## Remarks Rows whose first-column value is not numeric (for example header labels or blank rows) are skipped, so both matrices may include a header row. The dates do not need to be sorted; the output is sorted by date in ascending order. If a date occurs more than once in a matrix, the first occurrence is used for matching. Blank input cells and missing matches are shown as \#N/A. If no date qualifies, \#N/A is returned. # apaData.Dates.Match.B(DataMatrixA, DataMatrixB) URL: https://www.andreassteiner.net/help/apadata.dates.match.b/ ## Result Joins two data matrices on the Excel dates in their first columns and keeps all dates of the second matrix. The output contains the date, the data columns of DataMatrixB and the data columns of DataMatrixA, with \#N/A where DataMatrixA has no row for the date. ## Syntax *DataMatrixA*: first data matrix, the first column containing Excel dates *DataMatrixB*: second data matrix, the first column containing Excel dates ## Remarks Rows whose first-column value is not numeric (for example header labels or blank rows) are skipped, so both matrices may include a header row. The dates do not need to be sorted; the output is sorted by date in ascending order. If a date occurs more than once in a matrix, the first occurrence is used for matching. Blank input cells and missing matches are shown as \#N/A. If no date qualifies, \#N/A is returned. # apaData.Dates.Match.AandB(DataMatrixA, DataMatrixB) URL: https://www.andreassteiner.net/help/apadata.dates.match.aandb/ ## Result Joins two data matrices on the Excel dates in their first columns and keeps only the dates found in both matrices. The output contains the date, the data columns of DataMatrixA and the data columns of DataMatrixB. ## Syntax *DataMatrixA*: first data matrix, the first column containing Excel dates *DataMatrixB*: second data matrix, the first column containing Excel dates ## Remarks Rows whose first-column value is not numeric (for example header labels or blank rows) are skipped, so both matrices may include a header row. The dates do not need to be sorted; the output is sorted by date in ascending order. If a date occurs more than once in a matrix, the first occurrence is used for matching. Blank input cells and missing matches are shown as \#N/A. If no date qualifies, \#N/A is returned. # apaData.Dates.Match.AorB(DataMatrixA, DataMatrixB) URL: https://www.andreassteiner.net/help/apadata.dates.match.aorb/ ## Result Joins two data matrices on the Excel dates in their first columns and keeps the dates found in either matrix. The output contains the date, the data columns of DataMatrixA and the data columns of DataMatrixB, with \#N/A where a matrix has no row for the date. ## Syntax *DataMatrixA*: first data matrix, the first column containing Excel dates *DataMatrixB*: second data matrix, the first column containing Excel dates ## Remarks Rows whose first-column value is not numeric (for example header labels or blank rows) are skipped, so both matrices may include a header row. The dates do not need to be sorted; the output is sorted by date in ascending order. If a date occurs more than once in a matrix, the first occurrence is used for matching. Blank input cells and missing matches are shown as \#N/A. If no date qualifies, \#N/A is returned. # apaData.Digits.After(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.digits.after/ ## Result Returns the number of decimal places of each number in a data matrix. ## Syntax *DataMatrix*: data matrix, each column a different data series ## Remarks Numbers are evaluated with 15 significant digits, independently of the regional settings, so that floating-point noise (for example 0.1 + 0.2) is not counted. Numbers in scientific notation are handled (1E-07 has 7 decimal places). Non-numeric cells return \#N/A. # apaData.Digits.Before(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.digits.before/ ## Result Returns the number of digits before the decimal point of each number in a data matrix. ## Syntax *DataMatrix*: data matrix, each column a different data series ## Remarks The sign is ignored. Numbers with an absolute value below 1 return 1 (for example 0.5). Numbers are evaluated with 15 significant digits, independently of the regional settings. Non-numeric cells return \#N/A. # apaData.Drop.Zeros.Rows(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.drop.zeros.rows/ ## Result Drops all rows (joint observations) that contain a numeric zero. ## Syntax *DataMatrix*: n x m data matrix ## Remarks Only numeric zeros are dropped; text such as "0" and blank cells are kept. Blank cells in the remaining rows are shown as \#N/A. If no row remains, \#N/A is returned. # apaData.Gaps(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.gaps/ ## Result Calculates the size and frequency of gaps in data. The first column is the gap length, the other columns are the number of gaps of that length in each series. ## Syntax *DataMatrix*: data matrix. Missing elements must be non-numerical. ## Remarks A gap is a run of consecutive non-numeric cells (blank, text, logical or error); runs at the start or end of a series count as gaps as well. If there are no gaps, \#N/A is returned. # apaData.Gaps.Matrix(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.gaps.matrix/ ## Result Replaces each non-numeric cell by the length of the gap it belongs to and each numeric cell by 0. ## Syntax *DataMatrix*: data matrix. Missing elements must be non-numerical. ## Remarks A gap is a run of consecutive non-numeric cells (blank, text, logical or error) within a series. # apaData.nObs.Bivariate(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.nobs.bivariate/ ## Result Returns a matrix with the number of observations available for correlation calculations from jagged data: univariate numbers of observations on the main diagonal, bivariate joint observations on the off-diagonals. ## Syntax *DataMatrix*: a jagged data matrix, each column containing a series ## Remarks Only numeric cells count as observations; empty cells, text, logical values and error values are skipped. Pairs without common observations, and series without observations, return 0. # apaData.nObs.Joint(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.nobs.joint/ ## Result Returns the number of joint observations in a jagged data matrix. ## Syntax *DataMatrix*: a jagged data matrix, each column containing a series ## Remarks A joint observation is a row in which all series are numeric. The function returns 0 if there is no such row. # apaData.nObs.Joint.DropSeries(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.nobs.joint.dropseries/ ## Result Returns the number of joint observations when each series is dropped individually. ## Syntax *DataMatrix*: a jagged data matrix, each column containing a series ## Remarks Returns a 1 x c row vector. Element j is the number of rows in which all series except series j are numeric. With only one series, \#N/A is returned. # apaData.nObs.Joint.DropObs(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.nobs.joint.dropobs/ ## Result Returns the number of joint observations if each observation is dropped individually. ## Syntax *DataMatrix*: a jagged data matrix, each column containing a series ## Remarks Returns an r x 1 column vector. Element i is the number of joint observations (rows in which all series are numeric) after removing row i. # apaData.nObs.nTypes.Observations(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.nobs.ntypes.observations/ ## Result Counts the non-zero numbers, zeros, positive numbers, negative numbers, blanks, text, error values and logical values for each observation (row). Returns an nObs x 8 matrix. ## Syntax *DataMatrix*: data matrix, each column a different data series ## Remarks Counts are, in this order: non-zero numbers, zeros, positive numbers, negative numbers, blanks, text, error values and logical values (TRUE/FALSE). Positive and negative numbers are a breakdown of the non-zero numbers. Logical values are counted only in the last category. # apaData.nObs.nTypes.Series(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.nobs.ntypes.series/ ## Result Counts the non-zero numbers, zeros, positive numbers, negative numbers, blanks, text, error values and logical values for each series (column). Returns an 8 x nSeries matrix. ## Syntax *DataMatrix*: data matrix, each column a different data series ## Remarks Counts are, in this order: non-zero numbers, zeros, positive numbers, negative numbers, blanks, text, error values and logical values (TRUE/FALSE). Positive and negative numbers are a breakdown of the non-zero numbers. Logical values are counted only in the last category. # apaData.Proxy.CategoryAverage(DataMatrix, CategoryLabels, ProxyIndicators, DoUseExistingDataForCategoryAvg, DoReplaceAll, MinGapSize, MaxGapSize) URL: https://www.andreassteiner.net/help/apadata.proxy.categoryaverage/ ## Result Proxies series with category average values. ## Syntax *DataMatrix*: a jagged time series data matrix, each column containing a time series *CategoryLabels*: 1 x n vector with category labels *ProxyIndicators*: 1 x n vector of 0s and 1s; a value of 1 means that the series is proxied by the category average. Other values return an error. *DoUseExistingDataForCategoryAvg*: TRUE if existing data of the proxied series is included in the category average, FALSE if only the values of the other series in the same category are used *DoReplaceAll*: TRUE if existing values are overridden by the category average, FALSE if existing values are kept *MinGapSize*: minimum gap size to fill in; must not be negative *MaxGapSize*: maximum gap size to fill in; must not be smaller than MinGapSize ## Remarks For each row, the category average is the mean of the numeric values of the series in the same category; proxied series are included only if DoUseExistingDataForCategoryAvg is TRUE. A missing element of a proxied series is replaced if the run of consecutive non-numeric cells containing it is between MinGapSize and MaxGapSize long; runs at the start or end of a series count as gaps as well. If the category has no numeric values in that row, \#N/A is returned. CategoryLabels and ProxyIndicators may be row or column vectors with one entry per column of DataMatrix. Blank cells that are not filled are shown as \#N/A. # apaData.Repeats(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.repeats/ ## Result Calculates the size and frequency of repeats in data. The first column is the run length, the other columns are the number of runs of that length in each series. ## Syntax *DataMatrix*: data matrix. Missing elements must be non-numerical. ## Remarks A repeat is a run of at least two identical consecutive numbers within a series; non-numeric cells end a run. For example, the series 1, 1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 5 has two runs of length 2, one of length 3 and one of length 4. If there are no repeats, \#N/A is returned. # apaData.Repeats.Matrix(DataMatrix) URL: https://www.andreassteiner.net/help/apadata.repeats.matrix/ ## Result Replaces each cell that belongs to a repeat by the length of that repeat and all other cells by 0. ## Syntax *DataMatrix*: data matrix. Missing elements must be non-numerical. ## Remarks A repeat is a run of at least two identical consecutive numbers within a series; non-numeric cells end a run and return 0. For example, the series 1, 1, 1, 2, 2, 3 returns 3, 3, 3, 2, 2, 0. # apaDCC.GARCH.11.Estimate(DataMatrix) URL: https://www.andreassteiner.net/help/apadcc.garch.11.estimate/ ## Result Estimates a DCC‑GARCH(1,1) model with internal univariate GARCH(1,1) estimation and returns model diagnostics, per‑series GARCH parameters, the latest conditional correlation and covariance matrices, and the time series of dynamic pairwise correlations. A standard DCC approach estimates univariate GARCH models first and then estimates the dynamic correlation parameters $`a`$and $`b`$in a second step. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series ## Algorithm Inputs are validated: DataMatrix must be non-empty, with at least 2 observations and at least 2 series. ## Remarks Maximum likelihood; the variance start values and the correlation target use sample moments (denominator n − 1). # apaDCC.GARCH.11.Forecast(DataMatrix, nVector) URL: https://www.andreassteiner.net/help/apadcc.garch.11.forecast/ ## Result Returns out-of-sample DCC-GARCH(1,1) correlation forecasts for the requested forecast horizons, expressed as vecl representations of the forecast correlation matrices. Future conditional correlations are forecast from the fitted dynamic correlation process after the univariate GARCH stage has been estimated. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *nVector*: 1 x m or m x 1 vector of forecast horizons (positive integers) ## Algorithm Inputs are validated: DataMatrix must be non-empty with at least 2 observations and 2 series, and nVector must contain at least one valid positive horizon. Valid finite horizons are rounded to positive integers. ## Remarks Maximum likelihood; the variance start values and the correlation target use sample moments (denominator n − 1). # apaDRatio(Returns) URL: https://www.andreassteiner.net/help/apadratio/ ## Result Returns the d-ratio, the ratio of the total size of losses to the total size of gains, each weighted by its number of occurrences. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. ## Algorithm d-ratio = (nd · Σ max(−r, 0)) / (nu · Σ max(r, 0)), where nd and nu are the numbers of negative and positive returns (Bacon 2013). ## Remarks The result is a 1 x c row vector with one value per column of Returns. Lower values are better. The result is 0 if there are no negative returns and \#N/A if there are no positive returns. # apaDecisionTree.Regression.Fitted(Y, X, maxDepth, minSamplesSplit) URL: https://www.andreassteiner.net/help/apadecisiontree.regression.fitted/ ## Result Decision tree regression: returns the fitted values of Y. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of explanatory variables *maxDepth*: maximum depth of the tree (determines the number of branches) *minSamplesSplit*: minimum number of samples required to split a node # apaDecisionTree.Regression.Predict(Y, X, predictedX, maxDepth, minSamplesSplit) URL: https://www.andreassteiner.net/help/apadecisiontree.regression.predict/ ## Result Decision tree regression: returns the predicted values of Y for new values of X. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of explanatory variables *predictedX*: m x c matrix of explanatory variables for which Y is predicted *maxDepth*: maximum depth of the tree (determines the number of branches) *minSamplesSplit*: minimum number of samples required to split a node # apaDecisionTree.Regression.Residuals(Y, X, maxDepth, minSamplesSplit) URL: https://www.andreassteiner.net/help/apadecisiontree.regression.residuals/ ## Result Decision tree regression: returns the residuals. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of explanatory variables *maxDepth*: maximum depth of the tree (determines the number of branches) *minSamplesSplit*: minimum number of samples required to split a node # apaDecisionTree.Regression.ScatterPlot(Y, X, maxDepth, minSamplesSplit) URL: https://www.andreassteiner.net/help/apadecisiontree.regression.scatterplot/ ## Result Decision tree regression: returns a representation of the tree structure for plotting. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of explanatory variables *maxDepth*: maximum depth of the tree (determines the number of branches) *minSamplesSplit*: minimum number of samples required to split a node # apaDecisionTree.Regression.Structure(Y, X, maxDepth, minSamplesSplit) URL: https://www.andreassteiner.net/help/apadecisiontree.regression.structure/ ## Result Decision tree regression: returns a flat representation of the tree structure. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of explanatory variables *maxDepth*: maximum depth of the tree (determines the number of branches) *minSamplesSplit*: minimum number of samples required to split a node # apaDecisionTree.Regression.R2(Y, X, predictedX, maxDepth, minSamplesSplit) URL: https://www.andreassteiner.net/help/apadecisiontree.regression.r2/ ## Result Decision tree regression: returns the R-squared. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of explanatory variables *predictedX*: m x c matrix of explanatory variables for which Y is predicted *maxDepth*: maximum depth of the tree (determines the number of branches) *minSamplesSplit*: minimum number of samples required to split a node # apaDecisionTree.Regression.Timeseries.Forecast(Y, maxDepth, minSamplesSplit, nLags, nAhead) URL: https://www.andreassteiner.net/help/apadecisiontree.regression.timeseries.forecast/ ## Result Decision tree regression for time series forecasts: returns n-step-ahead forecasts with forecast intervals. The function is non-volatile. ## Syntax *Y*: r x 1 vector containing the time series *maxDepth*: maximum depth of the tree (determines the number of branches) *minSamplesSplit*: minimum number of samples required to split a node *nLags*: number of lags used as explanatory variables *nAhead*: number of periods ahead to forecast # apaDecisionTree.Regression.Timeseries.R2(Y, maxDepth, minSamplesSplit, nLags) URL: https://www.andreassteiner.net/help/apadecisiontree.regression.timeseries.r2/ ## Result Decision tree regression for time series forecasts: returns the R-squared. The function is non-volatile. ## Syntax *Y*: r x 1 vector containing the time series *maxDepth*: maximum depth of the tree (determines the number of branches) *minSamplesSplit*: minimum number of samples required to split a node *nLags*: number of lags used as explanatory variables # apaDependence.Empirical.Lower(X, Y, Threshold) URL: https://www.andreassteiner.net/help/apadependence.empirical.lower/ ## Result Calculates the empirical lower (left) tail dependence, i.e. the probability that Y is below the threshold given that X is below the threshold. ## Syntax *X*: r x 1 vector of returns *Y*: r x 1 vector of returns *Threshold*: return threshold ## Algorithm The lower tail dependence is a conditional probability: ![Formula](https://www.andreassteiner.net/help/assets/eq/image49.svg) ## Remarks \ # apaDetrend.LinearRegress(DataMatrix) URL: https://www.andreassteiner.net/help/apadetrend.linearregress/ ## Result Detrends data with a linear regression in time, y = a + b\*t. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series # apaDetrend.LinearRegress.Trend(DataMatrix) URL: https://www.andreassteiner.net/help/apadetrend.linearregress.trend/ ## Result Detrends data with a linear regression in time, y = a + b\*t. Returns the trend values. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series # apaDetrend.LinearRegress.Trend.Ahead(DataMatrix, nAhead) URL: https://www.andreassteiner.net/help/apadetrend.linearregress.trend.ahead/ ## Result Detrends data with a linear regression in time, y = a + b\*t. Returns the trend values and nAhead extrapolated values. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *nAhead*: number of observations to extrapolate # apaDetrend.Polynomial(DataMatrix, Order) URL: https://www.andreassteiner.net/help/apadetrend.polynomial/ ## Result Detrends data with a polynomial expression in t of order n. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order of the polynomial expression, e.g. 0 for mean, 1 for linear, 2 for quadratic and so on. # apaDetrend.Polynomial.Trend(DataMatrix, Order) URL: https://www.andreassteiner.net/help/apadetrend.polynomial.trend/ ## Result Detrends data with a polynomial expression in t of order n. Returns the trend values. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order of the polynomial expression, e.g. 0 for mean, 1 for linear, 2 for quadratic and so on. # apaDetrend.Polynomial.Trend.Ahead(DataMatrix, Order, nAhead) URL: https://www.andreassteiner.net/help/apadetrend.polynomial.trend.ahead/ ## Result Detrends data with a polynomial expression in t of order n. Returns the trend values and nAhead extrapolated values. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order of the polynomial expression, e.g. 0 for mean, 1 for linear, 2 for quadratic and so on. *nAhead*: number of observations to extrapolate # apaDistances.Angular(DataMatrix) URL: https://www.andreassteiner.net/help/apadistances.angular/ ## Result Derives the angular distance matrix from a data matrix. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series # apaDistances.Average(Distances) URL: https://www.andreassteiner.net/help/apadistances.average/ ## Result Calculates the average distance between all objects. ## Syntax *Distances*: n x n distance (or similarity) matrix # apaDistances.Averages(Distances) URL: https://www.andreassteiner.net/help/apadistances.averages/ ## Result Calculates the average distance of each object from all other objects. ## Syntax *Distances*: n x n distance (or similarity) matrix # apaDistances.Chebyshev(DataMatrix) URL: https://www.andreassteiner.net/help/apadistances.chebyshev/ ## Result Derives the Chebyshev distance matrix from a data matrix. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series ## Remarks Also known as maximum distance. # apaDistances.Correl(DataMatrix) URL: https://www.andreassteiner.net/help/apadistances.correl/ ## Result Derives a correlation-based distance matrix from a data matrix. Uses d = sqrt((1-c)/2) to convert correlations into distances. ## Syntax *DataMatrix*: r x c matrix of observations, each column containing a variable ## Algorithm > > ``` math > d = \sqrt{0.5(1 - \rho)} > ``` # apaDistances.Correl.FromCorrels(Correls) URL: https://www.andreassteiner.net/help/apadistances.correl.fromcorrels/ ## Result Derives a distance matrix from a correlation matrix. Uses d = sqrt((1-c)/2) to convert correlations into distances. ## Syntax *Correls*: n x n correlation matrix # apaDistances.Correl.Linear(DataMatrix) URL: https://www.andreassteiner.net/help/apadistances.correl.linear/ ## Result Derives a distance matrix from a data matrix. Uses d = (1-c)/2 to convert correlations into distances. ## Syntax *DataMatrix*: r x c matrix of observations, each column containing a variable # apaDistances.Correl.Linear.FromCorrels(Correls) URL: https://www.andreassteiner.net/help/apadistances.correl.linear.fromcorrels/ ## Result Derives a distance matrix from a correlation matrix. Uses d = (1-c)/2 to convert correlations into distances. ## Syntax *Correls*: n x n correlation matrix # apaDistances.Correl.Trigonometric(DataMatrix) URL: https://www.andreassteiner.net/help/apadistances.correl.trigonometric/ ## Result Derives a distance matrix from a data matrix. Uses d = acos(c)/π to convert correlations into distances. ## Syntax *DataMatrix*: r x c matrix of observations, each column containing a variable # apaDistances.Correl.Trigonometric.FromCorrels(Correls) URL: https://www.andreassteiner.net/help/apadistances.correl.trigonometric.fromcorrels/ ## Result Derives a distance matrix from a correlation matrix. Uses d = acos(c)/π to convert correlations into distances. ## Syntax *Correls*: n x n correlation matrix # apaDistances.Cosine(DataMatrix) URL: https://www.andreassteiner.net/help/apadistances.cosine/ ## Result Derives the cosine distance matrix from a data matrix. Cosine distance is defined as 1 - cosine similarity. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series # apaDistances.Covar(DataMatrix) URL: https://www.andreassteiner.net/help/apadistances.covar/ ## Result Derives a distance matrix from the covariance structure of a data matrix. Uses d = sqrt(2\*(1-covar_normalized)) to convert, with the normalized covariances within \[0,1\]. ## Syntax *DataMatrix*: r x c matrix of observations, each column containing a variable ## Remarks Uses population covariances (denominator n). # apaDistances.Covar.FromCovars(Covars) URL: https://www.andreassteiner.net/help/apadistances.covar.fromcovars/ ## Result Derives a distance matrix from a covariance matrix. Uses d = sqrt(2\*(1-covar_normalized)) to convert, with the normalized covariances within \[0,1\]. ## Syntax *Covars*: n x n covariance matrix # apaDistances.Euclidian(DataMatrix) URL: https://www.andreassteiner.net/help/apadistances.euclidian/ ## Result Derives the Euclidean distance matrix from a data matrix. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series ## Algorithm > > ``` math > d = \sqrt{\sum_{i = 1}^{n}\left( a_{i} - b_{i} \right)^{2}} > ``` # apaDistances.FromSimilarities(Similarities) URL: https://www.andreassteiner.net/help/apadistances.fromsimilarities/ ## Result Derives a distance matrix from a similarity matrix. ## Syntax *Similarities*: n x n similarity matrix # apaDistances.Mahalanobis(X, Y) URL: https://www.andreassteiner.net/help/apadistances.mahalanobis/ ## Result Returns the Mahalanobis distance of each observation of a data matrix X from the mean of a data matrix Y. ## Syntax *X*: r x c matrix of observations in dataset X *Y*: r x c matrix of observations in dataset Y ## Remarks Uses the sample covariance matrix (denominator n − 1). # apaDistances.Mahalanobis.CriticalValue(X, Y, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apadistances.mahalanobis.criticalvalue/ ## Result Returns the critical value of the Mahalanobis distance at a given confidence level. ## Syntax *X*: r x c matrix of observations in dataset X *Y*: r x c matrix of observations in dataset Y *ConfidenceLevel*: confidence level, e.g. 95% # apaDistances.Manhattan(DataMatrix) URL: https://www.andreassteiner.net/help/apadistances.manhattan/ ## Result Derives the Manhattan distance matrix from a data matrix. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series ## Algorithm > > ``` math > d = \sum_{i = 1}^{n}\left| a_{i} - b_{i} \right| > ``` # apaDistances.Minkowski(DataMatrix, Order) URL: https://www.andreassteiner.net/help/apadistances.minkowski/ ## Result Derives the Minkowski distance matrix of order p from a data matrix, a generalized distance measure. ## Syntax *DataMatrix*: n x m data matrix containing m series with n observations each *Order*: order p: p = 1 is the Manhattan distance, p = 2 the Euclidean distance, p -\> infinity approaches the Chebyshev distance # apaDistances.WeightedOrUnweighted(Distances, IsWeighted) URL: https://www.andreassteiner.net/help/apadistances.weightedorunweighted/ ## Result Returns the distance matrix unchanged (weighted) or as an unweighted matrix with unit distances, i.e. 1 for each non-zero entry and 0 otherwise. ## Syntax *Distances*: n x n distance matrix *IsWeighted*: TRUE to keep the distance information, FALSE to use unit distances # apaDiversificationRatio(Weights, Covariances) URL: https://www.andreassteiner.net/help/apadiversificationratio/ ## Result Calculates the diversification ratio (Choueifaty/Coignard), i.e. the weighted average constituent volatility divided by the portfolio volatility. ## Syntax *Weights*: 1 x n vector of constituent weights *Covariances*: n x n covariance matrix ## Algorithm The weighted average asset volatility divided by the portfolio volatility. The weighted average asset volatility equals the portfolio volatility when all assets are perfectly correlated. ## Remarks Choueifaty, Yves, and Yves Coignard (2008): “Toward Maximum Diversification”, Journal of Portfolio Management, Fall 2008, 40-51. # apaDiversificationChart.CVar(nAssetsInPortfolio, Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apadiversificationchart.cvar/ ## Result Calculates the average CVaR of all possible equal-weighted portfolios. ## Syntax *nAssetsInPortfolio*: number of positions in the equal-weighted portfolios *Returns*: r x c data matrix, each column containing an asset time series *ConfidenceLevel*: confidence level of the CVaR, e.g. 0.95 # apaDiversificationChart.Kurt(nAssetsInPortfolio, Returns) URL: https://www.andreassteiner.net/help/apadiversificationchart.kurt/ ## Result Calculates the average, minimum and maximum sample excess kurtosis (as the Excel function KURT) of all possible equal-weighted portfolios, and the number of portfolios. ## Syntax *nAssetsInPortfolio*: number of positions in the equal-weighted portfolios *Returns*: r x c data matrix, each column containing an asset time series # apaDiversificationChart.Skew(nAssetsInPortfolio, Returns) URL: https://www.andreassteiner.net/help/apadiversificationchart.skew/ ## Result Calculates the average skewness of all possible equal-weighted portfolios. ## Syntax *nAssetsInPortfolio*: number of positions in the equal-weighted portfolios *Returns*: r x c data matrix, each column containing an asset time series ## Remarks Uses the sample skewness (as Excel SKEW). # apaDiversificationChart.DaR(nAssetsInPortfolio, Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apadiversificationchart.dar/ ## Result Calculates the average drawdown at risk (DaR) of all possible equal-weighted portfolios. ## Syntax *nAssetsInPortfolio*: number of positions in the equal-weighted portfolios *Returns*: r x c data matrix, each column containing an asset time series *ConfidenceLevel*: confidence level between 0% and 100%; 100% is the maximum drawdown, 50% the median drawdown # apaDiversificationChart.Volatility(nAssetsInPortfolio, Covariances) URL: https://www.andreassteiner.net/help/apadiversificationchart.volatility/ ## Result Calculates the average volatility of all possible equal-weighted portfolios. ## Syntax *nAssetsInPortfolio*: number of positions in the equal-weighted portfolios *Covariances*: n x n covariance matrix # apaDaR.Empirical(Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apadar.empirical/ ## Result Calculates the empirical drawdown at risk (DaR) from a time series matrix of returns. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *ConfidenceLevel*: confidence level, e.g. 95%. ## Remarks Drawdown at risk is a less known risk measure related to value at risk and maximum drawdown: DaR is a quantile of the vector of empirical drawdowns. A confidence level of 100% returns the maximum drawdown. The drawdowns used in the calculation of DaR are overlapping. # apaDaR.Empirical.ConfidenceIntervals(ConfidenceLevelDaR, TimeSeries, ConfidenceLevel, nSamples) URL: https://www.andreassteiner.net/help/apadar.empirical.confidenceintervals/ ## Result Calculates resampled confidence intervals for the empirical drawdown at risk (DaR). ## Syntax *ConfidenceLevelDaR*: confidence level of the DaR *TimeSeries*: n x 1 time series data vector *ConfidenceLevel*: confidence level of the interval *nSamples*: number of resampled datasets to generate # apaDrawdowns.Drawdown(Returns, IsSorted) URL: https://www.andreassteiner.net/help/apadrawdowns.drawdown/ ## Result Returns the vector of drawdowns of a time series, i.e. the losses from the previous local high-water mark before the local maximum loss has occurred. ## Syntax *Returns*: r x 1 vector of returns *IsSorted*: TRUE for values sorted in ascending order, FALSE for chronological order # apaDrawdowns.Drawdown.Max(Returns) URL: https://www.andreassteiner.net/help/apadrawdowns.drawdown.max/ ## Result Returns the maximum drawdown including its start, bottom and end date. ## Syntax *Returns*: r x 1 vector of returns # apaDrawdowns.Drawdown.Max.All(Returns, MinUnderwaterPeriodLength, IsSortedOtherwiseChronologial) URL: https://www.andreassteiner.net/help/apadrawdowns.drawdown.max.all/ ## Result Returns the maximum drawdowns in all underwater periods. ## Syntax *Returns*: r x 1 vector of returns *MinUnderwaterPeriodLength*: minimum underwater period length to consider *IsSortedOtherwiseChronologial*: TRUE for drawdowns sorted by size, FALSE for chronological order # apaDrawdowns.Drawdown.WithZeros(Returns) URL: https://www.andreassteiner.net/help/apadrawdowns.drawdown.withzeros/ ## Result Returns the drawdowns of a time series, i.e. the losses from the previous local high-water mark before the local maximum loss has occurred, with zeros for all other observations. ## Syntax *Returns*: r x 1 vector of returns # apaDrawdowns.Drawdown.Max.Expected(Mu, Sigma, T) URL: https://www.andreassteiner.net/help/apadrawdowns.drawdown.max.expected/ ## Result Returns the expected maximum drawdown of a geometric Brownian motion over a certain time period. ## Syntax *Mu*: expected return (drift) of the geometric Brownian motion *Sigma*: volatility of the geometric Brownian motion *T*: time horizon expressed in years (0.5 = six months, 10 = ten years) ## Algorithm The calculations are based on rather lengthy expressions and numerical procedures. See Ismail/Atiya/Pratap/Mostafa (2003): “On the Maximum Drawdown of a Brownian Motion” for details. ## Remarks The algorithm is very similar to the MATLAB function emaxdrawdown(). Differences are: 1) our approach is more accurate for very short and very long time horizons, 2) the output can be directly interpreted as a percentage drop from peak to following low. # apaDrawdowns.Highwatermark(Returns) URL: https://www.andreassteiner.net/help/apadrawdowns.highwatermark/ ## Result Returns the trajectory of the high-water mark. ## Syntax *Returns*: r x 1 vector of returns # apaDrawdowns.Recovery.WithZeros(Returns) URL: https://www.andreassteiner.net/help/apadrawdowns.recovery.withzeros/ ## Result Returns the recovery returns, i.e. the gains from the local maximum loss back to the previous high-water mark, with zeros for all other observations. ## Syntax *Returns*: r x 1 vector of returns # apaDrawdowns.Underwater(Returns, IsSorted) URL: https://www.andreassteiner.net/help/apadrawdowns.underwater/ ## Result Returns the underwater returns, i.e. the losses from the previous local high-water mark. ## Syntax *Returns*: r x 1 vector of returns *IsSorted*: TRUE for values sorted in ascending order, FALSE for chronological order # apaDrawdowns.Underwater.Paths(Returns, DoShowDateIndicesOtherwiseNot, MinUnderwaterPeriodLength, MinDrawdown, InitialValue, DoNotContinueAfterRecovery, DoNotShowRecovery) URL: https://www.andreassteiner.net/help/apadrawdowns.underwater.paths/ ## Result Returns all filtered historical underwater paths of a time series. ## Syntax *Returns*: r x 1 vector of returns *DoShowDateIndicesOtherwiseNot*: TRUE to show the date indices in the first row of the result matrix, FALSE to show the drawdowns only *MinUnderwaterPeriodLength*: minimum duration of the underwater periods selected *MinDrawdown*: minimum drawdown of the underwater periods selected *InitialValue*: starting value used in rebasing the returns (typically 1 or 100) *DoNotContinueAfterRecovery*: TRUE to stop each path once the recovery has taken place *DoNotShowRecovery*: TRUE to omit the recovery returns # apaDrawdowns.Underwater.Start(Returns, Threshold) URL: https://www.andreassteiner.net/help/apadrawdowns.underwater.start/ ## Result Returns an indicator vector with the start points of drawdowns of a certain size (1 if an underwater period starts, 0 otherwise). ## Syntax *Returns*: r x 1 vector of returns *Threshold*: minimum drawdown as a signed figure, e.g. -5% for a drawdown of 5% # apaDrawdowns.Underwater.WithZeros(Returns) URL: https://www.andreassteiner.net/help/apadrawdowns.underwater.withzeros/ ## Result Returns the underwater returns, i.e. the losses from the previous local high-water mark, with zeros for the observations above water. ## Syntax *Returns*: r x 1 vector of returns # apaEigenvalues(aMat) URL: https://www.andreassteiner.net/help/apaeigenvalues/ ## Result Calculates the eigenvalues of a symmetric matrix. ## Syntax *aMat*: n x n symmetric matrix, e.g. a covariance or correlation matrix. ## Algorithm Jacobi method. # apaEigenvalues.Diagonal(Matrix) URL: https://www.andreassteiner.net/help/apaeigenvalues.diagonal/ ## Result Calculates the eigenvalues of a symmetric matrix and returns them on the main diagonal of an n x n matrix of zeros. ## Syntax *Matrix*: n x n symmetric matrix, e.g. a covariance or correlation matrix ## Algorithm Jacobi method. # apaEigenvalues.Sorted(aMat) URL: https://www.andreassteiner.net/help/apaeigenvalues.sorted/ ## Result Calculates the eigenvalues of a symmetric matrix, sorted in descending order (largest eigenvalue first). ## Syntax *aMat*: n x n symmetric matrix, e.g. a covariance or correlation matrix. ## Algorithm Jacobi method. # apaEigenvalues.Sorted.Percent(Matrix) URL: https://www.andreassteiner.net/help/apaeigenvalues.sorted.percent/ ## Result Calculates the eigenvalues of a symmetric matrix as percentages of their sum, sorted in descending order (largest eigenvalue first). ## Syntax *Matrix*: n x n symmetric matrix, e.g. a covariance or correlation matrix. ## Algorithm Jacobi method. # apaEigenvalues.Sorted.Percent.Cumulative(Matrix) URL: https://www.andreassteiner.net/help/apaeigenvalues.sorted.percent.cumulative/ ## Result Calculates the cumulative percentage eigenvalues of a symmetric matrix, sorted in descending order (largest eigenvalue first). ## Syntax *Matrix*: n x n symmetric matrix, e.g. a covariance or correlation matrix. ## Algorithm Jacobi method. # apaEigenvectors(aMat) URL: https://www.andreassteiner.net/help/apaeigenvectors/ ## Result Calculates the eigenvectors of a symmetric matrix. ## Syntax *aMat*: n x n symmetric matrix, e.g. a covariance or correlation matrix. ## Algorithm Jacobi method. # apaEigenvectors.Sorted(aMat) URL: https://www.andreassteiner.net/help/apaeigenvectors.sorted/ ## Result Calculates the eigenvectors of a symmetric matrix, sorted by their eigenvalues (largest eigenvalue first). ## Syntax *aMat*: n x n symmetric matrix, e.g. a covariance or correlation matrix. ## Algorithm Jacobi method. # apaElasticGradientDescentRegression(Y, X, L1Penality, L2Penality) URL: https://www.andreassteiner.net/help/apaelasticgradientdescentregression/ ## Result Elastic gradient descent regression, which combines ridge regression and forward stagewise regression. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of explanatory variables *L1Penality*: k x 1 list of L1 penalties *L2Penality*: k x 1 list of L2 penalties # apaEntropy.Shannon(DataVector) URL: https://www.andreassteiner.net/help/apaentropy.shannon/ ## Result Calculates the Shannon entropy of a probability vector. ## Syntax *DataVector*: r x 1 vector of probabilities, all elements \>= 0 and summing to 1 ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image50.svg) ## Remarks - The data x is assumed to have the properties of a probability distribution or of weights: 0 ≤ x ≤ 1, sum(x) = 1. # apaEmpCdf(TimeSeries) URL: https://www.andreassteiner.net/help/apaempcdf/ ## Result Calculates the empirical cumulative distribution function (cdf) from time series data. ## Syntax *TimeSeries*: r x 1 vector containing a time series ## Algorithm Empirical cumulative probability = rank in ascending order / number of observations. # apaEmpCdf.FromValue(TimeSeries, X) URL: https://www.andreassteiner.net/help/apaempcdf.fromvalue/ ## Result Calculates the empirical cumulative distribution function (cdf) of a single value, given a vector of observations. ## Syntax *TimeSeries*: r x 1 vector of observations *X*: value at which the empirical cdf is evaluated # apaEmpCdf.ConfidenceBands(TimeSeries, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaempcdf.confidencebands/ ## Result Calculates the empirical cumulative distribution function (cdf) with upper and lower confidence bands from a time series data vector. ## Syntax *TimeSeries*: r x 1 vector containing a time series *ConfidenceLevel*: confidence level ## Algorithm Empirical cumulative probability = rank in ascending order / number of observations. # apaEmpInv(Observations, Probabilities) URL: https://www.andreassteiner.net/help/apaempinv/ ## Result Inverse empirical cumulative distribution function. Values between observations are linearly interpolated. ## Syntax *Observations*: r1 x c matrix of observations *Probabilities*: r2 x c matrix of probabilities to invert # apaEVT.TailIndex.HillMethod(Returns, m) URL: https://www.andreassteiner.net/help/apaevt.tailindex.hillmethod/ ## Result Estimates the tail index with the least-squares Hill method, i.e. a regression on the m largest losses. ## Syntax *Returns*: r x 1 vector of returns *m*: number of tail observations (largest losses) to use # apaExcessReturnOnVaR(PortfolioReturns, RiskfreeReturns, VaR) URL: https://www.andreassteiner.net/help/apaexcessreturnonvar/ ## Result Calculates the excess return on value at risk, a risk-adjusted performance measure, i.e. the average excess return divided by the absolute VaR. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *RiskfreeReturns*: r x 1 vector of riskfree returns (i.e. a time series) or a single riskfree rate *VaR*: value at risk of the portfolio, i.e. the left quantile of the return distribution ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image51.svg) # apaExponentialWeights(nObs, HalfLife) URL: https://www.andreassteiner.net/help/apaexponentialweights/ ## Result Generates a vector of exponential weights of a certain length with a certain half-life. ## Syntax *nObs*: number of observations *HalfLife*: half-life in number of observations, i.e. the observation whose weight is exactly half the weight of the most recent observation ## Algorithm wi = 2^((i − nObs) / HalfLife) / Σj 2^((j − nObs) / HalfLife), i = 1, …, nObs. The last (most recent) observation has the largest weight; the weights sum to one. # apaFirstPassageTime.Resampled.Cdf(Returns, TargetReturn, nSimulations, MaxHorizon) URL: https://www.andreassteiner.net/help/apafirstpassagetime.resampled.cdf/ ## Result Generates the cumulative distribution function (cdf) of first passage times by resampling empirical returns. ## Syntax *Returns*: r x 1 vector of returns *TargetReturn*: target (cumulative) return *nSimulations*: number of simulations to perform *MaxHorizon*: maximum number of observations to simulate # apaFirstPassageTime.Resampled.Pdf(Returns, TargetReturn, nSimulations, MaxHorizon) URL: https://www.andreassteiner.net/help/apafirstpassagetime.resampled.pdf/ ## Result Generates the probability density function (pdf) of first passage times by resampling empirical returns. ## Syntax *Returns*: r x 1 vector of returns *TargetReturn*: target (cumulative) return *nSimulations*: number of simulations to perform *MaxHorizon*: maximum number of observations to simulate # apaFactorModel.AssetCorrels(Betas, ResidualVariances, FactorCovarMat) URL: https://www.andreassteiner.net/help/apafactormodel.assetcorrels/ ## Result Calculates the asset correlation matrix implied by a factor model from betas, residual variances and factor covariances. ## Syntax *Betas*: n x k matrix of asset betas, each row containing an asset, each column a factor *ResidualVariances*: n x 1 vector of residual variances *FactorCovarMat*: k x k factor covariance matrix ## Algorithm The covariance matrix is calculated as B F B' + D (see apaFactorModel.AssetCovars) and converted into a correlation matrix. ## Remarks The function is volatile. # apaFactorModel.AssetCovars(Betas, ResidualVariances, FactorCovarMat) URL: https://www.andreassteiner.net/help/apafactormodel.assetcovars/ ## Result Calculates the asset covariance matrix implied by a factor model from betas, residual variances and factor covariances. ## Syntax *Betas*: n x k matrix of asset betas, each row containing an asset, each column a factor *ResidualVariances*: n x 1 vector of residual variances *FactorCovarMat*: k x k factor covariance matrix ## Algorithm The covariance matrix is calculated as B F B' + D, with B the matrix of betas, F the factor covariance matrix and D the diagonal matrix of residual variances. ## Remarks The function is volatile. # apaFactorModel.AssetReturns(Betas, ResidualReturns, FactorReturns) URL: https://www.andreassteiner.net/help/apafactormodel.assetreturns/ ## Result Calculates the expected asset returns implied by a factor model from betas, residual returns and factor returns. ## Syntax *Betas*: n x k matrix of asset betas, each row containing an asset, each column a factor *ResidualReturns*: n x 1 vector of residual returns (alphas) *FactorReturns*: k x 1 vector of factor returns ## Algorithm The expected returns are calculated as α + B f, with α the residual returns, B the matrix of betas and f the factor returns. ## Remarks The function is volatile. # apaFactorModel.AssetVariances(Betas, ResidualVariances, FactorCovarMat) URL: https://www.andreassteiner.net/help/apafactormodel.assetvariances/ ## Result Calculates the total asset variances implied by a factor model from betas, residual variances and factor covariances. ## Syntax *Betas*: n x k matrix of asset betas, each row containing an asset, each column a factor *ResidualVariances*: n x 1 vector of residual variances *FactorCovarMat*: k x k factor covariance matrix ## Algorithm The variances are the diagonal elements of B F B' + D, with B the matrix of betas, F the factor covariance matrix and D the diagonal matrix of residual variances. ## Remarks The function is volatile. # apaFarinelliTibilettiRatio(PortfolioReturns, UpperThreshold, UpperDegree, LowerThreshold, LowerDegree) URL: https://www.andreassteiner.net/help/apafarinellitibilettiratio/ ## Result Calculates the Farinelli-Tibiletti ratio, a risk-adjusted performance measure, i.e. the ratio of the upper and lower partial moments of given degrees. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *UpperThreshold*: return threshold for the upper partial moment *UpperDegree*: degree of the upper partial moment *LowerThreshold*: return threshold for the lower partial moment *LowerDegree*: degree of the lower partial moment ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image52.svg) ## Remarks Partial moments divide by the total number of observations n (population-type). # apaGainLossSpread(TimeSeries, Threshold) URL: https://www.andreassteiner.net/help/apagainlossspread/ ## Result Calculates the gain-loss spread, a risk measure, i.e. the average return at or above the threshold minus the average return below the threshold. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *Threshold*: return threshold. Either a single value or a vector with one entry per return (r x 1 or 1 x r). ## Algorithm Arithmetic difference between the expected gain and the expected loss relative to a threshold. ## Remarks Returns equal to the threshold count as gains. A threshold vector of any other size returns an error, and \#N/A is returned if there are no gains or no losses. See the SSRN working paper by Javier Estrada (2009): “The Gain-Loss Spread: A New and Intuitive Measure of Risk”. # apaGainToPainRatio(Returns) URL: https://www.andreassteiner.net/help/apagaintopainratio/ ## Result Returns the gain-to-pain ratio, the sum of all returns divided by the sum of losses. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. ## Algorithm Gain-to-pain ratio = Σ r / Σ max(−r, 0) = profit factor − 1 (Schwager). ## Remarks The result is a 1 x c row vector with one value per column of Returns. \#N/A is returned if there are no negative returns. # apaGARCH11.Volatility.Estimate(Returns) URL: https://www.andreassteiner.net/help/apagarch11.volatility.estimate/ ## Result Estimates the GARCH(1,1) parameters alpha and beta by maximum likelihood, with variance targeting. ## Syntax *Returns*: r x 1 vector of returns ## Algorithm The standard GARCH(1,1) model is assumed: ![Formula](https://www.andreassteiner.net/help/assets/eq/image53.svg) Additionally, the unconditional (long-term) variance is assumed to equal the sample variance (denominator n − 1) of the full return time series (variance targeting). # apaGARCH11.Volatility.Conditional(Returns, Alpha, Beta) URL: https://www.andreassteiner.net/help/apagarch11.volatility.conditional/ ## Result Calculates the current conditional (short-term) volatility implied by the GARCH(1,1) parameters. ## Syntax *Returns*: r x 1 vector of returns *Alpha*: GARCH(1,1) alpha parameter (weight of the squared innovations) *Beta*: GARCH(1,1) beta parameter (weight of the lagged variance) ## Algorithm The standard GARCH(1,1) model is assumed: ![Formula](https://www.andreassteiner.net/help/assets/eq/image53.svg) Additionally, the unconditional (long-term) variance is assumed to equal the sample variance (denominator n − 1) of the full return time series (variance targeting). ## Remarks The recursion starts at the unconditional volatility, so the result equals the last value in the third column of apaGARCH11.Volatility.Chart. # apaGARCH11.Volatility.Conditional.Forward(nPeriods, ConditionalVolatility, UnconditionalVolatility, Alpha, Beta) URL: https://www.andreassteiner.net/help/apagarch11.volatility.conditional.forward/ ## Result Calculates the GARCH(1,1) forward volatility nPeriods ahead. ## Syntax *nPeriods*: number of periods ahead *ConditionalVolatility*: current conditional volatility *UnconditionalVolatility*: unconditional (long-run) volatility *Alpha*: GARCH(1,1) alpha parameter (weight of the squared innovations) *Beta*: GARCH(1,1) beta parameter (weight of the lagged variance) ## Algorithm The standard GARCH(1,1) model is assumed: ![Formula](https://www.andreassteiner.net/help/assets/eq/image53.svg) The unconditional (long-run) volatility is an input parameter; no moments are estimated from data. The GARCH(1,1) forward volatility is calculated as: ![Formula](https://www.andreassteiner.net/help/assets/eq/image54.svg) # apaGARCH11.Volatility.Conditional.ExpectedForward(nPeriods, ConditionalVolatility, UnconditionalVolatility, Alpha, Beta) URL: https://www.andreassteiner.net/help/apagarch11.volatility.conditional.expectedforward/ ## Result Calculates the expected average GARCH(1,1) volatility over the next nPeriods, e.g. for the term structure of volatility. ## Syntax *nPeriods*: number of periods ahead *ConditionalVolatility*: current conditional volatility *UnconditionalVolatility*: unconditional (long-run) volatility *Alpha*: GARCH(1,1) alpha parameter (weight of the squared innovations) *Beta*: GARCH(1,1) beta parameter (weight of the lagged variance) ## Algorithm The standard GARCH(1,1) model is assumed: ![Formula](https://www.andreassteiner.net/help/assets/eq/image53.svg) The unconditional (long-run) volatility is an input parameter; no moments are estimated from data. The GARCH(1,1) expected forward volatility is calculated as: ![Formula](https://www.andreassteiner.net/help/assets/eq/image55.svg) ## Remarks If α + β = 1, the conditional variance does not revert to its long-run level, and the expected forward volatility equals the conditional volatility. # apaGARCH11.Volatility.Chart(Returns, Alpha, Beta) URL: https://www.andreassteiner.net/help/apagarch11.volatility.chart/ ## Result Calculates a three-column matrix with 1) the squared innovations, 2) the unconditional volatility and 3) the conditional GARCH(1,1) volatility for each observation. Useful for creating charts. ## Syntax *Returns*: r x 1 vector of returns *Alpha*: GARCH(1,1) alpha parameter (weight of the squared innovations) *Beta*: GARCH(1,1) beta parameter (weight of the lagged variance) ## Algorithm The standard GARCH(1,1) model is assumed: ![Formula](https://www.andreassteiner.net/help/assets/eq/image53.svg) Additionally, the unconditional (long-term) variance is assumed to equal the sample variance (denominator n − 1) of the full return time series (variance targeting). # apaGARCH11.Volatility.Simulate(n, UnconditionalVolatility, Alpha, Beta) URL: https://www.andreassteiner.net/help/apagarch11.volatility.simulate/ ## Result Simulates a GARCH(1,1) process with zero mean and returns an n x 1 vector of simulated returns. ## Syntax *n*: number of observations to simulate *UnconditionalVolatility*: unconditional (long-run) volatility *Alpha*: GARCH(1,1) alpha parameter (weight of the squared innovations) *Beta*: GARCH(1,1) beta parameter (weight of the lagged variance) ## Algorithm The constant is derived from the unconditional volatility as ω = (1 − α − β) σ². ## Remarks α + β must be smaller than one for the process to be stationary. # apaGeneralizedRachevRatio(PortfolioReturns, ConfidenceLevelLosses, ConfidenceLevelGains, LowerPower, UpperPower) URL: https://www.andreassteiner.net/help/apageneralizedrachevratio/ ## Result Calculates the generalized Rachev ratio, a risk-adjusted performance measure, i.e. CVaG^UpperPower divided by CVaR^LowerPower. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *ConfidenceLevelLosses*: confidence level for the losses (CVaR), e.g. 0.95. *ConfidenceLevelGains*: confidence level for the gains (CVaG), e.g. 0.95. *LowerPower*: power applied to the CVaR of the losses *UpperPower*: power applied to the CVaG of the gains ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image56.svg) ## Remarks CVaG is the average of the returns above the ConfidenceLevelGains percentile (for 0.95 the best 5% of returns); CVaR is the average of the returns below the 1 − ConfidenceLevelLosses percentile (for 0.95 the worst 5%). # apaGiniMeanDifference(TimeSeries, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apaginimeandifference/ ## Result Calculates the Gini mean difference, i.e. the average absolute difference between all pairs of observations. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample figures (division by n-1), FALSE for population figures (division by n); default: FALSE ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image57.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image58.svg) # apaGPcdf(x, sigma, eta) URL: https://www.andreassteiner.net/help/apagpcdf/ ## Result Cumulative distribution function of the generalized Pareto distribution. ## Syntax *x*: value at which to evaluate the function, e.g. a loss (\> 0) *sigma*: scale parameter sigma *eta*: shape parameter eta ## Algorithm ## ![Formula](https://www.andreassteiner.net/help/assets/eq/image59.svg) # apaGPest(Returns) URL: https://www.andreassteiner.net/help/apagpest/ ## Result Estimates the scale parameter sigma and the shape parameter eta of the generalized Pareto distribution by maximum likelihood, for non-negative exceedances. ## Syntax *Returns*: r x 1 vector of non-negative exceedances (e.g. losses beyond a threshold). ## Algorithm A numerical maximum likelihood estimation is performed and the two parameters are returned in a column vector: Scale parameter (a dispersion measure comparable to volatility). Shape parameter (short-, thin- and fat-tailed distributions). # apaGPinv(p, sigma, eta) URL: https://www.andreassteiner.net/help/apagpinv/ ## Result Inverse cumulative distribution function of the generalized Pareto distribution. ## Syntax *p*: probability *sigma*: scale parameter sigma *eta*: shape parameter eta ## Algorithm x = σ/η · ((1 − p)^(−η) − 1) for η ≠ 0 and x = −σ·ln(1 − p) for η = 0. # apaGPpdf(x, sigma, eta) URL: https://www.andreassteiner.net/help/apagppdf/ ## Result Probability density function of the generalized Pareto distribution. ## Syntax *x*: value at which to evaluate the function, e.g. a loss (\> 0) *sigma*: scale parameter sigma *eta*: shape parameter eta ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image60.svg) # apaGPrnd(sigma, eta) URL: https://www.andreassteiner.net/help/apagprnd/ ## Result Returns a random drawing from a generalized Pareto distribution. ## Syntax *sigma*: scale parameter sigma *eta*: shape parameter eta # apaGPsim(n, sigma, eta) URL: https://www.andreassteiner.net/help/apagpsim/ ## Result Simulates random drawings from a generalized Pareto distribution. ## Syntax *n*: number of observations to simulate *sigma*: scale parameter sigma *eta*: shape parameter eta # apaGraph.AdjacencyMatrix.FromEdges(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.adjacencymatrix.fromedges/ ## Result Derives the adjacency matrix of a graph from an edge list. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.AdjacencyMatrix.FromIncidenceMatrix(IncidenceMatrix, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.adjacencymatrix.fromincidencematrix/ ## Result Derives the adjacency matrix of a graph from an incidence matrix. ## Syntax *IncidenceMatrix*: n x n incidence matrix *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.AdjacencyMatrix.ToSimilarities(AdjacencyMatrix, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.adjacencymatrix.tosimilarities/ ## Result Converts an adjacency matrix into a similarity matrix. ## Syntax *AdjacencyMatrix*: n x n adjacency matrix *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.BetweennessCentrality.FromEdges(Edges, NumberOfNodes, IsWeighted, IsRescaled) URL: https://www.andreassteiner.net/help/apagraph.betweennesscentrality.fromedges/ ## Result Calculates the betweenness centrality of the nodes of an undirected graph, weighted or unweighted, with Brandes’ algorithm. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE for weighted graphs, FALSE for unweighted graphs (unit weights) *IsRescaled*: TRUE to normalize by 2/((n-1)(n-2)) for undirected graphs ## Remarks If IsWeighted is TRUE, the shortest paths are determined from the distances in the third column of Edges; otherwise each edge has length 1. For graphs with two nodes or fewer, all betweenness values are 0. # apaGraph.Centralization.Freeman.FromEdges(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.centralization.freeman.fromedges/ ## Result Calculates Freeman’s centralization measure of a graph defined by an edge list. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.ClosenessCentrality.FromEdges(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.closenesscentrality.fromedges/ ## Result Calculates the closeness centrality of all nodes (vertices) of a graph defined by an edge list. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.Communities.CommunityAdjacencyMatrix(Edges, Communities) URL: https://www.andreassteiner.net/help/apagraph.communities.communityadjacencymatrix/ ## Result Returns the community adjacency matrix induced by a node-level graph and a community assignment. Entry (i,j) equals the number of edges connecting community i and community j. Rows and columns follow the sorted community indices. ## Syntax *Edges*: edge list; the first two columns contain the node indices, additional columns are ignored *Communities*: community membership table; the first column contains the 1-based community index, the second column the 1-based node index # apaGraph.Communities.CommunityAggregationMatrix(Communities) URL: https://www.andreassteiner.net/help/apagraph.communities.communityaggregationmatrix/ ## Result Returns the binary community aggregation matrix P, with communities in rows and nodes in columns. Entry P(k,i) equals 1 if node i belongs to community k, otherwise 0. Rows follow the sorted community indices and columns the sorted node indices of the community table. ## Syntax *Communities*: community membership table; the first column contains the 1-based community index, the second column the 1-based node index # apaGraph.Communities.GirvanNewman.ModularityPath(Edges, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.communities.girvannewman.modularitypath/ ## Result Returns the Girvan-Newman modularity path of a graph or MST. Each row contains the hierarchy level, the number of communities and the modularity at that level. If weighted, shortest paths use the edge distances, while modularity is evaluated on internally derived inverse-distance strengths. ## Syntax *Edges*: edge list; the first two columns contain the node indices, the third column the distance *IsWeighted*: TRUE to use the edge distances in the shortest-path betweenness, FALSE to use unit edge lengths # apaGraph.Communities.GirvanNewman(Edges, Layout, IsWeighted, ShowInfo) URL: https://www.andreassteiner.net/help/apagraph.communities.girvannewman/ ## Result Identifies Girvan-Newman communities. Returns one row per node with the community index, the node index and the x and y layout coordinates. ## Syntax *Edges*: edge list; the first two columns contain the node indices, the third column the distance *Layout*: node layout; the first column contains the x coordinates, the second column the y coordinates *IsWeighted*: TRUE to use the edge distances in the shortest-path betweenness, FALSE to use unit edge lengths *ShowInfo*: TRUE to show additional columns with community and node information: 1) average internal strength of the community, 2) internal strength of the node within the community, 3) external strength of the node # apaGraph.Communities.GirvanNewman.N(Edges, Layout, IsWeighted, N, ShowInfo) URL: https://www.andreassteiner.net/help/apagraph.communities.girvannewman.n/ ## Result Identifies Girvan-Newman communities for a fixed number of communities N. Returns one row per node with the community index, the node index and the x and y layout coordinates. ## Syntax *Edges*: edge list; the first two columns contain the node indices, the third column the distance *Layout*: node layout; the first column contains the x coordinates, the second column the y coordinates *IsWeighted*: TRUE to use the edge distances in the shortest-path betweenness, FALSE to use unit edge lengths *N*: target number of communities *ShowInfo*: TRUE to show additional columns with community and node information: 1) average internal strength of the community, 2) internal strength of the node within the community, 3) external strength of the node # apaGraph.Communities.CommunityGraph(Edges, Communities) URL: https://www.andreassteiner.net/help/apagraph.communities.communitygraph/ ## Result Returns the community graph induced by a node-level graph and a community assignment. Each output row contains the first community index, the second community index and the number of inter-community edges between them. ## Syntax *Edges*: edge list; the first two columns contain the node indices, additional columns are ignored *Communities*: community membership table; the first column contains the 1-based community index, the second column the 1-based node index # apaGraph.Communities.GreedyAgglomerative(Edges, Layout, ShowInfo) URL: https://www.andreassteiner.net/help/apagraph.communities.greedyagglomerative/ ## Result Returns greedy agglomerative modularity communities. The algorithm starts with singleton communities and repeatedly merges the pair with the highest modularity gain. Returns one row per node, including the layout coordinates. ## Syntax *Edges*: edge list; the first two columns contain the node indices, the third column the distance *Layout*: node layout; the first column contains the x coordinates, the second column the y coordinates *ShowInfo*: TRUE to show additional columns with community and node information: 1) average internal strength of the community, 2) internal strength of the node within the community, 3) external strength of the node ## Remarks Edge strengths are the inverse distances of the third column of Edges. At each step, the two communities a and b with the largest modularity gain ΔQ = W(a,b)/m - S(a)·S(b)/(2m²) are merged, where W(a,b) is the total strength of the edges between the two communities, S(a) and S(b) the total strengths of their nodes and m the total strength of all edges. The partition with the highest modularity along the merge path is returned; if several partitions have the same modularity, the one with fewer communities is chosen. # apaGraph.Communities.GreedyAgglomerative.N(Edges, Layout, N, ShowInfo) URL: https://www.andreassteiner.net/help/apagraph.communities.greedyagglomerative.n/ ## Result Returns greedy agglomerative modularity communities for a fixed number of communities N. The algorithm starts with singleton communities and repeatedly merges the pair with the highest modularity gain. Returns one row per node, including the layout coordinates. ## Syntax *Edges*: edge list; the first two columns contain the node indices, the third column the distance *Layout*: node layout; the first column contains the x coordinates, the second column the y coordinates *N*: target number of communities *ShowInfo*: TRUE to show additional columns with community and node information: 1) average internal strength of the community, 2) internal strength of the node within the community, 3) external strength of the node # apaGraph.Communities.GreedyAgglomerative.ModularityPath(Edges) URL: https://www.andreassteiner.net/help/apagraph.communities.greedyagglomerative.modularitypath/ ## Result Returns the greedy agglomerative modularity path. Each row contains the level index, the number of communities and the modularity after the best merge at that level. ## Syntax *Edges*: edge list; the first two columns contain the node indices, the third column the distance # apaGraph.Communities.CommunityLaplacian(Edges, Communities) URL: https://www.andreassteiner.net/help/apagraph.communities.communitylaplacian/ ## Result Returns the community Laplacian matrix L = D - A induced by a node-level graph and a community assignment, where A is the community adjacency matrix and D the diagonal matrix of community degrees. Rows and columns follow the sorted community indices. ## Syntax *Edges*: edge list; the first two columns contain the node indices, additional columns are ignored *Communities*: community membership table; the first column contains the 1-based community index, the second column the 1-based node index # apaGraph.Communities.CommunityLaplacian.Lifted(Edges, Communities) URL: https://www.andreassteiner.net/help/apagraph.communities.communitylaplacian.lifted/ ## Result Returns the lifted community Laplacian matrix P' \* Lc \* P in node (asset) space, where Lc is the community Laplacian and P the community aggregation matrix. The result can be added directly to other quadratic-term matrices in portfolio optimization. ## Syntax *Edges*: edge list; the first two columns contain the node indices, additional columns are ignored *Communities*: community membership table; the first column contains the 1-based community index, the second column the 1-based node index # apaGraph.DegreeCentrality.FromEdges(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.degreecentrality.fromedges/ ## Result Calculates the degree centrality of all nodes (vertices) of a graph defined by an edge list. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.DegreeMatrix(Distances) URL: https://www.andreassteiner.net/help/apagraph.degreematrix/ ## Result Derives the degree matrix from a distance (or similarity) matrix. ## Syntax *Distances*: n x n distance matrix # apaGraph.Eccentricity(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.eccentricity/ ## Result Calculates the eccentricity of each node of a graph, i.e. the largest shortest distance of the node to any other node. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances ## Remarks If the graph is not connected, the result is \#N/A. # apaGraph.Edges.FromAdjacencyMatrix(AdjacencyMatrix, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.edges.fromadjacencymatrix/ ## Result Derives the edge list of a graph from an adjacency matrix. ## Syntax *AdjacencyMatrix*: n x n adjacency matrix *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.Edges.FromClusteringResult(ClusteringResult) URL: https://www.andreassteiner.net/help/apagraph.edges.fromclusteringresult/ ## Result Converts the result of a hierarchical clustering algorithm into an edge list. ## Syntax *ClusteringResult*: output of a hierarchical clustering function, e.g. apaClustering.Hierarchical.SingleLinkage # apaGraph.Edges.FromClusterLabels(Labels) URL: https://www.andreassteiner.net/help/apagraph.edges.fromclusterlabels/ ## Result Converts cluster labels into the edge list of a tree. Returns one row per edge with the parent node index, the child node index and the edge weight, which is always 1. The result can be drawn with apaTree.Layout. ## Syntax *Labels*: n x 1 vector of cluster labels, e.g. from apaClustering.kMeans, or n x L matrix of nested groupings ordered from coarse to fine, e.g. from apaClustering.kMeans.Bisecting with DoShowStructureOtherwiseFinalGrouping = TRUE; columns containing only \#N/A are ignored ## Algorithm Every final cluster (the groups of the last column) becomes a node with its objects as children. For a vector, a root node is added above the clusters. For a matrix, each column must be a refinement of the previous one; a cluster that is divided between two columns becomes a parent node of its parts, while a cluster that is not divided remains the same node. If the first column contains more than one group, a root node is added above these groups. ## Remarks Node numbering follows the hierarchical clustering functions: the objects are numbered 1 to n in the order of the rows of Labels, the final clusters n + 1 to n + k in ascending order of their labels, followed by the higher-level nodes, and the root has the highest number. Since the node numbers are consecutive, row i of the output of apaTree.Layout contains the coordinates of node i. The labels can be any numbers; they only serve to identify the groups. An error is returned if the groupings are not nested. # apaGraph.Edges.FromDistanceMatrix(DistanceMatrix) URL: https://www.andreassteiner.net/help/apagraph.edges.fromdistancematrix/ ## Result Derives the edge list of a complete graph from a distance matrix. ## Syntax *DistanceMatrix*: n x n distance matrix # apaGraph.Edges.FromIncidenceMatrix(IncidenceMatrix, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.edges.fromincidencematrix/ ## Result Derives the edge list of a graph from an incidence matrix. ## Syntax *IncidenceMatrix*: n x n incidence matrix *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.Edges.Random(NumberOfNodes, \[GraphType\], \[Parameter\], \[DistanceType\], \[Seed\]) URL: https://www.andreassteiner.net/help/apagraph.edges.random/ ## Result Generates a random graph and returns it as an m x 3 edge list: node i, node j (1-based, i \< j, sorted by i and then j) and the distance between the two nodes. The edge list can be used directly as input of the apaGraph.Layout functions, apaGraph.MinimumSpanningTree.FromEdges and the other apaGraph functions that take an edge list. ## Syntax *NumberOfNodes*: number of nodes n, from 2 to 5000 *GraphType*: optional; 0 complete graph, 1 minimum spanning tree of the complete graph, 2 uniform random tree, 3 preferential-attachment tree, 4 Erdős–Rényi graph, 5 k-nearest-neighbour graph, 6 stochastic block model, 7 Watts–Strogatz small-world graph; default: 0 *Parameter*: optional; GraphType 4: edge probability p in (0, 1\], default 2 ln(n) / n (at most 1); GraphType 5: number of neighbours k from 1 to n - 1, default 3 (at most n - 1); GraphType 6: number of blocks from 1 to n, default min(3, n); GraphType 7: rewiring probability in \[0, 1\], default 0.1; ignored for the other graph types *DistanceType*: optional; 0 correlation distance sqrt(2(1 - ρ)), 1 Euclidean distance between random points in the unit square, 2 unit distances; default: 0 *Seed*: optional; integer seed of the random number generator, which makes the graph reproducible; default: empty, i.e. a new random graph whenever the function recalculates ## Algorithm First, distances between all pairs of nodes are generated. DistanceType 0: 250 observations of a factor model are simulated, x(i) = β(i) f + γ(i) g(b(i)) + σ(i) e(i), with a market factor f, standard normal factors and errors, market loadings β(i) uniform on \[0.3, 0.8\] and σ(i) = sqrt(1 - β(i)² - γ(i)²). Block factors g(b) with loadings γ(i) uniform on \[0.4, 0.7\] are used only for GraphType 6 (node i belongs to block (i - 1) mod number of blocks); the total factor variance is capped at 0.95. ρ is the sample correlation of the simulated observations. DistanceType 1: points are uniformly distributed in the unit square; for GraphType 6, they are normally distributed (standard deviation 0.08) around random block centres. DistanceType 2: the distances of DistanceType 0 are used to select the edges of GraphTypes 1 and 5, and all reported distances are set to 1. Then the edges are selected. GraphType 0: all n(n - 1)/2 pairs. GraphType 1: minimum spanning tree of the distances (Kruskal). GraphType 2: tree decoded from a random Prüfer sequence, so that all n^(n - 2) labelled trees are equally likely. GraphType 3: the nodes are added in random order, and each new node is attached to an existing node with a probability proportional to its degree, which produces hubs. GraphType 4: each pair is linked independently with probability p. GraphType 5: each node is linked to its k nearest nodes; the graph is the union of these links. GraphType 6: pairs within a block are linked with probability 0.5, pairs across blocks with probability min(0.5, 2 / n). GraphType 7: ring lattice in which each node is linked to its two nearest neighbours on each side; each link is rewired to a random node with the rewiring probability. Graphs of GraphTypes 4 to 7 that are not connected are connected by adding the shortest edges between their components (Kruskal on the distances), so that all n nodes are always part of a single connected graph. Trees (GraphTypes 1 to 3) have n - 1 edges. ## Remarks The function is not volatile, because the number of edges of GraphTypes 4 to 7 is random and Excel cannot spill a volatile array whose size changes between calculation passes (#SPILL!). Without Seed, a new graph is generated whenever the function recalculates, i.e. when an argument changes or with Ctrl+Alt+F9. The edge list must fit into the 1,048,576 rows of a worksheet; a complete graph allows at most 1,448 nodes. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.EdgeThinning.Build(Distances, Percent) URL: https://www.andreassteiner.net/help/apagraph.edgethinning.build/ ## Result Returns an edge list derived from the following thinning algorithm: start with all edges, sort them by distance (largest first), and delete an edge unless the deletion disconnects the graph. 100% returns the full graph with n\*(n-1)/2 edges, 0% returns the minimum spanning tree with n-1 edges. ## Syntax *Distances*: n x n distance matrix *Percent*: percentage of edges between the full graph (100%) and the minimum spanning tree (0%) # apaGraph.EigenvectorCentrality.FromEdges(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.eigenvectorcentrality.fromedges/ ## Result Calculates the eigenvector centrality (Bonacich power centrality) of all nodes (vertices) of a graph defined by an edge list. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.Fiedler.Value(LaplacianMatrix) URL: https://www.andreassteiner.net/help/apagraph.fiedler.value/ ## Result Returns the Fiedler value, i.e. the second smallest eigenvalue of the Laplacian matrix (algebraic connectivity). ## Syntax *LaplacianMatrix*: n x n Laplacian matrix # apaGraph.Fiedler.Vector(LaplacianMatrix) URL: https://www.andreassteiner.net/help/apagraph.fiedler.vector/ ## Result Returns the Fiedler vector, i.e. the eigenvector belonging to the second smallest eigenvalue of the Laplacian matrix. ## Syntax *LaplacianMatrix*: n x n Laplacian matrix # apaGraph.IncidenceMatrix.FromAdjacencyMatrix(AdjacencyMatrix, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.incidencematrix.fromadjacencymatrix/ ## Result Derives the incidence matrix of a graph from an adjacency matrix. ## Syntax *AdjacencyMatrix*: n x n adjacency matrix *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.IncidenceMatrix.FromEdges(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.incidencematrix.fromedges/ ## Result Derives the incidence matrix of a graph from an edge list. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.IsComplete(AdjacencyMatrix) URL: https://www.andreassteiner.net/help/apagraph.iscomplete/ ## Result Checks whether a graph is connected, i.e. whether every node can be reached from every other node. Returns TRUE or FALSE. ## Syntax *AdjacencyMatrix*: n x n adjacency matrix, weighted or unweighted ## Remarks An entry of AdjacencyMatrix counts as an edge if it is non-zero and finite; zero, empty or infinite entries mean that there is no edge. An edge is recognized if either A(i,j) or A(j,i) is set. # apaGraph.kNN.Build(Distances, OutputType, DoAddUnconnectedOnly) URL: https://www.andreassteiner.net/help/apagraph.knn.build/ ## Result Returns the edge list of the k-nearest-neighbor (kNN) graph at the smallest k at which the graph is connected, or that k. Each row of the edge list contains node i, node j (i \< j) and the distance d(i, j). ## Syntax *Distances*: n x n distance matrix *OutputType*: optional; 0 to return the edge list, 1 to return the k at which the graph first becomes connected; default: 0 *DoAddUnconnectedOnly*: optional; TRUE: from round k = 2 on, the k-th nearest neighbor of a node is only linked if the two nodes are not yet connected through a path; FALSE: all kNN edges; default: FALSE ## Algorithm The nearest neighbors of each node are sorted once by distance; ties are broken by the lower node index. Starting at k = 1, each round adds the k-th nearest neighbor of every node as an undirected edge, i.e. nodes i and j are linked if j is among the k nearest neighbors of i or i is among the k nearest neighbors of j. With DoAddUnconnectedOnly = TRUE, an edge from round k = 2 on is only added if its two nodes were not connected through a path after round k - 1; edges within an existing component are skipped. The connected components are tracked with a union-find structure, and the procedure stops at the first k for which a single component remains. ## Remarks Connected means that every node can reach every other node through a path, not that every pair of nodes is linked directly. The graph is always connected at k = n - 1. For n = 1, the k returned is 0 and the edge list is a row of \#N/A. The edge list at the returned k equals the result of apaGraph.kNN.Build.K with that k and the same DoAddUnconnectedOnly. DoAddUnconnectedOnly does not change the returned k, only the number of edges. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.kNN.Build.K(Distances, K, DoAddUnconnectedOnly) URL: https://www.andreassteiner.net/help/apagraph.knn.build.k/ ## Result Returns the edge list of the k-nearest-neighbor (kNN) graph for a given k. Each row contains node i, node j (i \< j) and the distance d(i, j). ## Syntax *Distances*: n x n distance matrix *K*: number of nearest neighbors to consider, between 0 and n - 1 *DoAddUnconnectedOnly*: optional; TRUE: from round k = 2 on, the k-th nearest neighbor of a node is only linked if the two nodes are not yet connected through a path; FALSE: all kNN edges; default: FALSE ## Remarks Nodes i and j are linked if j is among the K nearest neighbors of i or i is among the K nearest neighbors of j; ties are broken by the lower node index. With DoAddUnconnectedOnly = TRUE, the graph is built in rounds k = 1 to K as in apaGraph.kNN.Build: from round k = 2 on, the k-th nearest neighbor of a node is only linked if the two nodes were not connected through a path after round k - 1. If the graph has no edges (K = 0 or a single node), the function returns a row of \#N/A. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.LaplacianMatrix(AdjacencyMatrix) URL: https://www.andreassteiner.net/help/apagraph.laplacianmatrix/ ## Result Returns the Laplacian matrix of a graph, also known as Kirchhoff matrix, from an adjacency matrix. ## Syntax *AdjacencyMatrix*: n x n adjacency matrix # apaGraph.LaplacianMatrix.RW(AdjacencyMatrix) URL: https://www.andreassteiner.net/help/apagraph.laplacianmatrix.rw/ ## Result Returns the random walk (or left) normalized Laplacian matrix of a graph from an adjacency matrix. ## Syntax *AdjacencyMatrix*: n x n adjacency matrix # apaGraph.LaplacianMatrix.Sym(AdjacencyMatrix) URL: https://www.andreassteiner.net/help/apagraph.laplacianmatrix.sym/ ## Result Returns the symmetric normalized Laplacian matrix of a graph from an adjacency matrix. ## Syntax *AdjacencyMatrix*: n x n adjacency matrix ## Remarks The symmetric normalized Laplacian is L = I - D^(-1/2) A D^(-1/2), where A is the adjacency matrix and D the diagonal matrix of node degrees (row sums of A, excluding the diagonal of A). The off-diagonal elements are -A(i,j)/sqrt(d(i)·d(j)) and the diagonal elements are 1. For isolated nodes (degree 0), the row and column are 0. # apaGraph.Layout.Circular(Edges, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.layout.circular/ ## Result Circular layout of a graph defined by an edge list. Returns a matrix with the node index in the first column and the x/y coordinates in the next two columns. ## Syntax *Edges*: edge list; the first two columns contain the node indices, an optional third column the weight *IsWeighted*: TRUE to use the edge weights, FALSE to use unit weights # apaGraph.Layout.Concentric(Edges, IsWeighted, CentralityMeasure) URL: https://www.andreassteiner.net/help/apagraph.layout.concentric/ ## Result Concentric layout of a graph defined by an edge list: the more central a node, the closer it is to the centre. Returns a matrix with the node index in the first column and the x/y coordinates in the next two columns. ## Syntax *Edges*: edge list; the first two columns contain the node indices, an optional third column the weight *IsWeighted*: TRUE to use the edge weights, FALSE to use unit weights *CentralityMeasure*: optional; centrality that determines the radius: 0 = degree, 1 = closeness, 2 = betweenness, 3 = eigenvector, 4 = eccentricity; default: 0 ## Remarks The centralities are computed as in apaGraph.DegreeCentrality.FromEdges, apaGraph.ClosenessCentrality.FromEdges, apaGraph.BetweennessCentrality.FromEdges, apaGraph.EigenvectorCentrality.FromEdges (absolute values) and apaGraph.Eccentricity, with the same IsWeighted. For eccentricity, a smaller value is more central, and the graph must be connected. The radius of a node with centrality c is (M - c)/(M - m), where M and m are the highest and lowest centrality, so the most central node is at the centre and the least central nodes are on the unit circle; nodes with equal centrality share a circle. If several nodes share the highest centrality, the radii are shifted outwards so that these nodes lie on an inner circle. If all centralities are equal, all nodes lie on the unit circle. The nodes are placed from the inside out. Each node is placed as close as possible to the mean angle of its neighbours already placed (nodes without placed neighbours follow a golden-angle sequence, starting at the top), while keeping a distance of at least 0.5·√(π/n) to the nodes already placed, where n is the number of nodes; if no position on its circle achieves this distance, the position with the largest distance is used. Only nodes that occur in the edge list are returned, sorted by node index. # apaGraph.Layout.ForceAtlas2(Edges, UseWeightsOtherwiseUnitWeights) URL: https://www.andreassteiner.net/help/apagraph.layout.forceatlas2/ ## Result ForceAtlas2 layout of an edge list. Returns a layout matrix with the node index in the first column and the X/Y coordinates in the next two columns. ## Syntax *Edges*: n x 3 edge list, the first two columns containing the node indices, the third column the distance between the two nodes (smaller = closer, e.g. sqrt(2(1-ρ)) for correlations ρ) *UseWeightsOtherwiseUnitWeights*: TRUE to use the third column as edge distances, so that more similar nodes are placed closer together; FALSE to use unit distances ## Algorithm The layout is calculated with the default parameters of apaGraph.Layout.ForceAtlas2.AllParams, except for the maximum number of iterations, which is set to 1000 times the number of nodes. ## Remarks ForceAtlas2 is a continuous force-directed layout algorithm by Jacomy et al., developed for the Gephi software. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.Layout.ForceAtlas2.AllParams(Edges, UseWeightsOtherwiseUnitWeights, SpringLength, Epsilon, RepulsionStrength, Iterations, Gravity, StrongGravityMode, OutboundAttractionDistribution, LinLogMode, PreventOverlap, NodeSize, InitialSpeed, InitialSpeedEfficiency) URL: https://www.andreassteiner.net/help/apagraph.layout.forceatlas2.allparams/ ## Result ForceAtlas2 layout of an edge list with an extended parameter set. Returns a layout matrix with the node index in the first column and the X/Y coordinates in the next two columns. ## Syntax *Edges*: n x 3 edge list, the first two columns containing the node indices, the third column the distance between the two nodes (smaller = closer, e.g. sqrt(2(1-ρ)) for correlations ρ) *UseWeightsOtherwiseUnitWeights*: TRUE to use the third column as edge distances, so that more similar nodes are placed closer together; FALSE to use unit distances *SpringLength*: spring length (scaling ratio). Default value: 1 *Epsilon*: convergence tolerance. Default value: 0.0001 *RepulsionStrength*: repulsion strength. Default value: number of nodes *Iterations*: maximum number of iterations. Default value: 500 times the number of nodes *Gravity*: gravity strength, i.e. attraction towards the center. Default value: 1 *StrongGravityMode*: TRUE to use the strong gravity mode, FALSE otherwise. Default value: FALSE *OutboundAttractionDistribution*: TRUE to distribute the attraction by outbound mass, FALSE otherwise. Default value: FALSE *LinLogMode*: TRUE to use the lin-log attraction mode, FALSE otherwise. Default value: FALSE *PreventOverlap*: TRUE to reduce node overlap, FALSE otherwise. Default value: FALSE *NodeSize*: node size used when overlap prevention is enabled. Default value: 0 *InitialSpeed*: initial speed. Default value: 1 *InitialSpeedEfficiency*: initial speed efficiency. Default value: 1 ## Algorithm Nodes repel each other proportionally to their degree, connected nodes attract each other and gravity pulls all nodes towards the center. In weighted mode, the distances are divided by their median and clipped to \[0.05, 20\]; the attraction along an edge is proportional to 1/distance. Duplicate edges keep the shortest distance. ## Remarks Non-positive values of RepulsionStrength and Iterations are replaced by their default values. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.Layout.ForceDirected(Edges, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.layout.forcedirected/ ## Result Force-directed layout of a graph defined by an edge list. Returns a matrix with the node index in the first column and the x/y coordinates in the next two columns. ## Syntax *Edges*: n x 3 edge list, the first two columns containing the node indices, the third column the distance between the two nodes (smaller = closer, e.g. sqrt(2(1-ρ)) for correlations ρ) *IsWeighted*: TRUE to use the third column as edge distances, so that more similar nodes are placed closer together; FALSE to use unit distances Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.Layout.ForceDirected.AllParams(Edges, IsWeighted, SpringLength, TimeStep, RepulsionForce, AttractionConstant, Damping, Iterations) URL: https://www.andreassteiner.net/help/apagraph.layout.forcedirected.allparams/ ## Result Force-directed layout of an edge list with all parameters exposed. Returns a layout matrix with the node index in the first column and the X/Y coordinates in the next two columns. ## Syntax *Edges*: n x 3 edge list, the first two columns containing the node indices, the third column the distance between the two nodes (smaller = closer, e.g. sqrt(2(1-ρ)) for correlations ρ) *IsWeighted*: TRUE to use the third column as edge distances, so that more similar nodes are placed closer together; FALSE to use unit distances *SpringLength*: rest length of the springs. Default value: 0.5 *TimeStep*: time step of the simulation. Default value: 1 *RepulsionForce*: strength of the repulsive force between nodes. Default value: 1 *AttractionConstant*: spring constant of the attractive force along edges. Default value: 0.05 *Damping*: damping factor applied to the node velocities. Default value: 0.7 *Iterations*: number of iterations. Default value: 2000 ## Algorithm The nodes are treated as charged particles repelling each other, the edges as springs attracting connected nodes. In weighted mode, the distances are divided by their median and clipped to \[0.05, 20\]. Each edge is a spring with rest length SpringLength x distance and stiffness AttractionConstant / distance², capped at 0.5 / degree of the larger-degree end node for numerical stability; shorter distances thus give stiffer springs. Repulsion acts only between unconnected nodes, so that complete graphs reproduce the distances and sparse graphs such as trees can unfold without tangling. Duplicate edges keep the shortest distance. ## Remarks apaGraph.Layout.ForceDirected uses the default values of all parameters. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.Layout.KamadaKawai(Edges, UseWeightsOtherwiseUnitWeights) URL: https://www.andreassteiner.net/help/apagraph.layout.kamadakawai/ ## Result Kamada-Kawai layout of a graph defined by an edge list. Returns a matrix with the node index in the first column and the x/y coordinates in the next two columns. ## Syntax *Edges*: n x 3 edge list, the first two columns containing the node indices, the third column the distance between the two nodes (smaller = closer, e.g. sqrt(2(1-ρ)) for correlations ρ) *UseWeightsOtherwiseUnitWeights*: TRUE to use the third column as edge distances (shortest-path costs), so that more similar nodes are placed closer together; FALSE to use unit distances ## Remarks The optimization stops early when the selected node can no longer move, since all further iterations would leave the layout unchanged. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.Layout.KamadaKawai.AllParams(Edges, UseWeightsOtherwiseUnitWeights, springLength, springStiffness, epsilon, Iterations) URL: https://www.andreassteiner.net/help/apagraph.layout.kamadakawai.allparams/ ## Result Kamada-Kawai layout of an edge list with all parameters exposed. Returns a layout matrix with the node index in the first column and the X/Y coordinates in the next two columns. ## Syntax *Edges*: n x 3 edge list, the first two columns containing the node indices, the third column the edge lengths (costs) used in weighted mode *UseWeightsOtherwiseUnitWeights*: TRUE to use the third column as edge lengths in the shortest-path distances d(i,j), FALSE to use unit edge lengths *springLength*: optional global length scale L \> 0. The ideal spring length between nodes i and j is l(i,j) = L \* d(i,j). Default value: 1 *springStiffness*: optional global spring constant K \> 0. The spring stiffness between nodes i and j is k(i,j) = K / d(i,j)². Default value: 1 *epsilon*: optional convergence tolerance ≥ 0, i.e. the iteration stops when the largest node energy gradient falls below this value. Default value: 0, i.e. iterate until no node moves any further *Iterations*: optional maximum number of outer iterations. Default value: 500 times the number of nodes ## Algorithm The graph-theoretic shortest-path distances d(i,j) between all nodes are calculated. ## Remarks apaGraph.Layout.KamadaKawai uses the default values of all parameters. Omitted or empty parameters take their default values. The optimization stops early when the selected node can no longer move, since all further iterations would leave the layout unchanged. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.Layout.Spectral(Edges, NumberOfNodes, IsWeighted, NoiseAmount) URL: https://www.andreassteiner.net/help/apagraph.layout.spectral/ ## Result Spectral layout of a graph defined by an edge list. Returns a matrix with the node index in the first column and the x/y coordinates in the next two columns. ## Syntax *Edges*: n x 3 edge list, the first two columns containing the node indices, the third column the distance between the two nodes (smaller = closer, e.g. sqrt(2(1-ρ)) for correlations ρ) *NumberOfNodes*: deprecated and ignored; the nodes are inferred from the edge list *IsWeighted*: TRUE to use the third column as edge distances, so that more similar nodes are placed closer together; FALSE to use unit distances *NoiseAmount*: amount of noise added to the coordinates; 0 adds no noise, larger values add more noise In weighted mode, the distances are divided by their median and clipped to \[0.05, 20\] and converted into similarities 1/distance, which are the entries of the weighted adjacency matrix used for the graph Laplacian. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.Layout.TutteEmbedding(Edges) URL: https://www.andreassteiner.net/help/apagraph.layout.tutteembedding/ ## Result Layout of a planar graph defined by an edge list, based on the Tutte embedding algorithm (unweighted only). ## Syntax *Edges*: edge list; the first two columns contain the node indices, the third column the weight Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.Layout.YifanHu(Edges, UseWeightsOtherwiseUnitWeights) URL: https://www.andreassteiner.net/help/apagraph.layout.yifanhu/ ## Result Yifan Hu layout of an edge list. Returns a layout matrix with the node index in the first column and the X/Y coordinates in the next two columns. ## Syntax *Edges*: n x 3 edge list, the first two columns containing the node indices, the third column the distance between the two nodes (smaller = closer, e.g. sqrt(2(1-ρ)) for correlations ρ) *UseWeightsOtherwiseUnitWeights*: TRUE to use the third column as edge distances, so that more similar nodes are placed closer together; FALSE to use unit distances ## Algorithm The layout is calculated with the default parameters of apaGraph.Layout.YifanHu.AllParams, except for the maximum number of iterations, which is set to the larger of 100 and 20 times the number of edges. ## Remarks The Yifan Hu algorithm is a multilevel force-directed layout algorithm, suitable for large graphs. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.Layout.YifanHu.AllParams(Edges, UseWeightsOtherwiseUnitWeights, OptimalDistance, RelativeStrength, InitialStep, StepRatio, Iterations, AdaptiveCooling, ConvergenceTolerance, CoarsenMinSize, RefinementIterationsPerLevel, MaxLevels) URL: https://www.andreassteiner.net/help/apagraph.layout.yifanhu.allparams/ ## Result Yifan Hu multilevel layout of an edge list with an extended parameter set. Returns a layout matrix with the node index in the first column and the X/Y coordinates in the next two columns. ## Syntax *Edges*: n x 3 edge list, the first two columns containing the node indices, the third column the distance between the two nodes (smaller = closer, e.g. sqrt(2(1-ρ)) for correlations ρ) *UseWeightsOtherwiseUnitWeights*: TRUE to use the third column as edge distances, so that more similar nodes are placed closer together; FALSE to use unit distances *OptimalDistance*: preferred distance between nodes. Default value: 100 *RelativeStrength*: repulsion strength relative to attraction. Default value: 0.2 *InitialStep*: initial step size. Default value: 20 *StepRatio*: ratio used to update the step size. Default value: 0.95 *Iterations*: maximum number of iterations on the finest level. Default value: 500 times the number of nodes *AdaptiveCooling*: TRUE to use adaptive cooling, FALSE otherwise. Default value: TRUE *ConvergenceTolerance*: convergence tolerance. Default value: 1 *CoarsenMinSize*: minimum graph size, i.e. coarsening stops when the graph has this many nodes or fewer. Default value: 20 *RefinementIterationsPerLevel*: number of refinement iterations after prolongation at each intermediate level. Default value: 50 *MaxLevels*: maximum number of levels of the multilevel hierarchy. Default value: 10 ## Algorithm The graph is coarsened repeatedly by merging nodes, until it has CoarsenMinSize nodes or fewer or MaxLevels levels are reached. In weighted mode, the distances are divided by their median and clipped to \[0.05, 20\]; the attraction along an edge is proportional to 1/distance. Duplicate edges keep the shortest distance; when nodes are merged, the attraction strengths of the merged edges are added. ## Remarks A non-positive value of Iterations is replaced by its default value. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.MinimumSpanningTree(DistanceMatrix) URL: https://www.andreassteiner.net/help/apagraph.minimumspanningtree/ ## Result Returns the minimum spanning tree (MST) of a distance matrix as an edge list, using Kruskal’s algorithm. ## Syntax *DistanceMatrix*: n x n distance matrix ## Remarks Returns an (n-1) x 3 edge list: the first two columns contain the 1-based indices of the connected nodes and the third column their distance. Only the upper triangle of DistanceMatrix is used. Tied distances are allowed; in that case one of the possible minimum spanning trees is returned, all of which have the same total length. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.MinimumSpanningTree.FromEdges(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.minimumspanningtree.fromedges/ ## Result Returns the minimum spanning tree (MST) of a graph given as an edge list, using Kruskal’s algorithm. If the graph is not connected, the minimum spanning forest, i.e. one minimum spanning tree per connected component, is returned. ## Syntax *Edges*: graph as an edge list, i.e. an m x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes; additional columns are ignored *NumberOfNodes*: optional; total number of nodes; default: the highest node index in Edges *IsWeighted*: optional; TRUE to use the distances in the third column, FALSE to assume unit distances; default: TRUE ## Remarks Returns an edge list with one row per tree edge: the first two columns contain the 1-based indices of the connected nodes (smaller index first) and the third column their distance. A connected graph with n nodes gives n - 1 rows; a graph with c connected components gives n - c rows. Nodes without edges, e.g. when NumberOfNodes exceeds the highest node index in Edges, form their own components. If no tree edge exists, the function returns a row of \#N/A. Self-loops are ignored. Of several edges between the same two nodes, the shortest is used. Edges with the same distance are taken in the order of the edge list. With IsWeighted = FALSE, every spanning tree is minimal; the function then returns the spanning tree given by the order of the edge list. Applied to the output of apaGraph.kNN.Build or apaGraph.kNN.Build.K, the function returns the MST of the kNN graph. It equals the MST of all data points, i.e. apaGraph.MinimumSpanningTree, only if the kNN graph contains all of its edges; comparing the total distances of both trees shows whether this is the case. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaGraph.NeighboursFromEdges(Edges, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.neighboursfromedges/ ## Result Returns the neighbours of each node of a graph defined by an edge list. Each row contains the number of neighbours, the neighbour indices and the edge weights to the neighbours. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances ## Remarks Returns one row per node, from node 1 to the largest node index in Edges, and 1 + 2K columns, where K is the largest number of neighbours of any node. Column 1 contains the number of neighbours, columns 2 to K+1 the neighbour indices and columns K+2 to 2K+1 the corresponding edge weights (1 if IsWeighted is FALSE). Unused cells, e.g. for nodes with fewer than K neighbours or without any edge, show \#N/A. # apaGraph.Nodes.Central(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.nodes.central/ ## Result Returns the indices of the central nodes, i.e. the nodes with an eccentricity equal to the radius of the graph (smallest eccentricity). ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances ## Remarks If the graph is not connected, the result is \#N/A. # apaGraph.Nodes.Leaves(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.nodes.leaves/ ## Result Returns the indices of the leaf nodes, i.e. the nodes connected by one edge only. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances # apaGraph.Nodes.Peripheral(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.nodes.peripheral/ ## Result Returns the indices of the peripheral nodes, i.e. the nodes with an eccentricity equal to the diameter of the graph (largest eccentricity). ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances ## Remarks If the graph is not connected, the result is \#N/A. # apaGraph.ShortestDistances.All(AdjacencyMatrix) URL: https://www.andreassteiner.net/help/apagraph.shortestdistances.all/ ## Result Calculates the shortest distances between all pairs of nodes (vertices) of a graph with Dijkstra’s algorithm. ## Syntax *AdjacencyMatrix*: n x n adjacency matrix ## Remarks Entries of AdjacencyMatrix that are zero, empty or infinite mean that there is no edge. The distances to nodes that cannot be reached from a node are shown as \#N/A. # apaGraph.ShortestDistances.From(AdjacencyMatrix, StartIndex) URL: https://www.andreassteiner.net/help/apagraph.shortestdistances.from/ ## Result Calculates the shortest distances from a given node (vertex) to all other nodes of a graph with Dijkstra’s algorithm. ## Syntax *AdjacencyMatrix*: n x n adjacency matrix *StartIndex*: index of the starting node ## Remarks Entries of AdjacencyMatrix that are zero, empty or infinite mean that there is no edge. The distances to nodes that cannot be reached from a node are shown as \#N/A. # apaGraph.Text.Keyphrases(text, method, N) URL: https://www.andreassteiner.net/help/apagraph.text.keyphrases/ ## Result Builds a word co-occurrence graph from raw text and returns the top N keyphrases, ranked by graph-based word scores. ## Syntax *text*: raw input text *method*: word ranking method: Strength, Degree, Betweenness, Closeness, Eigenvector or PageRank *N*: number of top keyphrases to return # apaGraph.Text.Keysentence(text) URL: https://www.andreassteiner.net/help/apagraph.text.keysentence/ ## Result Returns ranked key sentences from a sentence-similarity graph using PageRank-style scoring. ## Syntax *text*: raw input text # apaGraph.Text.Keywords(text, method, N) URL: https://www.andreassteiner.net/help/apagraph.text.keywords/ ## Result Builds a word co-occurrence graph from raw text and returns the top N keywords, ranked by the selected graph centrality method. ## Syntax *text*: raw input text *method*: keyword ranking method: Strength, Degree, Betweenness, Closeness, Eigenvector or PageRank *N*: number of top keywords to return # apaGraph.Text.SentenceEdgeList(text) URL: https://www.andreassteiner.net/help/apagraph.text.sentenceedgelist/ ## Result Returns the weighted sentence-distance edge list extracted from raw text. ## Syntax *text*: raw input text # apaGraph.Text.SentenceList(text) URL: https://www.andreassteiner.net/help/apagraph.text.sentencelist/ ## Result Returns the indexed sentence list extracted from raw text, i.e. the nodes of the sentence graph. ## Syntax *text*: raw input text # apaGraph.Text.WordEdgeList(text, DoApplyLemmatization) URL: https://www.andreassteiner.net/help/apagraph.text.wordedgelist/ ## Result Builds a word co-occurrence graph from raw text and returns a three-column edge list: source index, target index and weight. The weight is a distance, not a similarity. ## Syntax *text*: raw input text *DoApplyLemmatization*: TRUE to apply lemmatization, FALSE otherwise # apaGraph.Text.WordList(text, DoApplyLemmatization) URL: https://www.andreassteiner.net/help/apagraph.text.wordlist/ ## Result Builds the node list from raw text and returns a two-column matrix: node index and node text. ## Syntax *text*: raw input text *DoApplyLemmatization*: TRUE to apply lemmatization, FALSE otherwise # apaGraph.Topology.AverageShortestPath(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.topology.averageshortestpath/ ## Result Calculates the average shortest path length of a graph, weighted or unweighted. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances ## Remarks If the graph is not connected, the result is \#N/A. # apaGraph.Topology.Diameter(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.topology.diameter/ ## Result Calculates the diameter of a graph, i.e. the largest shortest distance between any two nodes. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances ## Remarks If the graph is not connected, the result is \#N/A. # apaGraph.Topology.LeafFraction(Edges, NumberOfNodes) URL: https://www.andreassteiner.net/help/apagraph.topology.leaffraction/ ## Result Calculates the leaf fraction of a graph, i.e. the percentage of nodes with one connection only. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes # apaGraph.Topology.MeanOccupationLayer(Edges, NumberOfNodes) URL: https://www.andreassteiner.net/help/apagraph.topology.meanoccupationlayer/ ## Result Calculates the mean occupation layer of a graph relative to its central node, the node with the most connections. Returns a 1 x 3 vector with the index of the central node, its number of connections and the mean occupation layer. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes ## Remarks The mean occupation layer follows Onnela et al. (2003): each node is assigned a level equal to the number of edges on its shortest path to the central node, which has level 0. The mean occupation layer is the average level of all nodes, l = (1/N) Σ level(i). Edge distances are not used. If several nodes have the most connections, the one with the smallest mean occupation layer is chosen, and remaining ties are resolved by the smaller node index. If the graph is not connected, the mean occupation layer is \#N/A. # apaGraph.Topology.Overlap(Edges1, Edges2) URL: https://www.andreassteiner.net/help/apagraph.topology.overlap/ ## Result Counts the number of connections n which occur in both of two graphs with n1 and n2 connections. 2 \* n / (n1 + n2) gives the percentage overlap. ## Syntax *Edges1*: first graph as an edge list, an n x 3 or n x 2 matrix *Edges2*: second graph as an edge list, an n x 3 or n x 2 matrix # apaGraph.Topology.Radius(Edges, NumberOfNodes, IsWeighted) URL: https://www.andreassteiner.net/help/apagraph.topology.radius/ ## Result Calculates the radius of a graph, i.e. the smallest eccentricity of all nodes. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances ## Remarks If the graph is not connected, the result is \#N/A. # apaGraph.Topology.TotalWeight(Edges, NumberOfNodes, IsWeighted, IsStandard) URL: https://www.andreassteiner.net/help/apagraph.topology.totalweight/ ## Result Calculates the total weight of a graph, i.e. the sum of all edge weights. Unit weights are used when IsWeighted is FALSE. If IsStandard is TRUE, the total weight is divided by the number of nodes. ## Syntax *Edges*: graph as an edge list, i.e. an n x 3 data matrix, the first two columns containing the node indices and the third column the distance between the two nodes *NumberOfNodes*: total number of nodes *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances *IsStandard*: TRUE to divide the total weight by the number of nodes # apaGraph.TriangulatedMaximallyFiltered(DistanceMatrix) URL: https://www.andreassteiner.net/help/apagraph.triangulatedmaximallyfiltered/ ## Result Finds the triangulated maximally filtered graph (TMFG) of a distance matrix and returns it as an edge list. ## Syntax *DistanceMatrix*: n x n distance matrix # apaHalflifeToLambda(HalfLife) URL: https://www.andreassteiner.net/help/apahalflifetolambda/ ## Result Converts a half-life into the corresponding exponential decay factor lambda. ## Syntax *HalfLife*: half-life in number of observations, i.e. the observation with half the weight of the most recent one # apaHenrikssonMerton.Alpha(Returns, BenchmarkReturns, RiskfreeReturns) URL: https://www.andreassteiner.net/help/apahenrikssonmerton.alpha/ ## Result Returns the Henriksson-Merton alpha, i.e. the selectivity intercept of the market-timing regression. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *BenchmarkReturns*: r x 1 vector (shared by all columns) or r x c matrix of benchmark returns *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 ## Algorithm OLS regression r − rf = α + β·(rb − rf) + γ·max(0, rf − rb) + ε (Henriksson and Merton 1981). ## Remarks The result is a 1 x c row vector with one value per column of Returns. \#N/A is returned if the regressors are collinear, e.g. if the excess benchmark return never changes sign. See also apaHenrikssonMerton.Gamma and apaTreynorMazui.Alpha. # apaHenrikssonMerton.Gamma(Returns, BenchmarkReturns, RiskfreeReturns) URL: https://www.andreassteiner.net/help/apahenrikssonmerton.gamma/ ## Result Returns the Henriksson-Merton market-timing coefficient γ. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *BenchmarkReturns*: r x 1 vector (shared by all columns) or r x c matrix of benchmark returns *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 ## Algorithm Same regression as apaHenrikssonMerton.Alpha; the result is the coefficient γ on max(0, rf − rb). ## Remarks The result is a 1 x c row vector with one value per column of Returns. A positive γ indicates timing ability: the portfolio behaves like the benchmark plus a put option on it. \#N/A is returned if the regressors are collinear. # apaHerfindahlIndex(Data) URL: https://www.andreassteiner.net/help/apaherfindahlindex/ ## Result Calculates the Herfindahl (Herfindahl-Hirschman) index, a measure of concentration. ## Syntax *Data*: r x 1 vector of data, e.g. weights # apaHerfindahlIndex.Normalized(Data) URL: https://www.andreassteiner.net/help/apaherfindahlindex.normalized/ ## Result Calculates the normalized Herfindahl (Herfindahl-Hirschman) index, a measure of concentration between zero and one. ## Syntax *Data*: r x 1 vector of data, e.g. weights # apaHistogram(TimeSeries, nBins, MinVal, MaxVal) URL: https://www.andreassteiner.net/help/apahistogram/ ## Result Prepares the inputs to draw a histogram and returns rich information to characterize empirical distributions: ## Syntax *TimeSeries*: r x 1 data vector *nBins*: number of bins *MinVal*: lower value of the first bin, i.e. the left end of the distribution *MaxVal*: upper value of the last bin, i.e. the right end of the distribution ## Remarks The value reported in “Bins” is the middle of the bin. The normal density and the kernel bandwidth use the sample standard deviation (denominator n − 1). # apaHurstExponent(Returns) URL: https://www.andreassteiner.net/help/apahurstexponent/ ## Result Calculates the Hurst exponent (rescaled range analysis), an indicator whether a time series exhibits mean reversion or momentum. Values above 0.5 indicate trending, values below 0.5 mean-reverting behavior. ## Syntax *Returns*: r x 1 vector of returns ## Remarks The rescaled range uses the sample standard deviation (denominator n − 1). # apaHPFilter(TimeSeries, Lambda) URL: https://www.andreassteiner.net/help/apahpfilter/ ## Result Applies the Hodrick-Prescott filter to a time series and returns the trend component. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *Lambda*: smoothing parameter (common practice is 1600 for quarterly, 100 for annual and 14'400 for monthly data) ## Algorithm Assuming that a time series y_(t) consists of a trend tau_(t) and a cyclical component c_(t), the Hodrick-Prescott filter determines tau_(t) such that… ![Formula](https://www.andreassteiner.net/help/assets/eq/image61.svg) ## Remarks See the econometric literature for details. The HP filter is frequently used in business cycle analysis (e.g. determination of the output gap). As a rule of thumb, Lambda is typically set to 1600 for quarterly data. # apaHPFilter.Boosted(TimeSeries, Lambda, m) URL: https://www.andreassteiner.net/help/apahpfilter.boosted/ ## Result Applies the boosted Hodrick-Prescott filter to a time series and returns the trend component. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *Lambda*: smoothing parameter (common practice is 1600 for quarterly, 100 for annual and 14'400 for monthly data) *m*: number of boosting iterations; m = 0 calculates the simple HP-filtered time series without boosting # apaHull.Convex(X, Y) URL: https://www.andreassteiner.net/help/apahull.convex/ ## Result Selects the points of a set of two-dimensional observations (X,Y) which constitute the convex hull. ## Syntax *X*: r x 1 vector of observations in dataset X *Y*: r x 1 vector of observations in dataset Y ## Remarks Efficient frontiers in return/risk space are convex hulls. # apaIchimoku.Chart(TimeSeries) URL: https://www.andreassteiner.net/help/apaichimoku.chart/ ## Result Calculates the inputs needed for an Ichimoku Kinko Hyo chart. ## Syntax *TimeSeries*: r x 1 data vector containing a time series (e.g. prices). ## Algorithm Returns an array with eight columns: 1\. Price 2\. Tenkan 3\. Kijun 4\. Chikou 5\. Senkou A 6\. Senkou B 7\. Upper Cloud Boundary 8\. Lower Cloud Boundary ## Remarks \ # apaImputation.Delete(DataMatrix) URL: https://www.andreassteiner.net/help/apaimputation.delete/ ## Result (Listwise) deletion: handles missing observations by excluding incomplete data records. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical # apaImputation.Interpolate.Linear(DataMatrix, MaxGapSize) URL: https://www.andreassteiner.net/help/apaimputation.interpolate.linear/ ## Result Handles missing observations by linear interpolation between the last and the next existing observations. Missing first and last observations are ignored, and gaps larger than MaxGapSize are not interpolated. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical *MaxGapSize*: maximum number of missing observations to interpolate # apaImputation.Interpolate.Spline(DataMatrix, MaxGapSize) URL: https://www.andreassteiner.net/help/apaimputation.interpolate.spline/ ## Result Handles missing observations by natural spline interpolation between the last and the next existing observations. Gaps larger than MaxGapSize are not interpolated. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical *MaxGapSize*: maximum number of missing observations to interpolate # apaImputation.Last(DataMatrix) URL: https://www.andreassteiner.net/help/apaimputation.last/ ## Result Handles missing observations by replacing them with the last available observation. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical # apaImputation.Mean.Crosssection(DataMatrix) URL: https://www.andreassteiner.net/help/apaimputation.mean.crosssection/ ## Result Handles missing observations by replacing them with the cross-sectional mean of all series with observations. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical # apaImputation.Mean.Crosssection.Category(DataMatrix, CategoryLabels, MaxGapSize) URL: https://www.andreassteiner.net/help/apaimputation.mean.crosssection.category/ ## Result Handles missing observations by replacing them with the cross-sectional mean of the series in the same category with observations. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical *CategoryLabels*: 1 x n vector with category labels *MaxGapSize*: maximum gap size to fill in ## Remarks A missing (non-numeric) element is replaced by the mean of the numeric values of all series in the same category in that row if the run of consecutive missing elements containing it is at most MaxGapSize long. Runs at the start or end of a series count as gaps as well. Existing values are kept. If no series of the category has a value in that row, \#N/A is returned. CategoryLabels may be a row or a column vector with one label per column of DataMatrix. # apaImputation.Mean.Timeseries(DataMatrix) URL: https://www.andreassteiner.net/help/apaimputation.mean.timeseries/ ## Result Handles missing observations by replacing them with the unconditional mean of the respective series. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical ## Remarks The unconditional covariances are population covariances (denominator n). # apaImputation.Next(DataMatrix) URL: https://www.andreassteiner.net/help/apaimputation.next/ ## Result Handles missing observations by replacing them with the next available observation. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical # apaImputation.Regress.Linear(DataMatrix, MaxGapSize) URL: https://www.andreassteiner.net/help/apaimputation.regress.linear/ ## Result Imputes missing observations from a linear regression of the incomplete series on the other series. Gaps larger than MaxGapSize are not imputed. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical *MaxGapSize*: maximum number of missing observations to interpolate # apaImputation.Resample(DataMatrix) URL: https://www.andreassteiner.net/help/apaimputation.resample/ ## Result Handles missing observations by resampling the missing joint observations from the existing ones. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical # apaImputation.Resample.MVN(DataMatrix) URL: https://www.andreassteiner.net/help/apaimputation.resample.mvn/ ## Result Imputes missing observations with samples from a conditional multivariate normal distribution. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical ## Remarks The unconditional covariances are population covariances (denominator n). # apaImputation.Resample.MVN.FromUncondParams(DataMatrix, UnconditionalMeans, UnconditionalCovars) URL: https://www.andreassteiner.net/help/apaimputation.resample.mvn.fromuncondparams/ ## Result Imputes missing observations with samples from a conditional multivariate normal distribution with imposed means and covariances (which are not necessarily the means and covariances of the existing data). ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical *UnconditionalMeans*: 1 x n vector of the unconditional means *UnconditionalCovars*: n x n unconditional covariance matrix # apaImputation.Resample.MVT(DataMatrix, DegreesOfFreedom) URL: https://www.andreassteiner.net/help/apaimputation.resample.mvt/ ## Result Imputes missing observations with samples from a conditional multivariate (Student) t distribution. The degrees of freedom are imposed manually. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical *DegreesOfFreedom*: degrees of freedom. High values lead to convergence towards the multivariate normal distribution. ## Remarks The unconditional covariances are population covariances (denominator n). # apaImputation.Resample.MVT.FromUncondParams(DataMatrix, DegreesOfFreedom, UnconditionalMeans, UnconditionalCovars) URL: https://www.andreassteiner.net/help/apaimputation.resample.mvt.fromuncondparams/ ## Result Imputes missing observations with samples from a conditional multivariate (Student) t distribution with imposed means and covariances. The degrees of freedom are imposed manually. ## Syntax *DataMatrix*: data matrix; missing elements must be non-numerical *DegreesOfFreedom*: degrees of freedom. High values lead to convergence towards the multivariate normal distribution. *UnconditionalMeans*: 1 x n vector of the unconditional means for this data *UnconditionalCovars*: n x n unconditional covariance matrix for this data # apaInformationRatio.ActiveReturns(PortfolioReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/apainformationratio.activereturns/ ## Result Calculates the information ratio based on active returns, i.e. the average active return divided by the tracking error. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image62.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image63.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image64.svg) ## Remarks The tracking error is the sample volatility (denominator n − 1) of the active returns. # apaInformationRatio.ResidualReturns(PortfolioReturns, BenchmarkReturns, RiskfreeReturns) URL: https://www.andreassteiner.net/help/apainformationratio.residualreturns/ ## Result Calculates the information ratio based on the residual returns of the single-index model, i.e. alpha divided by residual risk. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *RiskfreeReturns*: r x 1 vector of riskfree returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image65.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image66.svg) ## Remarks Alpha is Jensen's alpha; the residual risk is calculated as in apaResidualRisk. The residual risk uses sample variances and covariance (denominator n − 1). # apaIsAutocorrelatedLjungBox(Returns, Lag, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaisautocorrelatedljungbox/ ## Result Ljung-Box test for statistically significant autocorrelations up to a certain lag. Returns TRUE if the null hypothesis of zero autocorrelation is rejected, FALSE otherwise, and the p-value. ## Syntax *Returns*: r x 1 vector of returns; must not be constant *Lag*: number of lags to test, between 1 and r − 1 *ConfidenceLevel*: confidence level strictly between 0 and 1, e.g. 0.95 ## Algorithm Q = n(n + 2)·Σk ρk² / (n − k), k = 1, …, *Lag*. Q is compared with the chi-square distribution with *Lag* degrees of freedom; the p-value is the right-tail probability of Q. ## Remarks The output is a 2 x 1 vector: TRUE/FALSE (TRUE if Q exceeds the chi-square critical value at ConfidenceLevel, i.e. zero autocorrelation is rejected) and the p-value. The autocorrelations ρk use the sum of squared deviations from the mean of the full series in the denominator, so the choice between sample and population moments cancels. A Lag outside 1 to r − 1, a ConfidenceLevel outside (0, 1) or a constant series returns an error message. # apaIsMeanDifferentFrom(Returns, ReferenceValue, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaismeandifferentfrom/ ## Result Two-sided t-test whether the mean of a data series statistically differs from a reference value. Returns a TRUE/FALSE indication and the p-value. ## Syntax *Returns*: r x 1 vector of returns *ReferenceValue*: reference value to test against *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm t = √n·(mean − *ReferenceValue*) / s, with s the sample standard deviation. The result is TRUE if \|t\| exceeds the two-sided critical value of the t distribution with n − 1 degrees of freedom. The p-value is 2·T(−\|t\|). # apaIsNormalJB(TimeSeries, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaisnormaljb/ ## Result Jarque-Bera test whether a time series is normally distributed. Returns a TRUE/FALSE indication and the p-value. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks The test statistic is assumed to be chi-square distributed, which is an approximation only. The larger the number of observations, the more accurate the approximation. The p-value is the right-tail probability of the JB statistic under the chi-square distribution with two degrees of freedom. Uses sample skewness and sample excess kurtosis (as Excel SKEW and KURT). # apaIsStructuralBreakChow(Y, X, Breakpoint, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaisstructuralbreakchow/ ## Result Performs a Chow test for a structural break in a linear regression at a given breakpoint. Returns a TRUE/FALSE indication and the p-value. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of explanatory variables, each column containing one variable *Breakpoint*: index of the observation at which the structural break is tested (“at the n-th observation”) *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm See any textbook on statistics. # apaIsUnitRootADF(ColumnVector, NumberOfLags, ConfidenceLevel, TestType) URL: https://www.andreassteiner.net/help/apaisunitrootadf/ ## Result Augmented Dickey-Fuller test for a unit root. Returns a TRUE/FALSE indication, the test statistic and the critical value. ## Syntax *ColumnVector*: r x 1 data vector containing a time series *NumberOfLags*: number of lagged differences to include *ConfidenceLevel*: confidence level, e.g. 0.95. *TestType*: 1 = with constant and time trend, 2 = with constant and no time trend, 3 = no constant and no time trend (random walk) ## Remarks Residual variance is SSE/(n − k), i.e. degrees-of-freedom corrected. # apaIsValidAllocation.Group.Bounds(Allocations, GroupMembership, GroupLowerBounds, GroupUpperBounds) URL: https://www.andreassteiner.net/help/apaisvalidallocation.group.bounds/ ## Result Validates whether allocations conform to the lower and upper bounds on group exposures. ## Syntax *Allocations*: r x c matrix of allocations, each row containing a different portfolio *GroupMembership*: k x c matrix of zeros and ones indicating group membership, each row containing a different group *GroupLowerBounds*: k x 1 vector of lower bounds *GroupUpperBounds*: k x 1 vector of upper bounds # apaIsValidAllocation.UCITS.51040(Allocations, DoShowDetails) URL: https://www.andreassteiner.net/help/apaisvalidallocation.ucits.51040/ ## Result Checks whether allocations conform to the UCITS 5/10/40 rule, i.e. that no single position is larger than 10% and that all positions larger than 5% do not add up to more than 40%. ## Syntax *Allocations*: r x c matrix of allocations, each row containing a different portfolio *DoShowDetails*: optional; TRUE to show the details: 1) number of positions \> 10%, 2) number of positions \> 5%, 3) sum of positions \> 5%; default: TRUE # apaIsValidAllocation.TE.UpperBound(Allocations, AssetReturns, BenchmarkReturns, TEUpperBound) URL: https://www.andreassteiner.net/help/apaisvalidallocation.te.upperbound/ ## Result Validates whether allocations conform to a given upper tracking error limit. ## Syntax *Allocations*: r x c matrix of allocations, each row containing a different portfolio *AssetReturns*: n x c matrix of asset returns, each column containing an asset return time series *BenchmarkReturns*: n x 1 vector of benchmark returns *TEUpperBound*: upper tracking error bound ## Remarks Uses the sample tracking error (denominator n − 1). # apaIsValidCF(Skewness, Kurtosis) URL: https://www.andreassteiner.net/help/apaisvalidcf/ ## Result Indicates whether a pair of skewness and excess kurtosis parameters results in a valid Cornish-Fisher expansion. Also returns the (excluded) lower and upper bounds for the excess kurtosis parameter, given the skewness parameter. ## Syntax *Skewness*: skewness parameter *Kurtosis*: excess kurtosis parameter ## Algorithm > ![Formula](https://www.andreassteiner.net/help/assets/eq/image67.svg) > > ![Formula](https://www.andreassteiner.net/help/assets/eq/image68.svg) # apaIsValidNIG(Skewness, Kurtosis) URL: https://www.andreassteiner.net/help/apaisvalidnig/ ## Result Indicates whether a pair of skewness and kurtosis (not excess kurtosis) values results in a valid NIG distribution. Also returns the (excluded) lower bound 3 + (5/3)·S² for the kurtosis, given the skewness S. ## Syntax *Skewness*: skewness *Kurtosis*: kurtosis (not excess kurtosis) ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image69.svg) # apaIVaR.Empirical.Discrete(Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaivar.empirical.discrete/ ## Result Calculates the empirical interim value at risk (interim VaR) at a given confidence level from a time series matrix of returns. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *ConfidenceLevel*: confidence level, e.g. 95%. ## Remarks Interim VaR is defined as the loss, measured relative to the beginning value, that occurs at any time up to the end of the investment period. \#N/A is returned if no observation lies in the tail. # apaJensenAlpha(PortfolioReturns, BenchmarkReturns, RiskfreeReturns) URL: https://www.andreassteiner.net/help/apajensenalpha/ ## Result Calculates Jensen’s alpha, a risk-adjusted performance measure. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *RiskfreeReturns*: r x 1 vector of riskfree returns (i.e. a time series) or a single riskfree rate ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image66.svg) ## Remarks Ratio of sample covariance to sample variance (denominator n − 1); population moments give the same beta. # apaKappa3(PortfolioReturns, Threshold) URL: https://www.andreassteiner.net/help/apakappa3/ ## Result Calculates the Kappa 3 ratio, a risk-adjusted performance measure, i.e. the average return in excess of the threshold divided by the cube root of the third lower partial moment. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *Threshold*: return threshold ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image70.svg) ## Remarks Partial moments divide by the total number of observations n (population-type). # apaKnee(DataVector, IsValueOtherwiseIndex) URL: https://www.andreassteiner.net/help/apaknee/ ## Result Finds the knee (or elbow) of a data vector, i.e. the observation with the largest distance to the line between the first and the last observation. ## Syntax *DataVector*: 1 x n or n x 1 data vector *IsValueOtherwiseIndex*: TRUE to return the knee value, FALSE to return its index in the data vector ## Algorithm \ # apaKurtosis.ExpWeighted(TimeSeries, HalfLife) URL: https://www.andreassteiner.net/help/apakurtosis.expweighted/ ## Result Calculates the exponentially weighted excess kurtosis (kurtosis minus 3) of each series of a time series matrix. ## Syntax *TimeSeries*: matrix containing time series data, each column a series *HalfLife*: half-life of the exponential weighting scheme ## Remarks Exponentially weighted moments; the weights sum to one (population-type, no small-sample correction). # apakNearestNeighbour.AdjacencyMatrix(k, DataMatrix, IsWeighted) URL: https://www.andreassteiner.net/help/apaknearestneighbour.adjacencymatrix/ ## Result Turns the k nearest neighbors of each data point into an adjacency matrix. ## Syntax *k*: number of nearest neighbors to consider, between 0 (zero matrix) and c - 1 *DataMatrix*: r x c data matrix *IsWeighted*: TRUE to use the distance information, FALSE to assume unit distances ## Remarks Data points i and j are linked if j is among the k nearest neighbors of i or i is among the k nearest neighbors of j, so the matrix is symmetric. With IsWeighted, the entries are Euclidean distances; data points with identical coordinates have distance 0 and therefore appear unlinked. Neighbors are ranked by Euclidean distance; ties are broken by the lower column index. A data point is never its own neighbor, even if other data points have the same coordinates. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apakNearestNeighbour.Classifier(k, KnownData, KnownCategoryLabels, UnknownData) URL: https://www.andreassteiner.net/help/apaknearestneighbour.classifier/ ## Result Classifies unknown data with the k-nearest neighbors (kNN) algorithm: each unknown data point receives the category label held by the majority of its k nearest known data points (Euclidean distance). Returns a 1 x m vector of category labels. ## Syntax *k*: number of nearest neighbors to consider, between 1 and the number of known data points c *KnownData*: r x c data matrix of known (labelled) data *KnownCategoryLabels*: 1 x c (or c x 1) vector of category labels of the known data *UnknownData*: r x m data matrix of unknown data to classify ## Remarks If several categories receive the same number of votes, the category of the nearest of the tied neighbors is chosen. With two categories, an odd k avoids ties. Ties in distance are broken by the lower column index of the known data. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apakNearestNeighbour.Distances.All(DataMatrix) URL: https://www.andreassteiner.net/help/apaknearestneighbour.distances.all/ ## Result Returns the distances of each data point to its nearest neighbors as a (c - 1) x c matrix; row k contains the distance of each data point to its k-th nearest neighbor. ## Syntax *DataMatrix*: r x c data matrix ## Remarks Neighbors are ranked by Euclidean distance; ties are broken by the lower column index. A data point is never its own neighbor, even if other data points have the same coordinates. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apakNearestNeighbour.Distances.Averages(DataMatrix, k) URL: https://www.andreassteiner.net/help/apaknearestneighbour.distances.averages/ ## Result Returns the average distance of each data point to its k nearest neighbors as a 1 x c vector. ## Syntax *DataMatrix*: r x c data matrix *k*: optional; number of nearest neighbors to average over, between 1 and c - 1, or 0 for all other data points; default: 0 ## Remarks Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apakNearestNeighbour.Distances.k(k, DataMatrix) URL: https://www.andreassteiner.net/help/apaknearestneighbour.distances.k/ ## Result Returns the distance of each data point to its k-th nearest neighbor (k-th kNN distance). ## Syntax *k*: rank of the neighbor, between 1 and c - 1 *DataMatrix*: r x c data matrix ## Remarks Neighbors are ranked by Euclidean distance; ties are broken by the lower column index. A data point is never its own neighbor, even if other data points have the same coordinates. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apakNearestNeighbour.Distances.k.Sorted(k, DataMatrix) URL: https://www.andreassteiner.net/help/apaknearestneighbour.distances.k.sorted/ ## Result Returns the distances of the data points to their k-th nearest neighbor, sorted in ascending order. To calibrate DBSCAN, use k = MinPoints - 1 (see apaClustering.DBSCAN.Epsilon). ## Syntax *k*: rank of the neighbor, between 1 and c - 1 *DataMatrix*: r x c data matrix ## Remarks Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apakNearestNeighbour.LocalOutlierFactor(k, DataMatrix) URL: https://www.andreassteiner.net/help/apaknearestneighbour.localoutlierfactor/ ## Result Calculates the local outlier factor (LOF) of each data point, based on its k nearest neighbors (Breunig et al., 2000). Returns a 1 x c vector. Values around 1 indicate a density similar to that of the neighbors; values clearly above 1 indicate outliers. ## Syntax *k*: number of nearest neighbors to consider, between 1 and c - 1 *DataMatrix*: r x c data matrix ## Algorithm The k-distance of a data point o is its distance to its k-th nearest neighbor. The reachability distance of p from o is max(k-distance(o), d(p, o)). The local reachability density lrd(p) is the inverse of the mean reachability distance of p from its k nearest neighbors. LOF(p) is the mean of lrd(o) / lrd(p) over the k nearest neighbors o of p. ## Remarks Exactly k neighbors are used. A constant of 1e-10 is added to the mean reachability distance, so that duplicate data points give finite values. Neighbors are ranked by Euclidean distance; ties are broken by the lower column index. A data point is never its own neighbor, even if other data points have the same coordinates. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apakNearestNeighbour.Points.Core(DataMatrix, Epsilon, MinPoints) URL: https://www.andreassteiner.net/help/apaknearestneighbour.points.core/ ## Result Classifies the data points as in the DBSCAN algorithm. Rows 1 to c - 1 contain the indices of the data points within distance Epsilon, nearest first (#N/A where there are none); the last row contains Core, Border or Outlier. ## Syntax *DataMatrix*: r x c data matrix. Objects are in columns, features in rows. *Epsilon*: parameter epsilon; a starting point is half the median Euclidean distance between all data points *MinPoints*: minimum number of points within distance Epsilon, including the point itself, for a point to be a core point ## Remarks The Epsilon-neighborhood includes the point itself, as in apaClustering.DBSCAN. Core: at least MinPoints points within Epsilon. Border: not a core point, but within Epsilon of a core point. Outlier: neither; these are the points that apaClustering.DBSCAN labels as noise. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apakNearestNeighbour.Points.Neighbour(DataMatrix) URL: https://www.andreassteiner.net/help/apaknearestneighbour.points.neighbour/ ## Result Returns the nearest neighbors of each data point as a (c - 1) x c matrix of column indices; row k contains the index of the k-th nearest neighbor. ## Syntax *DataMatrix*: r x c data matrix ## Remarks Neighbors are ranked by Euclidean distance; ties are broken by the lower column index. A data point is never its own neighbor, even if other data points have the same coordinates. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apakNearestNeighbour.Regression(k, DataMatrix) URL: https://www.andreassteiner.net/help/apaknearestneighbour.regression/ ## Result k-nearest neighbors (kNN) regression: for each data point, an OLS regression with a constant is fitted to the data point and its k nearest neighbors, and the fitted value at the data point is returned. Returns a 1 x c vector. ## Syntax *k*: number of nearest neighbors to consider, between the number of regressors r - 1 and c - 1 *DataMatrix*: r x c data matrix; row 1 contains the dependent variable, rows 2 to r the regressors. Objects are in columns. ## Remarks Neighbors are determined by the Euclidean distance in regressor space (rows 2 to r); ties are broken by the lower column index. Since the data point itself is part of each local regression, the fitted values are in-sample. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apakNearestNeighbour.Smoother(k, DataMatrix) URL: https://www.andreassteiner.net/help/apaknearestneighbour.smoother/ ## Result k-nearest neighbors (kNN) smoother: replaces each data point by the average of itself and its k nearest neighbors, feature by feature. Returns an r x c matrix. ## Syntax *k*: number of nearest neighbors to consider, between 1 and c - 1 *DataMatrix*: r x c data matrix ## Remarks Neighbors are ranked by Euclidean distance; ties are broken by the lower column index. A data point is never its own neighbor, even if other data points have the same coordinates. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaKurtosis.ConfidenceIntervals(TimeSeries, ConfidenceLevel, nSamples) URL: https://www.andreassteiner.net/help/apakurtosis.confidenceintervals/ ## Result Calculates the confidence intervals for the sample excess kurtosis (as the Excel function KURT) using a resampling methodology. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. *nSamples*: number of samples to generate # apaKurtosis.FromReturns(w, R) URL: https://www.andreassteiner.net/help/apakurtosis.fromreturns/ ## Result Calculates the portfolio kurtosis (not excess kurtosis) from the constituent weights and returns, using population moments. ## Syntax *w*: 1 x n vector of constituent weights *R*: nObs x n matrix of constituent returns, each column containing a time series # apaKurtosis.FromCokurts(w, Covars, Cokurts) URL: https://www.andreassteiner.net/help/apakurtosis.fromcokurts/ ## Result Calculates the portfolio kurtosis (not excess kurtosis) from the constituent weights, the covariance matrix and the cokurtosis matrix. ## Syntax *w*: 1 x n vector of constituent weights *Covars*: n x n covariance matrix *Cokurts*: cokurtosis matrix, e.g. from apaCokurts. # apaKurtosis.Population(TimeSeries) URL: https://www.andreassteiner.net/help/apakurtosis.population/ ## Result Calculates the population excess kurtosis (population version of the Excel function KURT). ## Syntax *TimeSeries*: r x c matrix of data, each column containing a data series # apaLicense.Code() URL: https://www.andreassteiner.net/help/apalicense.code/ ## Result Returns the license code assigned to the computer currently being used. ## Syntax This function has no arguments. # apaLicense.ExpiryDate() URL: https://www.andreassteiner.net/help/apalicense.expirydate/ ## Result Returns the expiry date of the subscription period of the current license code. ## Syntax This function has no arguments. # apaLicense.Computers.InUse() URL: https://www.andreassteiner.net/help/apalicense.computers.inuse/ ## Result Returns the number of computers assigned to the current license code. ## Syntax This function has no arguments. # apaLicense.Computers.Purchased() URL: https://www.andreassteiner.net/help/apalicense.computers.purchased/ ## Result Returns the number of computers purchased, i.e. the maximum number of computers which can be assigned to the current license code. ## Syntax This function has no arguments. # apaLicense.Computer.Name() URL: https://www.andreassteiner.net/help/apalicense.computer.name/ ## Result Returns the name of the computer currently being used. ## Syntax \ # apaLicense.Computer.Name.All() URL: https://www.andreassteiner.net/help/apalicense.computer.name.all/ ## Result Returns the names of all computers assigned to the current license code. ## Syntax \ # apaLicense.Computer.Deactivate() URL: https://www.andreassteiner.net/help/apalicense.computer.deactivate/ ## Result Deactivates the current computer such that the add-in can be activated and used on another computer. ## Syntax \ ## Remarks - Deactivation is permanent, i.e. the add-in cannot be used again on the deactivated computer at a later point. # apaLicense.Computer.Deactivate.Name(ComputerName) URL: https://www.andreassteiner.net/help/apalicense.computer.deactivate.name/ ## Result Deactivates a computer, identified by its name, from the current license. ## Syntax *ComputerName*: name of the computer to be deactivated ## Remarks - Deactivation is permanent, i.e. the add-in cannot be used again on the deactivated computer at a later point. # apaLcdf(x, mu, scale) URL: https://www.andreassteiner.net/help/apalcdf/ ## Result Cumulative distribution function of the logistic distribution. ## Syntax *x*: value at which to evaluate the function *mu*: location parameter *scale*: scale parameter # apaLpdf(x, mu, scale) URL: https://www.andreassteiner.net/help/apalpdf/ ## Result Probability density function of the logistic distribution. ## Syntax *x*: value at which to evaluate the function *mu*: location parameter *scale*: scale parameter # apaLinv(p, mu, scale) URL: https://www.andreassteiner.net/help/apalinv/ ## Result Inverse cumulative distribution function of the logistic distribution. ## Syntax *p*: probability *mu*: location parameter *scale*: scale parameter # apaLarg(mu, sigma) URL: https://www.andreassteiner.net/help/apalarg/ ## Result Derives the location and scale parameters of the logistic distribution from its mean and volatility. ## Syntax *mu*: mean *sigma*: volatility # apaLmom(mu, scale) URL: https://www.andreassteiner.net/help/apalmom/ ## Result Derives the moments of the logistic distribution from its location and scale parameters. The fourth moment is the kurtosis, not the excess kurtosis. ## Syntax *mu*: location parameter *scale*: scale parameter # apaLambdaToHalflife(Lambda) URL: https://www.andreassteiner.net/help/apalambdatohalflife/ ## Result Converts an exponential decay factor lambda into the corresponding half-life. ## Syntax *Lambda*: exponential decay factor lambda, between 0 and 1 # apaLayers.Convex.InnerData(X, Y, Percentile) URL: https://www.andreassteiner.net/help/apalayers.convex.innerdata/ ## Result Returns the inner data of a two-dimensional dataset (X,Y), defined by convex layers and a percentile threshold. ## Syntax *X*: r x 1 vector of observations in dataset X *Y*: r x 1 vector of observations in dataset Y *Percentile*: percentile which defines the inner data, i.e. the number of inner observations expressed as a percentage of the total number of observations # apaLayers.Convex.OuterData(X, Y, Percentile) URL: https://www.andreassteiner.net/help/apalayers.convex.outerdata/ ## Result Returns the outer data of a two-dimensional dataset (X,Y), defined by convex layers and a percentile threshold. ## Syntax *X*: r x 1 vector of observations in dataset X *Y*: r x 1 vector of observations in dataset Y *Percentile*: percentile which defines the inner data, i.e. the number of inner observations expressed as a percentage of the total number of observations # apaLayout.FromGrid(Lo, Hi, N) URL: https://www.andreassteiner.net/help/apalayout.fromgrid/ ## Result Derives an (X,Y) layout (grid) from lower and upper bounds for X and Y. ## Syntax *Lo*: 1 x n vector of lower bounds *Hi*: 1 x n vector of upper bounds *N*: 1 x n vector with the number of coordinates to generate # apaLayout.Match(Layout1, Layout2) URL: https://www.andreassteiner.net/help/apalayout.match/ ## Result Interpolates two 2D objects linearly such that they have the same number of points. Returns an n x 4 matrix, the first two columns containing the coordinates of the first object, the last two columns the coordinates of the second object. ## Syntax *Layout1*: n x 2 matrix of X and Y coordinates of object 1 *Layout2*: m x 2 matrix of X and Y coordinates of object 2 # apaLayout.Morph(Layout1, Layout2, Morphage) URL: https://www.andreassteiner.net/help/apalayout.morph/ ## Result Interpolates between two 2D objects from 0% (first object) to 100% (second object). The objects can be defined by different numbers of points. ## Syntax *Layout1*: n x 2 matrix of X and Y coordinates of object 1 *Layout2*: m x 2 matrix of X and Y coordinates of object 2 *Morphage*: percentage defining the position between object 1 (0%) and object 2 (100%) # apaLayout.Transform(Layout, scale, rotationAngleDegrees, flipHorizontal, flipVertical, Jitter, Shear) URL: https://www.andreassteiner.net/help/apalayout.transform/ ## Result Transforms a 2D layout: scaling, rotation, horizontal and vertical flipping, jitter and shear. ## Syntax *Layout*: n x 2 matrix of X and Y coordinates *scale*: scale factor *rotationAngleDegrees*: rotation angle in degrees, positive or negative *flipHorizontal*: TRUE to flip horizontally *flipVertical*: TRUE to flip vertically *Jitter*: jitter value between 0% and 100% *Shear*: shear value # apaLPM(Returns, Threshold, Degree) URL: https://www.andreassteiner.net/help/apalpm/ ## Result Calculates the lower partial moment (LPM) of a return time series. ## Syntax *Returns*: r x 1 vector of returns *Threshold*: return threshold *Degree*: degree (order) of the lower partial moment ## Remarks Partial moments divide by the total number of observations n (population-type). # apaLognormalToNormal.Mean(LognormalMean, LognormalVolatility) URL: https://www.andreassteiner.net/help/apalognormaltonormal.mean/ ## Result Converts the mean and volatility of a lognormal variable into the mean of the underlying normal variable. ## Syntax *LognormalMean*: mean of the lognormal variable *LognormalVolatility*: volatility of the lognormal variable ## Algorithm See our research note “Discrete and Continuous Correlation” for details. # apaLognormalToNormal.Volatility(LognormalMean, LognormalVolatility) URL: https://www.andreassteiner.net/help/apalognormaltonormal.volatility/ ## Result Converts the mean and volatility of a lognormal variable into the volatility of the underlying normal variable. ## Syntax *LognormalMean*: mean of the lognormal variable *LognormalVolatility*: volatility of the lognormal variable ## Algorithm See our research note “Discrete and Continuous Correlation” for details. # apaLognormalToNormal.Covariance(LognormalMean1, LognormalMean2, LognormalVolatility1, LognormalVolatility2, LognormalCovariance) URL: https://www.andreassteiner.net/help/apalognormaltonormal.covariance/ ## Result Converts the covariance of two lognormal variables into the covariance of the underlying normal variables. ## Syntax *LognormalMean1*: mean of the first lognormal variable *LognormalMean2*: mean of the second lognormal variable *LognormalVolatility1*: volatility of the first lognormal variable *LognormalVolatility2*: volatility of the second lognormal variable *LognormalCovariance*: covariance of the lognormal variables ## Algorithm See our research note “Discrete and Continuous Correlation” for details. # apaLognormalToNormal.Correlation(LognormalMean1, LognormalMean2, LognormalVolatility1, LognormalVolatility2, LognormalCorrelation) URL: https://www.andreassteiner.net/help/apalognormaltonormal.correlation/ ## Result Converts the correlation of two lognormal variables into the correlation of the underlying normal variables. ## Syntax *LognormalMean1*: mean of the first lognormal variable *LognormalMean2*: mean of the second lognormal variable *LognormalVolatility1*: volatility of the first lognormal variable *LognormalVolatility2*: volatility of the second lognormal variable *LognormalCorrelation*: correlation of the lognormal variables ## Algorithm See our research note “Discrete and Continuous Correlation” for details. # apaLongfallProb.Empirical(Returns, Threshold) URL: https://www.andreassteiner.net/help/apalongfallprob.empirical/ ## Result Calculates empirical longfall probabilities from a time series matrix of returns, i.e. the probabilities of returns at or above a certain threshold. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *Threshold*: return threshold ## Remarks Longfall observations are larger than or equal to the threshold. # apaLoss.Cdf(Returns, Threshold) URL: https://www.andreassteiner.net/help/apaloss.cdf/ ## Result Returns the sorted losses relative to a threshold and their empirical cumulative distribution. ## Syntax *Returns*: r x 1 vector of returns *Threshold*: return threshold # apaLoss.MeanExcess(Returns, Threshold) URL: https://www.andreassteiner.net/help/apaloss.meanexcess/ ## Result Returns the mean excess loss below the threshold. ## Syntax *Returns*: r x 1 return vector *Threshold*: threshold value # apaLoss(Returns, Threshold) URL: https://www.andreassteiner.net/help/apaloss/ ## Result Returns all losses, i.e. returns below the threshold. ## Syntax *Returns*: r x 1 return vector *Threshold*: threshold value # apaLoss.Sorted(Returns, Threshold) URL: https://www.andreassteiner.net/help/apaloss.sorted/ ## Result Returns all losses, i.e. returns below the threshold, sorted in ascending order. ## Syntax *Returns*: r x 1 return vector *Threshold*: threshold value # apaLoss.CountExcess(Returns, Threshold) URL: https://www.andreassteiner.net/help/apaloss.countexcess/ ## Result Counts the number of losses below the threshold. ## Syntax *Returns*: r x 1 return vector *Threshold*: threshold value # apaLogisticFunction(X) URL: https://www.andreassteiner.net/help/apalogisticfunction/ ## Result Calculates the standard logistic function 1/(1+exp(-X)). ## Syntax *X*: X value # apaLogisticFunction.FirstAntiderivative(X) URL: https://www.andreassteiner.net/help/apalogisticfunction.firstantiderivative/ ## Result Calculates the first antiderivative of the standard logistic function, ln(1+exp(X)). ## Syntax *X*: X value ## Remarks The function is evaluated as max(X, 0) + ln(1+exp(-\|X\|)), which is accurate for all values of X and does not overflow. # apaLogisticFunction.FirstDerivative(X) URL: https://www.andreassteiner.net/help/apalogisticfunction.firstderivative/ ## Result Calculates the first derivative of the standard logistic function, exp(X)/((1+exp(X))^2). ## Syntax *X*: X value ## Remarks The function is evaluated as exp(-\|X\|)/(1+exp(-\|X\|))^2, which is accurate for all values of X and does not overflow. # apaLogisticFunction.Generalized(X, LeftHorizontalAsymptotic, RightHorizontalAsymptotic, Curvature) URL: https://www.andreassteiner.net/help/apalogisticfunction.generalized/ ## Result Calculates the generalized logistic function LeftHorAsympt + (RightHorAsympt - LeftHorAsympt) / (1 + exp(-X(i,j)\*Curvature)). ## Syntax *X*: nRows x nCols matrix with X values *LeftHorizontalAsymptotic*: left horizontal asymptote *RightHorizontalAsymptotic*: right horizontal asymptote *Curvature*: curvature; values \> 1 increase the curvature, values \< 1 decrease the curvature, i.e. make the function more linear # apaLogisticFunction.Inverse(Y) URL: https://www.andreassteiner.net/help/apalogisticfunction.inverse/ ## Result Calculates the inverse of the standard logistic function, -ln((1/Y)-1). ## Syntax *Y*: Y value # apaMACD(TimeSeries, Faster, Slower, Signal) URL: https://www.andreassteiner.net/help/apamacd/ ## Result Calculates the moving average convergence/divergence (MACD) technical indicator. The columns of the result are (EMA stands for exponentially weighted moving average): ## Syntax *TimeSeries*: r x 1 data vector containing a time series (e.g. prices). *Faster*: number of periods of the faster exponential moving average, e.g. 12. *Slower*: number of periods of the slower exponential moving average, e.g. 26. *Signal*: number of periods of the signal line, e.g. 9. ## Remarks The most commonly used parameters are 12 periods for Faster, 26 periods for Slower and 9 periods for Signal. # apaMAD.Downside(Returns, Threshold) URL: https://www.andreassteiner.net/help/apamad.downside/ ## Result Calculates the downside mean absolute deviation of each series of a return matrix. Downside is defined as below the threshold. ## Syntax *Returns*: r x c matrix of returns, each column containing a series *Threshold*: threshold return # apaMAD.Mean(Returns) URL: https://www.andreassteiner.net/help/apamad.mean/ ## Result Calculates the mean absolute deviation from the arithmetic mean. ## Syntax *Returns*: r x c matrix of returns, each column containing a series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image71.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image72.svg) # apaMAD.Median(Returns) URL: https://www.andreassteiner.net/help/apamad.median/ ## Result Calculates the mean absolute deviation from the median. ## Syntax *Returns*: r x c matrix of returns, each column containing a series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image73.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image74.svg) # apaMagnitudeSurprise(Returns) URL: https://www.andreassteiner.net/help/apamagnitudesurprise/ ## Result Calculates the magnitude surprise (Kinlaw/Turkington), i.e. the turbulence ignoring correlations, for each observation. ## Syntax *Returns*: nObs x nAssets matrix of returns, each column containing a time series ## Algorithm Same formulas as in apaTurbulence, using different inputs. ## Remarks Kinlaw/Turkington (2013): “Correlation Surprise”, Journal of Asset Management: “a ‘correlation-blind’ turbulence score in which all off-diagonals in the covariance matrix are set to zero.” Uses population variances (denominator n). # apaMarchenkoPasturPDF(x, Q, Sigma) URL: https://www.andreassteiner.net/help/apamarchenkopasturpdf/ ## Result Probability density function of the Marchenko-Pastur distribution, i.e. the theoretical distribution of the eigenvalues of a random correlation matrix. ## Syntax *x*: eigenvalue at which to evaluate the function *Q*: ratio Q = nObs/nVariables *Sigma*: optional; standard deviation of the data; default: 1 # apaMarkov.Hidden.MVC.Estimate(DataMatrix, numStates, numSymbols, nMultiStarts, Seed) URL: https://www.andreassteiner.net/help/apamarkov.hidden.mvc.estimate/ ## Result Estimates a hidden Markov model with multivariate categorical emissions and returns the emission probabilities, the transition matrix and the state probabilities. The function is non-volatile. ## Syntax *DataMatrix*: r x c matrix of categorical data, each column containing a categorical series coded 1..numSymbols *numStates*: number of hidden states to impose *numSymbols*: number of categorical symbols per observed variable, coded from 1 to numSymbols *nMultiStarts*: optional; number of multi-starts. Default value: 1 (also used if omitted or below 1) *Seed*: optional; seed of the random number generator. Default value: 1 (also used if omitted or 0) ## Algorithm Inputs are validated: non-empty DataMatrix, numStates ≥ 1, numSymbols ≥ 2. # apaMarkov.Hidden.MVC.StateProbabilities URL: https://www.andreassteiner.net/help/apamarkov.hidden.mvc.stateprobabilities/ ## Result Returns the smoothed posterior (or filtered) state probabilities of a multivariate categorical hidden Markov model. ## Syntax StateProbabilityMatrix: $`T \times K`$matrix of state probabilities. ## Algorithm The state probability matrix is passed through for visualization and downstream analysis. # apaMarkov.Hidden.MVN.Estimate(DataMatrix, numStates, nMultiStarts, Seed) URL: https://www.andreassteiner.net/help/apamarkov.hidden.mvn.estimate/ ## Result Estimates a hidden Markov model with multivariate normal emissions and returns the parameters and the state probabilities. The function is non-volatile. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *numStates*: number of states to impose *nMultiStarts*: optional; number of multi-starts. Default value: 1 (also used if omitted or below 1) *Seed*: optional; seed of the random number generator. Default value: 1 (also used if omitted or 0) ## Algorithm Inputs are validated: non-empty DataMatrix, numStates ≥ 1. ## Remarks Covariances are maximum-likelihood (EM) estimates: probability-weighted, population-type, no small-sample correction. # apaMarkov.Hidden.MVN.LogLikelihoodSamples URL: https://www.andreassteiner.net/help/apamarkov.hidden.mvn.loglikelihoodsamples/ ## Result Returns the per-sample log-likelihoods under an estimated multivariate normal hidden Markov model. ## Syntax DataMatrix: $`T \times c`$data matrix used in HMM estimation. ModelOutput: MVN HMM estimation result (parameters and states). ## Algorithm For each observation, the emission and transition structure of the fitted model is evaluated to obtain the individual log-likelihood contribution. Return a $`T \times 1`$vector of per‑sample log‑likelihoods for diagnostics. # apaMarkov.Hidden.MVN.nObsRecommended(DataMatrix, numStates) URL: https://www.andreassteiner.net/help/apamarkov.hidden.mvn.nobsrecommended/ ## Result Returns the minimum number of observations recommended for estimating a multivariate normal hidden Markov model. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *numStates*: number of states to impose ## Algorithm The recommended minimum number of observations is computed as: ``` math 50 \times (\text{numSeries} \cdot \text{numStates} + 0.5 \cdot \text{numStates} \cdot (\text{numSeries}(\text{numSeries} + 1)) + \text{numStates}(\text{numStates} - 1)). ``` Return this scalar value. # apaMarkov.Hidden.MVN.Simulate(nObs, InitState, Means, Vols, CorrelsVecl, TransProbs, ShowStateOtherwiseReturnsOnly) URL: https://www.andreassteiner.net/help/apamarkov.hidden.mvn.simulate/ ## Result Simulates Gaussian emissions from a Markov regime switching process, i.e. multivariate normally distributed returns whose means, volatilities and correlations depend on a hidden state following a Markov chain. ## Syntax *nObs*: number of observations to generate *InitState*: initial state, i.e. the state preceding the first observation *Means*: nStates x nAssets matrix of means *Vols*: nStates x nAssets matrix of volatilities *CorrelsVecl*: nStates x (nAssets\*(nAssets-1)/2) matrix of correlations, each row containing the vecl correlation values of a state *TransProbs*: matrix of transition probabilities, each row summing to one (rows: current state, columns: next state) *ShowStateOtherwiseReturnsOnly*: optional; TRUE to show the simulated state in the first column, FALSE to return the simulated returns only; default: TRUE ## Algorithm For each observation, the next state is drawn from the transition probabilities of the previous state. ## Remarks The transition probability matrix is organized such that each row sums to one, consistent with apaMarkov.Simulate and with the transition matrices returned by the hidden Markov estimation functions. # apaMarkov.Hidden.MVN.StateProbabilities URL: https://www.andreassteiner.net/help/apamarkov.hidden.mvn.stateprobabilities/ ## Result Returns the smoothed posterior (or filtered) state probabilities of a multivariate normal hidden Markov model. ## Syntax StateProbabilityMatrix: $`T \times K`$matrix of state probabilities. ## Algorithm The state probability matrix is passed through as is, giving a table with one row per time step and one column per state probability. # apaMarkov.Hidden.MVT.Estimate(DataMatrix, numStates, nMultiStarts, Seed) URL: https://www.andreassteiner.net/help/apamarkov.hidden.mvt.estimate/ ## Result Estimates a hidden Markov model with multivariate Student t emissions and state-specific degrees of freedom, and returns the parameters and the state probabilities. The function is non-volatile. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *numStates*: number of states to impose *nMultiStarts*: optional; number of multi-starts. Default value: 1 (also used if omitted or below 1) *Seed*: optional; seed of the random number generator. Default value: 1 (also used if omitted or 0) ## Algorithm Inputs are validated: non-empty DataMatrix, numStates ≥ 1. The parameters are estimated with an expectation conditional maximization (ECM) algorithm. The E-step computes the smoothed state probabilities γ(t,k) with a scaled forward-backward recursion and, for each state, the latent precision weights u(t,k) = (ν(k) + p) / (ν(k) + δ(t,k)), where δ(t,k) is the Mahalanobis distance of observation t and p the number of series. The means and covariances are the γ·u-weighted averages. The degrees of freedom of state k solve −ψ(ν/2) + ln(ν/2) + 1 + Σ γ(t,k) (E\[ln u(t,k)\] − u(t,k)) / Σ γ(t,k) = 0, with ψ the digamma function, and are bounded to the interval \[2.01, 500\]. Transition and initial probabilities are updated from the smoothed transition and state probabilities. The iterations stop when the change of the log-likelihood falls below 1E-7. With numStates = 1 the same iterations start from the sample means and covariance matrix, giving the maximum likelihood fit of a single multivariate Student t distribution with estimated degrees of freedom. ## Remarks Covariances are maximum-likelihood (EM) estimates: probability-weighted, population-type, no small-sample correction. # apaMarkov.Hidden.MVT.StateProbabilities URL: https://www.andreassteiner.net/help/apamarkov.hidden.mvt.stateprobabilities/ ## Result Returns the smoothed posterior (or filtered) state probabilities of a multivariate Student t hidden Markov model. ## Syntax StateProbabilityMatrix: $`T \times K`$matrix of state probabilities. ## Algorithm The state probability matrix is passed through so that it can be charted or used for regime-based decision rules. # apaMarkov.Hidden.MVT.LogLikelihoodSamples URL: https://www.andreassteiner.net/help/apamarkov.hidden.mvt.loglikelihoodsamples/ ## Result Returns the per-sample log-likelihoods under an estimated multivariate Student t hidden Markov model with state-specific degrees of freedom. ## Syntax DataMatrix: $`T \times c`$data matrix used in HMM estimation. ModelOutput: MVT HMM estimation result. ## Algorithm The Student t emission densities and the transitions are computed for each observation under the fitted model. Return a $`T \times 1`$vector of log‑likelihood contributions. # apaMarkov.HigherOrder.StatePath.FromStatePath(StatePath, Order) URL: https://www.andreassteiner.net/help/apamarkov.higherorder.statepath.fromstatepath/ ## Result Derives the higher-order state path from a state path and an order. ## Syntax *StatePath*: n x 1 vector containing the state path *Order*: order of the new path ## Algorithm Transform the original first‑order state sequence into a higher‑order sequence by grouping consecutive states into composite states of length Order. For example, for order 2, the path $`\left( 1,2,3,\ldots\text{ } \right)`$becomes $`\left( 1\text{ }\text{⁣} - \text{ }\text{⁣}2,2\text{ }\text{⁣} - \text{ }\text{⁣}3,\ldots\text{ } \right)`$. Return the resulting higher‑order state path as numeric state identifiers. # apaMarkov.HigherOrder.StatePath.Labels.FromStatePath(StatePath, Order) URL: https://www.andreassteiner.net/help/apamarkov.higherorder.statepath.labels.fromstatepath/ ## Result Derives the higher-order state path from a state path and an order, returning formatted state labels. ## Syntax *StatePath*: n x 1 vector containing the state path *Order*: order of the new path ## Algorithm Higher-order composite states are constructed from consecutive observations of the original state path, as in apaMarkov.HigherOrder.StatePath.FromStatePath. Formatted labels are returned for the composite states, for example “1-2”, “2-3”, etc. # apaMarkov.IsIrreducible(TransProbs) URL: https://www.andreassteiner.net/help/apamarkov.isirreducible/ ## Result Checks whether a Markov chain is irreducible. ## Syntax *TransProbs*: matrix of transition probabilities, each row summing to one ## Algorithm A Markov chain is irreducible if every state can be reached from every other state in a finite number of steps. The function checks the communication structure implied by the transition matrix and returns TRUE if the chain consists of a single communicating class, otherwise FALSE. # apaMarkov.IsAperiodic(TransProbs, maxPower) URL: https://www.andreassteiner.net/help/apamarkov.isaperiodic/ ## Result Checks whether a Markov chain is aperiodic. ## Syntax *TransProbs*: matrix of transition probabilities, each row summing to one *maxPower*: optional; computational cutoff, i.e. the maximum matrix power. Default: 0 (5\*n^2 if the value is 0 or negative). Can be set as low as (n-1)^2+1 ## Algorithm For each state, examine return times using powers of the transition matrix. A chain is aperiodic if the greatest common divisor of possible return times is 1 for all states in the communicating class. The function uses repeated matrix powers up to maxPower to test this condition and returns TRUE if the chain is aperiodic, otherwise FALSE. # apaMarkov.IsErgodic(TransProbs, maxPower) URL: https://www.andreassteiner.net/help/apamarkov.isergodic/ ## Result Checks whether a Markov chain is ergodic. ## Syntax *TransProbs*: matrix of transition probabilities, each row summing to one *maxPower*: optional; computational cutoff, i.e. the maximum matrix power. Default: 0 (5\*n^2 if the value is 0 or negative). Can be set as low as (n-1)^2+1 ## Algorithm A finite Markov chain is ergodic if it is both irreducible and aperiodic. The function tests these properties and returns TRUE if both hold, otherwise FALSE. # apaMarkov.PathProbability.Conditional(StatePath, TransProbs) URL: https://www.andreassteiner.net/help/apamarkov.pathprobability.conditional/ ## Result Calculates the probability of an observed state path, given a transition probability matrix and conditional on the first state. ## Syntax *StatePath*: n x 1 or 1 x n vector of integer state labels from 1 to k, where k is the number of rows of TransProbs *TransProbs*: matrix of transition probabilities, each row summing to one ## Algorithm Inputs are validated: TransProbs is square and every element of StatePath is an integer between 1 and k. A path with a single observation has conditional probability 1. Treat the first state in StatePath as given. The conditional probability of the path is the product of all one-step transition probabilities along the path: ``` math P(s_{2},\ldots,s_{n} \mid s_{1}) = \prod_{t = 2}^{n}p_{s_{t - 1},s_{t}}. ``` Return the conditional path probability. # apaMarkov.PathProbability.Unconditional(StatePath, InitialStateDistribution, TransProbs) URL: https://www.andreassteiner.net/help/apamarkov.pathprobability.unconditional/ ## Result Calculates the unconditional probability of an observed state path. ## Syntax *StatePath*: n x 1 or 1 x n vector of integer state labels from 1 to k, where k is the number of rows of TransProbs *InitialStateDistribution*: 1 x k or k x 1 vector of first-state probabilities, non-negative and summing to one *TransProbs*: matrix of transition probabilities, each row summing to one ## Algorithm Inputs are validated: TransProbs is square, every element of StatePath is an integer between 1 and k, and InitialStateDistribution has k non-negative elements whose sum differs from one by at most 1e-6. Take the probability of the first state from the initial state distribution and multiply by the transition probabilities along the path: ``` math P(s_{1},\ldots,s_{n}) = \pi_{s_{1}}\prod_{t = 2}^{n}p_{s_{t - 1},s_{t}}. ``` Return the unconditional path probability. # apaMarkov.SemiHidden.Gaussian.Estimate(DataMatrix, numStates, maxDuration, nMultiStarts, Seed) URL: https://www.andreassteiner.net/help/apamarkov.semihidden.gaussian.estimate/ ## Result Estimates a Gaussian hidden semi-Markov model (HSMM) with explicit state duration distributions and returns the parameters, the duration statistics and the state probabilities. The function is non-volatile. ## Syntax *DataMatrix*: r x c matrix of return data, each column containing an asset return series *numStates*: number of states to impose *maxDuration*: maximum explicit state duration *nMultiStarts*: number of multi-starts. Default value: 1 (also used if omitted or below 1) *Seed*: seed of the random number generator. Default value: 1 (also used if omitted or 0) ## Algorithm Inputs are validated: non-empty DataMatrix, numStates ≥ 1, maxDuration ≥ 1. The parameters are estimated with an EM algorithm based on a segment forward-backward recursion. Each state has an explicit duration distribution over 1 to maxDuration observations, and a new segment always moves to a different state, so maxDuration is the longest possible regime length and should exceed the longest regime expected in the data. The first segment starts with the first observation and the last segment ends with the last observation. The E-step yields the posterior probabilities of each segment (state, duration, end time) and of each switch between states; the state means and covariances, the switching probabilities and the duration probabilities are their posterior-weighted averages. ## Remarks Covariances are maximum-likelihood (EM) estimates: probability-weighted, population-type, no small-sample correction. # apaMarkov.SecondOrder.Test(StatePath) URL: https://www.andreassteiner.net/help/apamarkov.secondorder.test/ ## Result Tests a first-order state path for the presence of second-order Markov dependence. ## Syntax *StatePath*: n x 1 vector containing the state path ## Algorithm The first-order Markov representation is compared with a second-order alternative based on the observed path, i.e. the test evaluates whether the transition behavior depends only on the current state or also on the previous state. The function returns a message summarizing the result of the test. # apaMarkov.Simulate(nObs, InitState, TransProbs) URL: https://www.andreassteiner.net/help/apamarkov.simulate/ ## Result Simulates a state path from a Markov chain defined by a transition probability matrix. ## Syntax *nObs*: number of observations to generate *InitState*: initial state (1-based index) *TransProbs*: matrix of transition probabilities, each row summing to one ## Algorithm Inputs are validated: nObs ≥ 1, TransProbs with rows summing to one. # apaMarkov.StateDuration.Analysis(StatePath, DoIgnoreFirstAndLastRun) URL: https://www.andreassteiner.net/help/apamarkov.stateduration.analysis/ ## Result Compares the empirical state durations with the geometric duration distribution implied by an estimated Markov chain. The input states must be a row or column vector. ## Syntax *StatePath*: n x 1 vector of states *DoIgnoreFirstAndLastRun*: TRUE to ignore the first and last runs of the state path, because they might be incomplete in a finite sample ## Algorithm The empirical run lengths of each state are estimated from StatePath, optionally excluding the first and last runs. ## Remarks The empirical duration variance is a sample variance (denominator n − 1). # apaMarkov.StateDurations.Expected(TransProbs) URL: https://www.andreassteiner.net/help/apamarkov.statedurations.expected/ ## Result Calculates the expected state durations implied by a transition probability matrix. ## Syntax *TransProbs*: matrix of transition probabilities, each row summing to one ## Algorithm For each state $`i`$, compute the expected duration from the diagonal transition probability $`p_{ii}`$. For a first‑order Markov chain, the expected duration in state $`i`$is ``` math E\lbrack D_{i}\rbrack = \frac{1}{1 - p_{ii}}. ``` Return the vector of expected state durations. # apaMarkov.StatePath.FromConditions(ConditioningVars, ThresholdVals) URL: https://www.andreassteiner.net/help/apamarkov.statepath.fromconditions/ ## Result Returns the Markov state path from conditioning variables and threshold values. ## Syntax *ConditioningVars*: nObs x nVars matrix of conditioning variables *ThresholdVals*: nThresholds x nVars matrix of threshold values, one column per variable ## Algorithm Thresholds can be unsorted, and the number of thresholds can differ between variables. # apaMarkov.StatePath.LabelsAndLocalStates(ConditioningVars, ThresholdVals) URL: https://www.andreassteiner.net/help/apamarkov.statepath.labelsandlocalstates/ ## Result Returns the Markov state path labels derived from conditioning variables and threshold values, plus all local states. The first column contains the state label, the following columns the local state of each conditioning variable. ## Syntax *ConditioningVars*: nObs x nVars matrix of conditioning variables *ThresholdVals*: nThresholds x nVars matrix of threshold values, one column per variable. Empty cells are ignored, i.e. the variables can have different numbers of thresholds ## Algorithm For each variable, the thresholds are sorted in ascending order. A variable with k thresholds has k + 1 local states. ## Remarks The number of columns of ThresholdVals must equal the number of conditioning variables. # apaMarkov.StationaryDistribution(TransProbs) URL: https://www.andreassteiner.net/help/apamarkov.stationarydistribution/ ## Result Calculates the stationary (steady state) distribution implied by a transition probability matrix. ## Syntax *TransProbs*: matrix of transition probabilities, each row summing to one ## Algorithm Find the probability vector $`\pi`$satisfying ``` math \pi P = \pi ``` subject to ``` math \sum_{i}^{}\pi_{i} = 1. ``` Return the stationary distribution as a vector. # apaMarkov.StationaryDistribution.ConfidenceIntervals(StatePath, Confidence, nResamples) URL: https://www.andreassteiner.net/help/apamarkov.stationarydistribution.confidenceintervals/ ## Result Calculates confidence intervals for the stationary (steady state) distribution by resampling from an observed state path. ## Syntax *StatePath*: n x 1 vector containing the state path *Confidence*: confidence level, e.g. 95%. *nResamples*: number of resamples to calculate ## Algorithm The transition probabilities are derived from the observed state path. # apaMarkov.TransitionProbabilityMatrix.FromStatePath(StatePath) URL: https://www.andreassteiner.net/help/apamarkov.transitionprobabilitymatrix.fromstatepath/ ## Result Derives the transition probability matrix from an observed trajectory of states. ## Syntax *StatePath*: column vector of 1-based state indices ## Algorithm Transitions from each state i to each state j in StatePath are counted. # apaMatrix.Adjugate(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.adjugate/ ## Result Returns the adjugate matrix of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Averages.Categories(DataMatrix, CategoryLabels) URL: https://www.andreassteiner.net/help/apamatrix.averages.categories/ ## Result Returns the equally-weighted arithmetic category means of a data matrix. The input data can be jagged. ## Syntax *DataMatrix*: jagged data matrix, each column containing a time series *CategoryLabels*: 1 x c vector of category labels ## Remarks Each column of DataMatrix is assigned to the category given in CategoryLabels. For each row, the equally-weighted arithmetic mean of the numeric values of each category is computed; empty cells, text, logical values and error values are skipped. The output has one row per row of DataMatrix and one column per category. A category without numeric values in a row returns \#N/A. CategoryLabels may be a row or a column vector with one label per column of DataMatrix. # apaMatrix.Averages.Categories.Weighted(DataMatrix, CategoryLabels, Weights) URL: https://www.andreassteiner.net/help/apamatrix.averages.categories.weighted/ ## Result Returns the weighted arithmetic category means of a data matrix. The columns are grouped by category label and the weighted mean within each category is computed using the weights. The input data can be jagged. ## Syntax *DataMatrix*: jagged data matrix, each column containing a time series *CategoryLabels*: 1 x c vector of category labels *Weights: 1 x c vector of weights, one per column of DataMatrix; within each category and row, the weights are rescaled to the series with numeric values* ## Algorithm Each column of DataMatrix is treated as one series and assigned to the category given in CategoryLabels. For each category and each row, the weighted arithmetic mean across all columns of that category is computed using the weights: ``` math {\overset{ˉ}{x}}_{w} = \frac{\sum_{i}^{}w_{i}x_{i}}{\sum_{i}^{}w_{i}}. ``` Missing observations or uneven column lengths of the jagged input are excluded from the calculation: empty cells, text, logical values and error values are skipped, and the weights of each category are rescaled to the series available in that row. A category without numeric values in a row returns \#N/A. CategoryLabels may be a row or a column vector with one label per column of DataMatrix. The result is the category mean matrix, with one column per category. # apaMatrix.Averages.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.averages.cols/ ## Result Returns the column averages of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Averages.Diagonal.Major(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.averages.diagonal.major/ ## Result Returns the averages of all major diagonals of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Averages.Diagonal.Minor(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.averages.diagonal.minor/ ## Result Returns the averages of all minor diagonals of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Averages.Rows(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.averages.rows/ ## Result Returns the row averages of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Center.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.center.cols/ ## Result Centers the columns of a matrix such that their means are zero. ## Syntax *Matrix*: nRows x nCols matrix of data ## Remarks x_center = x – x_mean # apaMatrix.Center.Double(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.center.double/ ## Result Centers the rows and columns of a matrix such that both their means are zero. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Center.Rows(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.center.rows/ ## Result Centers the rows of a matrix such that their means are zero. ## Syntax *Matrix*: nRows x nCols matrix of data ## Algorithm x_center = x – x_mean # apaMatrix.Centering(Size) URL: https://www.andreassteiner.net/help/apamatrix.centering/ ## Result Creates the n x n centering matrix H = I − (1/n)\*1\*1', with n = Size. ## Syntax *Size*: size n of the centering matrix ## Algorithm The elements are calculated as H(i,j) = δ(i,j) − 1/n, with δ(i,j) = 1 for i = j and 0 otherwise. ## Remarks Multiplying a data matrix X with H from the left, i.e. H\*X, subtracts the column means from all observations. # apaMatrix.ChangeSign.OffDiagonal.Major(DataMatrix) URL: https://www.andreassteiner.net/help/apamatrix.changesign.offdiagonal.major/ ## Result Changes the sign of the entries off the main diagonal of a matrix. ## Syntax *DataMatrix*: r x c data matrix # apaMatrix.ChangeSign.Diagonal.Major(DataMatrix) URL: https://www.andreassteiner.net/help/apamatrix.changesign.diagonal.major/ ## Result Changes the sign of the entries on the main diagonal of a matrix. ## Syntax *DataMatrix*: r x c data matrix # apaMatrix.Cholesky(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.cholesky/ ## Result Returns the Cholesky decomposition of a symmetric positive definite matrix. ## Syntax *Matrix*: n x n symmetric positive definite matrix # apaMatrix.Cofactors(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.cofactors/ ## Result Returns the matrix of all cofactors of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Concatenate.Cols(Matrix1, Matrix2) URL: https://www.andreassteiner.net/help/apamatrix.concatenate.cols/ ## Result Stacks two matrices in the horizontal direction. ## Syntax *Matrix1*: nRows1 x nCols1 matrix *Matrix2*: nRows1 x nCols2 matrix # apaMatrix.Concatenate.Rows(Matrix1, Matrix2) URL: https://www.andreassteiner.net/help/apamatrix.concatenate.rows/ ## Result Stacks two matrices in the vertical direction. ## Syntax *Matrix1*: nRows1 x nCols1 matrix *Matrix2*: nRows2 x nCols1 matrix # apaMatrix.ConditionNumber(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.conditionnumber/ ## Result Returns the condition number of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data ## Algorithm The condition number is a function of the ratio between the largest and the smallest eigenvalue of the input matrix: ![Formula](https://www.andreassteiner.net/help/assets/eq/image75.svg) # apaMatrix.Cumsum.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.cumsum.cols/ ## Result Returns the running cumulative sums by columns. ## Syntax *Matrix*: n x m data matrix # apaMatrix.Cumsum.Rows(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.cumsum.rows/ ## Result Returns the running cumulative sums by rows. ## Syntax *Matrix*: n x m data matrix # apaMatrix.Diagonal.Minor.Get(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.diagonal.minor.get/ ## Result Returns a vector containing the elements on the minor diagonal of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Diagonal.Minor.Nth.Get(Matrix, Idx) URL: https://www.andreassteiner.net/help/apamatrix.diagonal.minor.nth.get/ ## Result Returns a vector containing the elements on the n-th minor diagonal of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data *Idx*: integer index of the minor diagonal # apaMatrix.Diagonal.Minor.Put(Vector) URL: https://www.andreassteiner.net/help/apamatrix.diagonal.minor.put/ ## Result Returns a square matrix of zeros with the elements of a vector on the minor diagonal. ## Syntax *Vector*: 1 x nCols vector of data # apaMatrix.Diagonal.Major.Get(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.diagonal.major.get/ ## Result Returns a vector containing the elements on the major diagonal of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Diagonal.Major.Nth.Get(Matrix, Idx) URL: https://www.andreassteiner.net/help/apamatrix.diagonal.major.nth.get/ ## Result Returns a vector containing the elements on the n-th major diagonal of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data *Idx*: integer index of the major diagonal # apaMatrix.Diff.Cols(Matrix, n) URL: https://www.andreassteiner.net/help/apamatrix.diff.cols/ ## Result Returns the column-wise n-th differences of a data matrix. ## Syntax *Matrix*: data matrix *n*: order of differencing, i.e. number of times the data is differenced ## Algorithm The data is differenced n times, each time calculating x(t) − x(t−1) for each column. ## Remarks The result has n rows less than the input matrix. n = 0 returns a copy of the input. # apaMatrix.Difference(n) URL: https://www.andreassteiner.net/help/apamatrix.difference/ ## Result Generates the (first) difference matrix. When multiplied with a data vector, the resulting vector contains the first differences. ## Syntax *n*: dimension of the difference matrix # apaMatrix.Diagonal.Major.Put(Vector) URL: https://www.andreassteiner.net/help/apamatrix.diagonal.major.put/ ## Result Returns a square matrix of zeros with the elements of a vector on the major diagonal. ## Syntax *Vector*: 1 x nCols vector of data # apaMatrix.Diagonal.Major.Put.Ones(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.diagonal.major.put.ones/ ## Result Sets all entries on the main diagonal of a matrix to one. ## Syntax *Matrix*: nRows x nCols matrix # apaMatrix.Drop.Cols(Selection, Matrix) URL: https://www.andreassteiner.net/help/apamatrix.drop.cols/ ## Result Removes columns of a matrix, given a vector of column indicators. ## Syntax *Selection*: 1 x c vector of column indicators (1 to drop, 0 to keep) *Matrix*: r x c data matrix # apaMatrix.Drop.Cols.ByIndex(Selection, Matrix) URL: https://www.andreassteiner.net/help/apamatrix.drop.cols.byindex/ ## Result Removes columns of a matrix, given a vector of column indices. ## Syntax *Selection*: 1 x m vector of column indices *Matrix*: r x c data matrix # apaMatrix.Drop.Rows(Selection, Matrix) URL: https://www.andreassteiner.net/help/apamatrix.drop.rows/ ## Result Removes rows of a matrix, given a vector of row indicators. ## Syntax *Selection*: r x 1 vector of row indicators (1 to drop, 0 to keep) *Matrix*: r x c data matrix # apaMatrix.Drop.Rows.ByIndex(Selection, Matrix) URL: https://www.andreassteiner.net/help/apamatrix.drop.rows.byindex/ ## Result Removes rows of a matrix, given a vector of row indices. ## Syntax *Selection*: m x 1 vector of row indices *Matrix*: r x c data matrix # apaMatrix.Flip.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.flip.cols/ ## Result Reverses the order of the elements of a matrix in the horizontal direction. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Flip.Rows(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.flip.rows/ ## Result Reverses the order of the elements of a matrix in the vertical direction. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.FromVec(Vec) URL: https://www.andreassteiner.net/help/apamatrix.fromvec/ ## Result Puts the elements of a vec vector into a square matrix. ## Syntax *Vec*: vector containing the ordered elements of a square matrix # apaMatrix.FromVech(Vech) URL: https://www.andreassteiner.net/help/apamatrix.fromvech/ ## Result Puts the elements of a vech vector, i.e. the lower triangular part including the main diagonal, into a square matrix. ## Syntax *Vech*: vector containing the ordered elements of the lower triangular part including the main diagonal # apaMatrix.FromVecl(Vecl) URL: https://www.andreassteiner.net/help/apamatrix.fromvecl/ ## Result Turns a vecl vector, i.e. the lower vectorization of a square matrix excluding the main diagonal, into a matrix. ## Syntax *Vecl*: 1 x n vector containing the ordered elements, n = m\*(m-1)/2 for an m x m matrix ## Algorithm The size of the matrix is derived from the number of elements as m = (1 + sqrt(1 + 8n)) / 2. ## Remarks The result is a lower triangular matrix with zeros on and above the main diagonal. To obtain a correlation matrix, use apaCorrels.FromVecl. # apaMatrix.Hankel(Matrix, WindowSize) URL: https://www.andreassteiner.net/help/apamatrix.hankel/ ## Result Builds a Hankel matrix from a data vector. ## Syntax *Matrix*: nRows x nCols matrix of data *WindowSize*: number of lags, which determines the number of rows # apaMatrix.Identity(n) URL: https://www.andreassteiner.net/help/apamatrix.identity/ ## Result Creates an n x n identity matrix, i.e. a square matrix with ones on the main diagonal and zeros otherwise. ## Syntax *n*: dimension of the identity matrix # apaMatrix.Inverse.Pseudo(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.inverse.pseudo/ ## Result Returns the Moore-Penrose pseudo-inverse of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data ## Remarks - The Moore–Penrose pseudo-inverse is calculated # apaMatrix.Kron(Matrix1, Matrix2) URL: https://www.andreassteiner.net/help/apamatrix.kron/ ## Result Returns the Kronecker product of two matrices. ## Syntax *Matrix1*: nRows1 x nCols1 matrix1 *Matrix2*: nRows2 x nCols2 matrix2 ## Remarks Beware: the size of the result can be rather large. # apaMatrix.Lagged(Matrix, LagVector) URL: https://www.andreassteiner.net/help/apamatrix.lagged/ ## Result Returns a matrix of lagged copies of data, defined by a vector of lags. Only matching observations are returned. ## Syntax *Matrix*: nRows x nCols matrix of data *LagVector*: 1 x nCols vector of lags. Negative lags reference past observations, positive lags future observations # apaMatrix.Lagged.nLags(Matrix, nLags, IncludeOriginal) URL: https://www.andreassteiner.net/help/apamatrix.lagged.nlags/ ## Result Returns a matrix of lagged copies of data, defined by the maximum number of lags nLags. ## Syntax *Matrix*: nRows x nCols matrix of data *nLags*: maximum number of lags *IncludeOriginal*: TRUE to include the original data in the first columns # apaMatrix.Lagged.Pad(Matrix, LagVector) URL: https://www.andreassteiner.net/help/apamatrix.lagged.pad/ ## Result Returns a matrix of lagged copies of data, defined by a vector of lags. Non-matching observations are padded with zeros. ## Syntax *Matrix*: nRows x nCols matrix of data *LagVector*: 1 x nCols vector of lags. Negative lags reference past observations, positive lags future observations # apaMatrix.Linspace(LowerValue, UpperValue, nPoints) URL: https://www.andreassteiner.net/help/apamatrix.linspace/ ## Result Generates a linearly spaced 1 x nPoints vector. ## Syntax *LowerValue*: lower value *UpperValue*: upper value *nPoints*: optional; number of points to generate; default: 1 # apaMatrix.LU.L(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.lu.l/ ## Result Returns the L matrix of an LU decomposition. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.LU.P(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.lu.p/ ## Result Returns the P matrix of an LU decomposition. ## Syntax *Matrix*: nRows x nCols matrix of data ## Remarks P is a permutation matrix. # apaMatrix.LU.U(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.lu.u/ ## Result Returns the U matrix of an LU decomposition. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.MatrixProfile.WithIndex(series, windowSize) URL: https://www.andreassteiner.net/help/apamatrix.matrixprofile.withindex/ ## Result Returns the matrix profile and the 1-based matrix profile index for a univariate time series. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *windowSize*: length of the subsequences (window size) ## Algorithm The calculation is identical to apaPatternRecognition.MatrixProfile. ## Remarks The result is a k x 2 matrix with k = r − windowSize + 1, the matrix profile in the first and the matrix profile index in the second column. # apaMatrix.Max.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.max.cols/ ## Result Returns the column maxima of a matrix. ## Syntax *Matrix*: data matrix # apaMatrix.Min.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.min.cols/ ## Result Returns the column minima of a matrix. ## Syntax *Matrix*: data matrix # apaMatrix.Minors(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.minors/ ## Result Returns the matrix of all minors of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Numeric.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.numeric.cols/ ## Result Returns the columns of a matrix with numeric values only, i.e. series containing non-numeric elements are excluded. ## Syntax *Matrix*: data matrix # apaMatrix.Numeric.Rows(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.numeric.rows/ ## Result Returns the rows of a matrix with numeric values only, i.e. data records containing non-numeric elements are excluded. ## Syntax *Matrix*: data matrix # apaMatrix.Normal.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.normal.cols/ ## Result Normalizes the columns of a matrix such that the lowest value is 0 and the highest value is 1. ## Syntax *Matrix*: nRows x nCols matrix of data ## Remarks ![Formula](https://www.andreassteiner.net/help/assets/eq/image76.svg) # apaMatrix.Normal.Rows(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.normal.rows/ ## Result Normalizes the rows of a matrix such that the lowest value is 0 and the highest value is 1. ## Syntax *Matrix*: nRows x nCols matrix of data ## Remarks ![Formula](https://www.andreassteiner.net/help/assets/eq/image76.svg) # apaMatrix.Normal.L2.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.normal.l2.cols/ ## Result L2 normalization of all columns of a matrix: values are divided by the L2 norm of their column, such that all series are vectors of length one. ## Syntax *Matrix*: nRows x nCols matrix of data ## Remarks L2 normalization, also known as Euclidean normalization or unit vector normalization, rescales vectors to a length (norm) of one by dividing each element by the Euclidean norm of the vector, i.e. the square root of the sum of its squared elements. # apaMatrix.Normal.QuadraticTerm(Matrix, Method) URL: https://www.andreassteiner.net/help/apamatrix.normal.quadraticterm/ ## Result Normalizes a square quadratic-term matrix by dividing all elements by a representative scale. Method 0 = MeanDiagonal (default), 1 = Trace, 2 = MaxDiagonal. The result is a normalized matrix of the same dimension as the input matrix. ## Syntax *Matrix*: square quadratic-term matrix, e.g. a covariance matrix, a Laplacian matrix or a lifted community Laplacian matrix *Method*: optional; normalization method: 0 = MeanDiagonal (default), 1 = Trace, 2 = MaxDiagonal # apaMatrix.Normal.QuadraticTerm.Scale(Matrix, Method) URL: https://www.andreassteiner.net/help/apamatrix.normal.quadraticterm.scale/ ## Result Returns the representative scale used for quadratic-term normalization, i.e. the scalar normalization scale used by apaMatrix.Normal.QuadraticTerm. Method 0 = MeanDiagonal (default), 1 = Trace, 2 = MaxDiagonal. ## Syntax *Matrix*: square quadratic-term matrix, e.g. a covariance matrix, a Laplacian matrix or a lifted community Laplacian matrix *Method*: optional; normalization method: 0 = MeanDiagonal (default), 1 = Trace, 2 = MaxDiagonal # apaMatrix.Normal.Range.Cols(Matrix, LowerLimit, UpperLimit) URL: https://www.andreassteiner.net/help/apamatrix.normal.range.cols/ ## Result Normalizes all columns of a matrix to a given lower and upper limit. ## Syntax *Matrix*: nRows x nCols matrix of data *LowerLimit*: lower limit of the range *UpperLimit*: upper limit of the range # apaMatrix.Normal.Range.Rows(Matrix, LowerLimit, UpperLimit) URL: https://www.andreassteiner.net/help/apamatrix.normal.range.rows/ ## Result ## Normalizes all rows in a matrix to a given lower and upper bound. ## Syntax *Matrix*: nRows x nCols matrix of data *LowerLimit*: lower limit of the range *UpperLimit*: upper limit of the range # apaMatrix.Ones(nRows, nCols) URL: https://www.andreassteiner.net/help/apamatrix.ones/ ## Result Returns an nRows x nCols matrix of ones. ## Syntax *nRows*: number of rows *nCols*: number of columns # apaMatrix.Power(Matrix, Exponent) URL: https://www.andreassteiner.net/help/apamatrix.power/ ## Result Calculates the power of a square matrix. ## Syntax *Matrix*: n x n matrix *Exponent*: exponent, a non-negative integer # apaMatrix.QR.Q(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.qr.q/ ## Result Returns the Q matrix of a QR decomposition. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.QR.R(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.qr.r/ ## Result Returns the R matrix of a QR decomposition. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Rank(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.rank/ ## Result Returns the rank of a matrix, i.e. the number of linearly independent rows or columns. ## Syntax *Matrix*: nRows x nCols matrix of data ## Algorithm The rank is determined based on a singular value decomposition of the input matrix. # apaMatrix.Remove.Duplicate.Rows(DataMatrix) URL: https://www.andreassteiner.net/help/apamatrix.remove.duplicate.rows/ ## Result Removes the duplicate rows of a matrix. ## Syntax *DataMatrix*: nRows x nCols matrix of data # apaMatrix.Reorder.Cols(Matrix, Order) URL: https://www.andreassteiner.net/help/apamatrix.reorder.cols/ ## Result Reorders the columns of a matrix based on a vector of indices. ## Syntax *Matrix*: nRows x nCols matrix of data *Order*: 1 x nCols vector of indices representing the new order # apaMatrix.Reorder.Rows(Matrix, Order) URL: https://www.andreassteiner.net/help/apamatrix.reorder.rows/ ## Result Reorders the rows of a matrix based on a vector of indices. ## Syntax *Matrix*: nRows x nCols matrix of data *Order*: nRows x 1 vector of indices representing the new order # apaMatrix.Repeat.Cols(Matrix, n) URL: https://www.andreassteiner.net/help/apamatrix.repeat.cols/ ## Result Repeats a matrix n times in the horizontal direction. ## Syntax *Matrix*: nRows x nCols matrix of data *n*: integer number of repetitions # apaMatrix.Repeat.Rows(Matrix, n) URL: https://www.andreassteiner.net/help/apamatrix.repeat.rows/ ## Result Repeats a matrix n times in the vertical direction. ## Syntax *Matrix*: nRows x nCols matrix of data *n*: integer number of repetitions # apaMatrix.Replace.ExcelEmpty(Matrix, ReplacementValue) URL: https://www.andreassteiner.net/help/apamatrix.replace.excelempty/ ## Result Replaces empty Excel cell values in a data matrix with another value. The replacement value can be numeric, text or an Excel error value. ## Syntax *Matrix*: r x c matrix of data. Does not need to be numerical only. *ReplacementValue*: replacement value, does not need to be numeric # apaMatrix.Replace.Value(Matrix, RowIndex, ColIndex, ReplacementValue) URL: https://www.andreassteiner.net/help/apamatrix.replace.value/ ## Result Replaces one value in a matrix. ## Syntax *Matrix*: r x c data matrix *RowIndex*: row index *ColIndex*: column index *ReplacementValue*: new value # apaMatrix.Replace.Values(Matrix, Values, ReplacementValue) URL: https://www.andreassteiner.net/help/apamatrix.replace.values/ ## Result Replaces given numbers in a data matrix with another value. The replacement value can be numeric, text or an Excel error value. ## Syntax *Matrix*: r x c data matrix, does not need to be numeric only *Values*: r x 1 vector of numeric values to be replaced *ReplacementValue*: replacement value, does not need to be numeric # apaMatrix.Replace.Zeros(Matrix, ReplacementValue) URL: https://www.andreassteiner.net/help/apamatrix.replace.zeros/ ## Result Replaces zero values in a data matrix with another value. The replacement value can be numeric, text or an Excel error value. ## Syntax *Matrix*: r x c data matrix, does not need to be numeric only *ReplacementValue*: replacement value, does not need to be numeric # apaMatrix.Scale.Cols(Matrix, Target, IsSignedValsOtherwiseAbs) URL: https://www.andreassteiner.net/help/apamatrix.scale.cols/ ## Result Scales the columns of a matrix such that their sums are all equal to a target value. ## Syntax *Matrix*: nRows x nCols matrix of data *Target*: target to which the scaled values add up *IsSignedValsOtherwiseAbs*: TRUE to use the signed values, FALSE to use the absolute values # apaMatrix.Scale.Rows(Matrix, Target, IsSignedValsOtherwiseAbs) URL: https://www.andreassteiner.net/help/apamatrix.scale.rows/ ## Result Scales the rows of a matrix such that their sums are all equal to a target value. ## Syntax *Matrix*: nRows x nCols matrix of data *Target*: target to which the scaled values add up *IsSignedValsOtherwiseAbs*: TRUE to use the signed values, FALSE to use the absolute values # apaMatrix.Scalar.Mult.MajDiag(Matrix, Scalar) URL: https://www.andreassteiner.net/help/apamatrix.scalar.mult.majdiag/ ## Result Multiplies the elements on the major diagonal of a matrix by a scalar. ## Syntax *Matrix*: nRows x nCols matrix of data *Scalar*: a real number # apaMatrix.Scalar.Mult.OffMajDiag(Matrix, Scalar) URL: https://www.andreassteiner.net/help/apamatrix.scalar.mult.offmajdiag/ ## Result Multiplies the elements off the major diagonal of a matrix by a scalar. ## Syntax *Matrix*: nRows x nCols matrix of data *Scalar*: a real number # apaMatrix.Select.Cols(Selection, Matrix) URL: https://www.andreassteiner.net/help/apamatrix.select.cols/ ## Result Selects columns of a matrix, given an indicator vector. ## Syntax *Selection*: 1 x c vector of column indicators (1 for selected, 0 for not selected) *Matrix*: r x c data matrix # apaMatrix.Select.Cols.ByCategory(CategorySelected, CategoryIndices, Matrix) URL: https://www.andreassteiner.net/help/apamatrix.select.cols.bycategory/ ## Result Selects the columns of a matrix which belong to a given category. ## Syntax *CategorySelected*: category index to select *CategoryIndices*: 1 x c vector of category indices, one per column of Matrix *Matrix*: r x c data matrix ## Remarks The columns are returned in their original order. # apaMatrix.Select.Cols.ByIndex(Selection, Matrix) URL: https://www.andreassteiner.net/help/apamatrix.select.cols.byindex/ ## Result Selects columns of a matrix, given a vector of column indices. ## Syntax *Selection*: 1 x m vector of column indices *Matrix*: r x c data matrix # apaMatrix.Select.Rows(Selection, Matrix) URL: https://www.andreassteiner.net/help/apamatrix.select.rows/ ## Result Selects rows of a matrix, given an indicator vector. ## Syntax *Selection*: r x 1 vector of row indicators (1 for selected, 0 for not selected) *Matrix*: r x c data matrix # apaMatrix.Select.Rows.ByCategory(CategorySelected, CategoryIndices, Matrix) URL: https://www.andreassteiner.net/help/apamatrix.select.rows.bycategory/ ## Result Selects the rows of a matrix which belong to a given category. ## Syntax *CategorySelected*: index of the selected category *CategoryIndices*: nRows x 1 vector of category indices *Matrix*: nRows x c data matrix # apaMatrix.Select.Rows.ByIndex(Selection, Matrix) URL: https://www.andreassteiner.net/help/apamatrix.select.rows.byindex/ ## Result Selects rows of a matrix, given a vector of row indices. ## Syntax *Selection*: m x 1 vector of row indices *Matrix*: r x c data matrix # apaMatrix.Select.Rows.NA(Selection, Matrix) URL: https://www.andreassteiner.net/help/apamatrix.select.rows.na/ ## Result Selects rows of a matrix, given an indicator vector, and sets the data of the non-selected rows to \#N/A. ## Syntax *Selection*: r x 1 vector of row indicators (1 for selected, 0 for not selected) *Matrix*: r x c data matrix # apaMatrix.Shift.Circular(Matrix, nXDirection, nYDirection) URL: https://www.andreassteiner.net/help/apamatrix.shift.circular/ ## Result Shifts a matrix in the horizontal and/or vertical direction by folding (circular shift). ## Syntax *Matrix*: nRows x nCols matrix of data *nXDirection*: number of steps in the horizontal direction *nYDirection*: number of steps in the vertical direction ## Remarks nXDirection and nYDirection can be negative or positive. The sign defines the direction. # apaMatrix.Shuffle.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.shuffle.cols/ ## Result Shuffles the columns of a matrix randomly. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Shuffle.Rows(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.shuffle.rows/ ## Result Shuffles the rows of a matrix randomly. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Shift.Pad(Matrix, nXDirection, nYDirection) URL: https://www.andreassteiner.net/help/apamatrix.shift.pad/ ## Result Shifts a matrix in the horizontal and/or vertical direction by padding zeros. ## Syntax *Matrix*: nRows x nCols matrix of data *nXDirection*: number of steps in the horizontal direction *nYDirection*: number of steps in the vertical direction ## Remarks nXDirection and nYDirection can be negative or positive. The sign defines the direction. # apaMatrix.SolveLinear(A, b) URL: https://www.andreassteiner.net/help/apamatrix.solvelinear/ ## Result Solves a linear system of equations A\*x = b. ## Syntax *A*: n x n matrix A *b*: n x 1 vector b ## Algorithm The linear system is solved by matrix decomposition (e.g. LU decomposition). The result is the solution vector x; on error, an Excel error value is returned. # apaMatrix.Sort.Rows.ByFirstColumn.Asc(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.sort.rows.byfirstcolumn.asc/ ## Result Sorts the rows of a matrix by the values in its first column in ascending order. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Sort.Rows.ByFirstColumn.Des(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.sort.rows.byfirstcolumn.des/ ## Result Sorts the rows of a matrix by the values in its first column in descending order. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Sort.Rows.ByVector.Asc(Matrix, Vector) URL: https://www.andreassteiner.net/help/apamatrix.sort.rows.byvector.asc/ ## Result Sorts the rows of a matrix by the values in a vector in ascending order. ## Syntax *Matrix*: nRows x nCols matrix of data *Vector*: nRows x 1 vector of data # apaMatrix.Sort.Rows.ByVector.Des(Matrix, Vector) URL: https://www.andreassteiner.net/help/apamatrix.sort.rows.byvector.des/ ## Result Sorts the rows of a matrix by the values in a vector in descending order. ## Syntax *Matrix*: nRows x nCols matrix of data *Vector*: nRows x 1 vector of data # apaMatrix.Standard.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.standard.cols/ ## Result Standardizes the columns of a matrix such that their means are zero and their volatilities equal one. ## Syntax *Matrix*: nRows x nCols matrix of data ## Remarks x_stand = (x – x_mean) / x_volatility Uses the population volatility (denominator n). # apaMatrix.Standard.Rows(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.standard.rows/ ## Result Standardizes the rows of a matrix such that their means are zero and their volatilities equal one. ## Syntax *Matrix*: nRows x nCols matrix of data ## Algorithm x_stand = (x – x_mean) / x_volatility ## Remarks Uses the population volatility (denominator n). # apaMatrix.Sums.Categories(DataMatrix, CategoryLabels) URL: https://www.andreassteiner.net/help/apamatrix.sums.categories/ ## Result Returns the category sums of a data matrix. The input data can be jagged. ## Syntax *DataMatrix*: jagged data matrix, each column containing a time series *CategoryLabels*: 1 x c vector of category labels ## Remarks Each column of DataMatrix is assigned to the category given in CategoryLabels. For each row, the numeric values of each category are summed; empty cells, text, logical values and error values are skipped. The output has one row per row of DataMatrix and one column per category. A category without numeric values in a row returns \#N/A. CategoryLabels may be a row or a column vector with one label per column of DataMatrix. # apaMatrix.Sums.Cols(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.sums.cols/ ## Result Returns the column sums of a matrix. ## Syntax *Matrix*: data matrix # apaMatrix.Sums.Rows(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.sums.rows/ ## Result Returns the row sums of a matrix. ## Syntax *Matrix*: data matrix # apaMatrix.SVD.S(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.svd.s/ ## Result Returns the S matrix of a singular value decomposition (SVD). ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.SVD.U(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.svd.u/ ## Result Returns the U matrix of a singular value decomposition (SVD). ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.SVD.V(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.svd.v/ ## Result Returns the V matrix of a singular value decomposition (SVD). ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Trace(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.trace/ ## Result Returns the trace of a matrix. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Toeplitz(Matrix, WindowSize) URL: https://www.andreassteiner.net/help/apamatrix.toeplitz/ ## Result Builds a Toeplitz matrix from a data vector. ## Syntax *Matrix*: nRows x nCols matrix of data *WindowSize*: number of lags, which determines the number of rows # apaMatrix.Uniques(DataMatrix) URL: https://www.andreassteiner.net/help/apamatrix.uniques/ ## Result Returns all unique items of a matrix. The data can be numeric, non-numeric or mixed. ## Syntax *DataMatrix*: r x c data matrix, numeric and/or non-numeric # apaMatrix.Vec(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.vec/ ## Result Turns a matrix into a column vector. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Vech(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.vech/ ## Result Turns the lower triangular part of a matrix, including the major diagonal, into a column vector. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Vecl(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.vecl/ ## Result Turns the lower triangular part of a matrix, excluding the major diagonal, into a column vector. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Vecl.WithIndices(Matrix) URL: https://www.andreassteiner.net/help/apamatrix.vecl.withindices/ ## Result Turns the lower triangular part of a matrix, excluding the major diagonal, into a column vector. Also returns the time series indices as labels. ## Syntax *Matrix*: nRows x nCols matrix of data # apaMatrix.Zeros(nRows, nCols) URL: https://www.andreassteiner.net/help/apamatrix.zeros/ ## Result Returns an nRows x nCols matrix of zeros. ## Syntax *nRows*: number of rows *nCols*: number of columns # apaMean.ConfidenceIntervals(TimeSeries, ConfidenceLevel, nSamples) URL: https://www.andreassteiner.net/help/apamean.confidenceintervals/ ## Result Calculates the confidence intervals for the mean (first moment) using a resampling methodology. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *ConfidenceLevel*: confidence level, e.g. 95% *nSamples*: number of resampled data sets # apaMeanCDaR.Assets(ReturnMatrix, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apameancdar.assets/ ## Result Returns a 2 x nAssets matrix with the average return of each asset in the first row and its conditional drawdown at risk (CDaR) in the second row. The CDaR is calculated exactly as in the mean-CDaR optimizer (apaMeanCDaR.Restricted.Bounded.Frontier and apaMeanCDaR.Restricted.Bounded.Axb.Frontier): the CDaR of an asset equals the CDaR the optimizer reports for a portfolio fully invested in that asset. The asset points and the efficient frontier are therefore on the same scale and can be plotted in one mean-CDaR diagram. The CDaR is expressed as a positive drawdown: a CDaR of 0.15 at a confidence level of 0.95 means that the average of the worst 5% of the drawdowns is 15 percentage points of cumulative return. The average returns are expressed in the periodicity of the input data and are not annualized. ## Syntax *ReturnMatrix*: nObs x nAssets matrix of asset returns in chronological order (oldest observation in the first row), each column containing the return time series of one asset *ConfidenceLevel*: CDaR confidence level in \[0, 1), e.g. 0.95; 0 gives the average drawdown, values close to 1 give the maximum drawdown ## Algorithm The CDaR follows Chekhlov, Uryasev and Zabarankin and uses the same drawdown definition as the linear program of the mean-CDaR optimizer. With T returns r(t, j) of asset j, the cumulative uncompounded return and the drawdown in period t are ``` math R_{t,j} = \sum_{s = 1}^{t}r_{s,j},\quad\quad R_{0,j} = 0 ``` ``` math DD_{t,j} = \max_{0 \leq s \leq t}R_{s,j} - R_{t,j},\quad\quad t = 1,\ldots,T ``` The running peak includes the starting value R(0) = 0, so an initial loss already counts as a drawdown. All T drawdowns enter the calculation with the probability 1/T, including the periods without a drawdown (DD = 0). With the confidence level β, the CDaR is the Rockafellar-Uryasev tail average of the drawdowns: ``` math {CDaR}_{\beta,j} = \min_{z}\left\{ z + \frac{1}{(1 - \beta)\, T}\sum_{t = 1}^{T}\max\left( DD_{t,j} - z,\, 0 \right) \right\} ``` The minimizing z is the drawdown at risk (DaR). The function evaluates the minimum in closed form. With the drawdowns of asset j sorted in descending order, DD(1) ≥ DD(2) ≥ … ≥ DD(T), the tail size τ and its integer part n are ``` math \tau = (1 - \beta)\, T,\quad\quad n = \lfloor\tau\rfloor ``` ``` math {CDaR}_{\beta,j} = \frac{1}{\tau}\left( \sum_{i = 1}^{n}DD_{(i)} + (\tau - n)\, DD_{(n + 1)} \right) ``` The CDaR is thus the average of the τ largest drawdowns. If τ is not an integer, the boundary drawdown DD(n + 1) enters with the fractional weight τ - n. With β = 0 the CDaR equals the average drawdown, and for β ≥ 1 - 1/T it equals the maximum drawdown. The average return in the first row is the arithmetic mean of each column. ## Remarks The CDaR is computed per asset, i.e. without diversification; it is not additive across assets. Because drawdowns depend on the order of the observations, the rows of ReturnMatrix must be in chronological order. apaCDaR.Empirical uses a different convention, so its figures generally differ from apaMeanCDaR.Assets. (1) Compounding: apaCDaR.Empirical measures drawdowns of the compounded wealth path, W(t) / max W(s) - 1, whereas apaMeanCDaR.Assets uses differences of cumulative uncompounded returns, as required for the linear program of the optimizer. For large losses the two differ markedly; uncompounded drawdowns can exceed 100%. (2) Sign: apaCDaR.Empirical reports drawdowns as negative returns, apaMeanCDaR.Assets as positive numbers. (3) Sample: apaCDaR.Empirical drops all periods without a drawdown and applies the confidence level to the underwater periods only, whereas apaMeanCDaR.Assets applies it to all T periods. (4) Tail definition: apaCDaR.Empirical determines the DaR as the interpolated empirical percentile of the drawdowns and averages the drawdowns strictly beyond it, without a fractional boundary observation; with IsSmooth = TRUE it additionally blends in the DaR. apaMeanCDaR.Assets uses the Rockafellar-Uryasev tail average with the fractional boundary weight described above. Use apaMeanCDaR.Assets whenever assets are compared with the output of the mean-CDaR optimizer, and apaCDaR.Empirical when drawdowns of the compounded wealth path are of interest. See apaMeanCVaR.Assets and apaMeanVariance.Assets for the corresponding mean-CVaR and mean-volatility coordinates. # apaMeanCDaR.Restricted.Bounded.Axb.Frontier(nPoints, Returns, ConfidenceLevel, lowerBounds, upperBounds, Budget, EqualityPickMatrix, EqualityValues, LowerPickMatrix, LowerValues, UpperPickMatrix, UpperValues) URL: https://www.andreassteiner.net/help/apameancdar.restricted.bounded.axb.frontier/ ## Result Calculates the restricted and bounded mean-CDaR efficient frontier for a given confidence level, with optional additional linear equality and inequality constraints. Columns: conditional drawdown at risk (CDaR), return and constituent weights. ## Syntax *nPoints*: number of points on the frontier to calculate *Returns*: nObs x nAssets matrix of portfolio constituent returns in chronological order, each column containing a constituent *ConfidenceLevel*: CDaR confidence level in \[0, 1). 0 gives the average drawdown, values close to 1 the maximum drawdown *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *EqualityPickMatrix*: optional mE x nAssets matrix of the equality constraints EqualityPickMatrix\*w = EqualityValues *EqualityValues*: optional vector of the mE equality constraint values *LowerPickMatrix*: optional mL x nAssets matrix of the inequality constraints LowerPickMatrix\*w \>= LowerValues *LowerValues*: optional vector of the mL lower constraint values *UpperPickMatrix*: optional mU x nAssets matrix of the inequality constraints UpperPickMatrix\*w \<= UpperValues *UpperValues*: optional vector of the mU upper constraint values ## Algorithm The algorithm corresponds to apaMeanCDaR.Restricted.Bounded.Frontier, with the additional linear constraints added to the linear programs. ## Remarks Infeasible points are skipped. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanCDaR.Restricted.Bounded.Frontier(nPoints, Returns, ConfidenceLevel, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameancdar.restricted.bounded.frontier/ ## Result Calculates the restricted and bounded mean-CDaR efficient frontier for a given confidence level, using drawdowns of cumulative uncompounded returns. Columns: conditional drawdown at risk (CDaR), return and constituent weights. ## Syntax *nPoints*: number of points on the frontier to calculate *Returns*: nObs x nAssets matrix of portfolio constituent returns in chronological order, each column containing a constituent *ConfidenceLevel*: CDaR confidence level in \[0, 1). 0 gives the average drawdown, values close to 1 the maximum drawdown *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures ## Algorithm The minimum CDaR portfolio and the maximum return portfolio are calculated. ## Remarks Infeasible points are skipped. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanCVaR.Assets(ReturnMatrix, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apameancvar.assets/ ## Result Returns a 2 x nAssets matrix with the average return of each asset in the first row and its conditional value at risk (CVaR) in the second row. The CVaR is calculated exactly as in the mean-CVaR optimizer (apaMeanCVaR.Restricted.Bounded.Frontier and the related apaMeanCVaR functions): the CVaR of an asset equals the CVaR the optimizer reports for a portfolio fully invested in that asset. The asset points and the efficient frontier are therefore on the same scale and can be plotted in one mean-CVaR diagram. The CVaR is expressed as a positive loss: a CVaR of 0.08 at a confidence level of 0.95 means that the average loss in the worst 5% of the scenarios is 8%. Both statistics are expressed in the periodicity of the input data and are not annualized. ## Syntax *ReturnMatrix*: nObs x nAssets matrix of asset returns or return scenarios, each column containing the returns of one asset; all rows are treated as equally likely *ConfidenceLevel*: CVaR confidence level in \[0, 1), e.g. 0.95 ## Algorithm Each of the T scenarios has the probability 1/T. With the confidence level β, the CVaR of asset j is the Rockafellar-Uryasev expected shortfall, the same expression that the mean-CVaR optimizer minimizes as a linear program: ``` math {CVaR}_{\beta,j} = \min_{z}\left\{ z + \frac{1}{(1 - \beta)\, T}\sum_{t = 1}^{T}\max\left( - r_{t,j} - z,\, 0 \right) \right\} ``` The minimizing z is the value at risk. The function evaluates the minimum in closed form. With the returns of asset j sorted in ascending order, r(1) ≤ r(2) ≤ … ≤ r(T), the tail size τ and its integer part n are ``` math \tau = (1 - \beta)\, T,\quad\quad n = \lfloor\tau\rfloor ``` ``` math {CVaR}_{\beta,j} = \frac{1}{\tau}\left( - \sum_{i = 1}^{n}r_{(i)} - (\tau - n)\, r_{(n + 1)} \right) ``` The CVaR is thus the average loss of the worst τ scenarios. If τ is not an integer, the boundary scenario r(n + 1) enters with the fractional weight τ - n. The average return in the first row is the arithmetic mean of each column. ## Remarks The CVaR is computed per asset, i.e. without diversification; it is not additive across assets. With a confidence level of 0, the CVaR equals the negative average return. apaCVaR.Empirical uses a different convention: it reports the tail average as a (negative) return and averages only the scenarios strictly below the empirical VaR without a fractional boundary scenario, so its figures can differ from apaMeanCVaR.Assets in sign and, for small samples, in magnitude. Use apaMeanCVaR.Assets whenever assets are compared with the output of the mean-CVaR optimizer. See apaMeanVariance.Assets for the corresponding mean-volatility coordinates. # apaMeanCVaR.Restricted.Bounded.Axb.Frontier(nPoints, Returns, ConfidenceLevel, lowerBounds, upperBounds, Budget, EqualityPickMatrix, EqualityValues, LowerPickMatrix, LowerValues, UpperPickMatrix, UpperValues) URL: https://www.andreassteiner.net/help/apameancvar.restricted.bounded.axb.frontier/ ## Result Calculates the restricted and bounded mean-CVaR efficient frontier for a given confidence level, with optional additional linear equality and inequality constraints. Columns: conditional value at risk (CVaR), return and constituent weights. ## Syntax *nPoints*: number of points on the frontier to calculate *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *ConfidenceLevel*: CVaR confidence level *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *EqualityPickMatrix*: optional mE x nAssets matrix of the equality constraints EqualityPickMatrix\*w = EqualityValues *EqualityValues*: optional vector of the mE equality constraint values *LowerPickMatrix*: optional mL x nAssets matrix of the inequality constraints LowerPickMatrix\*w \>= LowerValues *LowerValues*: optional vector of the mL lower constraint values *UpperPickMatrix*: optional mU x nAssets matrix of the inequality constraints UpperPickMatrix\*w \<= UpperValues *UpperValues*: optional vector of the mU upper constraint values ## Algorithm The minimum CVaR portfolio and the maximum return portfolio are calculated subject to all constraints. ## Remarks Infeasible points are skipped. See apaMeanCVaR.Restricted.Bounded.Frontier for the frontier without additional constraints. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanCVaR.Restricted.Bounded.Weights.FromCVaR(Returns, targetCVaR, ConfidenceLevel, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameancvar.restricted.bounded.weights.fromcvar/ ## Result Returns the composition of the restricted and bounded maximum return portfolio subject to a target CVaR. ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *targetCVaR*: target conditional value at risk (CVaR) *ConfidenceLevel*: CVaR confidence level *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanCVaR.Restricted.Bounded.Weights.MinCVaR(Returns, ConfidenceLevel, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameancvar.restricted.bounded.weights.mincvar/ ## Result Returns the composition of the restricted and bounded minimum CVaR portfolio. ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *ConfidenceLevel*: CVaR confidence level *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanCVaR.Restricted.Bounded.Frontier(nPoints, Returns, ConfidenceLevel, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameancvar.restricted.bounded.frontier/ ## Result Calculates the restricted and bounded mean-CVaR efficient frontier for a given confidence level. The function is non-volatile. ## Syntax *nPoints*: number of points on the frontier to calculate *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *ConfidenceLevel*: CVaR confidence level *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanCVaR.Restricted.Bounded.Weights.FromReturn(Returns, targetReturn, ConfidenceLevel, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameancvar.restricted.bounded.weights.fromreturn/ ## Result Returns the composition of the restricted and bounded minimum CVaR portfolio subject to a target return. ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *targetReturn*: target return *ConfidenceLevel*: CVaR confidence level *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMAD.Restricted.Bounded.Weights.FromMAD(Returns, targetMAD, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmad.restricted.bounded.weights.frommad/ ## Result Returns the composition of the restricted and bounded maximum return portfolio subject to a target MAD (mean absolute deviation). ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *targetMAD*: target MAD (mean absolute deviation) *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMAD.Restricted.Bounded.Weights.MinMAD(Returns, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmad.restricted.bounded.weights.minmad/ ## Result Returns the composition of the restricted and bounded minimum MAD (mean absolute deviation) portfolio. ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMAD.Restricted.Bounded.Frontier(nPoints, Returns, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmad.restricted.bounded.frontier/ ## Result Calculates the restricted and bounded mean-MAD (mean absolute deviation) efficient frontier. The function is non-volatile. ## Syntax *nPoints*: number of points on the frontier to calculate *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMAD.Restricted.Bounded.Weights.FromReturn(Returns, targetReturn, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmad.restricted.bounded.weights.fromreturn/ ## Result Returns the composition of the restricted and bounded minimum MAD (mean absolute deviation) portfolio subject to a target return. ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *targetReturn*: target return *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMADD.Restricted.Bounded.Weights.FromMADD(Returns, targetMADD, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmadd.restricted.bounded.weights.frommadd/ ## Result Returns the composition of the restricted and bounded maximum return portfolio subject to a target MADD (mean absolute downside deviation). ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *targetMADD*: target MADD (mean absolute downside deviation) *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMADD.Restricted.Bounded.Weights.MinMADD(Returns, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmadd.restricted.bounded.weights.minmadd/ ## Result Returns the composition of the restricted and bounded minimum MADD (mean absolute downside deviation) portfolio. ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMADD.Restricted.Bounded.Frontier(nPoints, Returns, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmadd.restricted.bounded.frontier/ ## Result Calculates the restricted and bounded mean-MADD (mean absolute downside deviation) efficient frontier. The function is non-volatile. ## Syntax *nPoints*: number of points on the frontier to calculate *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMADD.Restricted.Bounded.Weights.FromReturn(Returns, targetReturn, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmadd.restricted.bounded.weights.fromreturn/ ## Result Returns the composition of the restricted and bounded minimum MADD (mean absolute downside deviation) portfolio subject to a target return. ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *targetReturn*: target return *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMADTD.Restricted.Bounded.Weights.FromMADTD(Returns, thresholdReturn, targetMADTD, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmadtd.restricted.bounded.weights.frommadtd/ ## Result Returns the composition of the restricted and bounded maximum return portfolio subject to a target MADTD (mean absolute downside threshold deviation). ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *thresholdReturn*: threshold return of the MADTD *targetMADTD*: target MADTD (mean absolute downside threshold deviation) *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMADTD.Restricted.Bounded.Weights.MinMADTD(Returns, thresholdReturn, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmadtd.restricted.bounded.weights.minmadtd/ ## Result Returns the composition of the restricted and bounded minimum MADTD (mean absolute downside threshold deviation) portfolio. ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *thresholdReturn*: threshold return of the MADTD *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMADTD.Restricted.Bounded.Frontier(nPoints, Returns, thresholdReturn, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmadtd.restricted.bounded.frontier/ ## Result Calculates the restricted and bounded mean-MADTD (mean absolute downside threshold deviation) efficient frontier. The function is non-volatile. ## Syntax *nPoints*: number of points on the frontier to calculate *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *thresholdReturn*: threshold return of the MADTD *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanMADTD.Restricted.Bounded.Weights.FromReturn(Returns, thresholdReturn, targetReturn, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanmadtd.restricted.bounded.weights.fromreturn/ ## Result Returns the composition of the restricted and bounded minimum MADTD (mean absolute downside threshold deviation) portfolio subject to a target return. ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *thresholdReturn*: threshold return of the MADTD *targetReturn*: target return *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanML.Restricted.Bounded.Weights.FromML(Returns, targetML, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanml.restricted.bounded.weights.fromml/ ## Result Returns the composition of the restricted and bounded maximum return portfolio subject to a target ML (maximum loss). ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *targetML*: target ML (maximum loss) *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanML.Restricted.Bounded.Weights.MinML(Returns, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanml.restricted.bounded.weights.minml/ ## Result Returns the composition of the restricted and bounded minimum ML (maximum loss) portfolio. ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanML.Restricted.Bounded.Frontier(nPoints, Returns, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanml.restricted.bounded.frontier/ ## Result Calculates the restricted and bounded mean-ML (maximum loss) efficient frontier. The function is non-volatile. ## Syntax *nPoints*: number of points on the frontier to calculate *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanML.Restricted.Bounded.Weights.FromReturn(Returns, targetReturn, lowerBounds, upperBounds, Budget) URL: https://www.andreassteiner.net/help/apameanml.restricted.bounded.weights.fromreturn/ ## Result Returns the composition of the restricted and bounded minimum ML (maximum loss) portfolio subject to a target return. ## Syntax *Returns*: nObs x nAssets matrix of portfolio constituent returns, each column containing a constituent *targetReturn*: target return *lowerBounds*: 1 x nAssets vector of lower bounds *upperBounds*: 1 x nAssets vector of upper bounds *Budget*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Assets(ReturnMatrix, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apameanvariance.assets/ ## Result Returns a 2 x nAssets matrix with the average return of each asset in the first row and its volatility in the second row. The two rows are the coordinates of the individual assets in the mean-volatility diagram, so they can be charted directly next to a mean-variance efficient frontier, e.g. one calculated with apaMeanVariance.Restricted.Bounded.Frontier. The first row can also serve as the vector of expected returns of the mean-variance functions. Both statistics are expressed in the periodicity of the input data and are not annualized. ## Syntax *ReturnMatrix*: nObs x nAssets matrix of asset returns, each column containing the return time series of one asset *IsSampleOtherwisePopulation*: optional; TRUE for the sample volatility (division by nObs - 1), FALSE for the population volatility (division by nObs); default: FALSE ## Algorithm With T observations r(t, j) of asset j, the average return and the volatility are ``` math {\bar{r}}_{j} = \frac{1}{T}\sum_{t = 1}^{T}r_{t,j} ``` ``` math \sigma_{j} = \sqrt{\frac{1}{T - k}\sum_{t = 1}^{T}\left( r_{t,j} - {\bar{r}}_{j} \right)^{2}},\quad\quad k = \left\{ \begin{matrix} 0 & \text{population volatility} \\ 1 & \text{sample volatility} \end{matrix} \right.\ ``` The result is the vertical concatenation of the row of averages (as apaMatrix.Averages.Cols) and the row of volatilities (as apaVolatilities). ## Remarks The volatilities are identical to apaVolatilities(ReturnMatrix, IsSampleOtherwisePopulation). The sample volatility requires at least two observations. All cells of ReturnMatrix must be numeric; missing values are not allowed. See apaMeanCVaR.Assets for the corresponding mean-CVaR coordinates. # apaMeanVariance.Restricted.Bounded.Frontier(nPointsInbetween, ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.frontier/ ## Result Calculates the mean-variance efficient frontier with Markowitz’s Critical Line Algorithm. The first two columns of the result contain the volatilities and returns of the frontier portfolios, the remaining columns the constituent weights. ## Syntax *nPointsInbetween*: number of frontier portfolios to calculate between corner portfolios *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *LowerBounds*: 1 x n vector of lower constituent exposure bounds (a vector of zeros, for example, is the “long-only” constraint) *UpperBounds*: 1 x n vector of upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures (a value of 1 is the “no leverage” constraint) ## Algorithm The Critical Line Algorithm is an “exact” method to generate the efficient frontier. Compared to other methods, the algorithm determines all corner portfolios directly. ## Remarks - See various publications by Harry Markowitz for details. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bounded.Frontier.Axb(nPointsInbetween, ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure, A, b, LowerPickMatrix, LowerValues, UpperPickMatrix, UpperValues) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.frontier.axb/ ## Result Calculates the bounded mean-variance efficient frontier with optional linear equality constraints A\*w = b and optional linear inequality constraints, using the critical line algorithm. Columns: volatility, return and constituent weights of the frontier portfolios, from the minimum variance to the maximum return portfolio. ## Syntax *nPointsInbetween*: number of frontier portfolios to calculate between two adjacent corner portfolios *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix. Singular matrices are allowed if the efficient portfolios are unique, e.g. zero-variance cash assets *LowerBounds*: 1 x n vector with lower constituent exposure bounds *UpperBounds*: 1 x n vector with upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *A*: optional; m x n matrix of the additional linear equality constraints A\*w = b, with m the number of equality constraints; default: no equality constraints *b*: optional; vector of the m values of the equality constraints A\*w = b, supplied together with A; default: no equality constraints *LowerPickMatrix*: optional; mL x n matrix of the inequality constraints LowerPickMatrix\*w \>= LowerValues, e.g. minimum group weights; default: no lower inequality constraints *LowerValues*: optional; vector of the mL lower constraint values, supplied together with LowerPickMatrix; default: no lower inequality constraints *UpperPickMatrix*: optional; mU x n matrix of the inequality constraints UpperPickMatrix\*w \<= UpperValues, e.g. maximum group weights or a limit on the short book; default: no upper inequality constraints *UpperValues*: optional; vector of the mU upper constraint values, supplied together with UpperPickMatrix; default: no upper inequality constraints ## Algorithm The corner portfolios are calculated with the critical line algorithm generalized to linear equality and inequality constraints, following Niedermayer and Niedermayer. ## Remarks The total exposure constraint and the bounds are combined with the optional constraints A\*w = b, LowerPickMatrix\*w \>= LowerValues and UpperPickMatrix\*w \<= UpperValues. The equality constraints must be linearly independent, and all constraints must be jointly feasible. Without A, b and inequality constraints, the result equals apaMeanVariance.Restricted.Bounded.Frontier. Each row of a pick matrix defines one constraint, e.g. a row with ones for the equity constituents and zeros elsewhere limits the total equity weight. Leave A and b empty if only inequality constraints are needed. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bounded.Frontier.Axb.xQxc(nPortfolios, ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure, A, b, LowerPickMatrix, LowerValues, UpperPickMatrix, UpperValues, Q, c) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.frontier.axb.xqxc/ ## Result Calculates the bounded mean-variance efficient frontier with a quadratic constraint w'Q\*w \<= c and optional linear equality and inequality constraints, using the quadratic critical line algorithm. Columns: volatility, return and constituent weights of nPortfolios frontier portfolios, from the minimum variance to the maximum return portfolio. ## Syntax *nPortfolios*: number of frontier portfolios to calculate, equally spaced in expected return from the minimum variance to the maximum return portfolio (at least 2) *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix. Singular matrices are allowed if the efficient portfolios are unique, e.g. zero-variance cash assets *LowerBounds*: 1 x n vector with lower constituent exposure bounds *UpperBounds*: 1 x n vector with upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *A*: optional; m x n matrix of the linear equality constraints A\*w = b, with m the number of equality constraints; supplied together with b; default: no equality constraints *b*: optional; vector of the m values of the equality constraints A\*w = b, supplied together with A; default: no equality constraints *LowerPickMatrix*: optional; mL x n matrix of the inequality constraints LowerPickMatrix\*w \>= LowerValues, e.g. minimum group weights; supplied together with LowerValues; default: no lower inequality constraints *LowerValues*: optional; vector of the mL lower constraint values, supplied together with LowerPickMatrix; default: no lower inequality constraints *UpperPickMatrix*: optional; mU x n matrix of the inequality constraints UpperPickMatrix\*w \<= UpperValues, e.g. maximum group weights or a limit on the short book; supplied together with UpperValues; default: no upper inequality constraints *UpperValues*: optional; vector of the mU upper constraint values, supplied together with UpperPickMatrix; default: no upper inequality constraints *Q*: n x n symmetric positive semidefinite matrix of the quadratic constraint w'Q\*w \<= c, e.g. a tracking error covariance matrix, or the identity matrix for a concentration limit *c*: upper limit of the quadratic constraint w'Q\*w \<= c, e.g. the squared tracking error, or 1/(effective number of assets) for Q = identity matrix ## Algorithm The quadratic constraint is handled by an exact homotopy: for θ in \[0, 1\], the critical line algorithm is applied to the trace-normalized matrix (1 - θ)Σ + θQ, subject to the bounds, the exposure constraint and the optional linear constraints. For each of the nPortfolios expected returns, equally spaced between the minimum variance return rMin and the maximum return rMax, the frontier portfolio of θ = 0 (no quadratic constraint) is used where the quadratic constraint is slack. Otherwise θ is bracketed and found by a safeguarded secant search such that w'Q\*w = c at the target return, which gives the exact optimum of the constrained problem; θ/(1 - θ) is the multiplier of the quadratic constraint. The minimum variance and maximum return portfolios are determined taking the quadratic constraint into account. The variance V(r) of the constrained frontier portfolio with expected return r is convex and non-decreasing between rMin and rMax. ## Remarks Each row of a pick matrix defines one constraint, e.g. a row with ones for the equity constituents and zeros elsewhere limits the total equity weight. Leave A and b empty if only inequality constraints are needed. The equality constraints must be linearly independent, and all constraints must be jointly feasible. If the minimum variance and the maximum return portfolio have the same expected return, a single row is returned. Without a quadratic constraint, use apaMeanVariance.Restricted.Bounded.Frontier.Axb, which returns the corner portfolios and nPointsInbetween portfolios between adjacent corner portfolios. With Q equal to the identity matrix, the quadratic constraint limits the Herfindahl concentration index of the weights, i.e. c = 1/N enforces at least N effective assets. The function is non-volatile. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bounded.Frontier.Resampled(nPointsInbetween, ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure, nSamples, SampleSize, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.frontier.resampled/ ## Result Resamples points on the mean-variance efficient frontier generated by Markowitz’s Critical Line Algorithm. Important: this is not the copyright-protected Resampled Efficient Frontier™ by Michaud. ## Syntax *nPointsInbetween*: number of frontier portfolios to calculate between corner portfolios *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *LowerBounds*: 1 x n vector of lower constituent exposure bounds (a vector of zeros, for example, is the “long-only” constraint) *UpperBounds*: 1 x n vector of upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures (a value of 1 is the “no leverage” constraint) *nSamples*: number of samples to generate *SampleSize*: number of observations in each sample *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: TRUE ## Algorithm The Critical Line Algorithm is an “exact” method to generate the efficient frontier. Compared to other methods, the algorithm determines all corner portfolios directly. ## Remarks Efficient frontiers are really expected efficient frontiers, in the sense that frontier portfolios are what investors can expect if they repeat the investment horizon many times. Resampling points on the efficient frontier highlights the fact that efficient frontiers are stochastic, not deterministic, results. Covariances of the resampled data are sample (denominator n − 1) or population (denominator n) covariances, set by IsSampleOtherwisePopulation; default: sample. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bounded.Frontier.Morphing(ExpectedReturnsMat, CovariancesVecMat, LowerBounds, UpperBounds, PortfolioExposure, Shrinkage) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.frontier.morphing/ ## Result Morphs between a set of mean-variance efficient frontiers (Critical Line Algorithm). The function is non-volatile. ## Syntax *ExpectedReturnsMat*: m x n matrix of m expected constituent return vectors, one per row *CovariancesVecMat*: m x n^2 matrix of m vectorized covariance matrices, one per row *LowerBounds*: 1 x n vector of lower constituent exposure bounds *UpperBounds*: 1 x n vector of upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *Shrinkage*: morph parameter between 1 (first frontier) and m (last frontier); any rational number in between is allowed Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bounded.Frontier.Trailing(nPointsInbetween, ExpectedReturnsMat, CovariancesVecMat, LowerBounds, UpperBounds, PortfolioExposure) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.frontier.trailing/ ## Result Calculates the mean-variance efficient frontier with Markowitz’s Critical Line Algorithm in a sequential (“trailing”) manner, one frontier per row of inputs. The function is non-volatile. ## Syntax *nPointsInbetween*: number of frontier portfolios to calculate between corner portfolios *ExpectedReturnsMat*: m x n matrix of m expected constituent return vectors, one per row *CovariancesVecMat*: m x n^2 matrix of m vectorized covariance matrices, one per row *LowerBounds*: 1 x n vector of lower constituent exposure bounds (a vector of zeros, for example, is the “long-only” constraint) *UpperBounds*: 1 x n vector of upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures (a value of 1 is the “no leverage” constraint) Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bounded.Frontier.xQxc(nPortfolios, ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure, Q, c) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.frontier.xqxc/ ## Result Calculates the bounded mean-variance efficient frontier with one additional quadratic constraint w'Q\*w \<= c. Columns: volatility, return and constituent weights of the frontier portfolios, from the minimum variance to the maximum return portfolio. ## Syntax *nPortfolios*: number of frontier portfolios to calculate, equally spaced in expected return (at least 2) *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix. Singular matrices are allowed if the efficient portfolios are unique, e.g. zero-variance cash assets *LowerBounds*: 1 x n vector with lower constituent exposure bounds *UpperBounds*: 1 x n vector with upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *Q*: n x n symmetric positive semidefinite matrix of the quadratic constraint w'Q\*w \<= c, e.g. a tracking error covariance matrix, or the identity matrix for a concentration limit *c*: upper limit of the quadratic constraint w'Q\*w \<= c, e.g. the squared tracking error, or 1/(effective number of assets) for Q = identity matrix ## Algorithm The feasible minimum variance and maximum return portfolios are determined, taking the quadratic constraint into account. ## Remarks With Q equal to the identity matrix, the constraint limits the Herfindahl concentration index of the weights, i.e. c = 1/N enforces at least N effective assets. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bounded.Weights.FromReturn(ReturnTarget, ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure, A, b, LowerPickMatrix, LowerValues, UpperPickMatrix, UpperValues, Q, c, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.weights.fromreturn/ ## Result Returns the 1 x n weights (optionally preceded by the portfolio volatility and expected return) of the restricted and bounded mean-variance efficient portfolio with a given expected return, i.e. the minimum variance portfolio subject to e'w \>= ReturnTarget, with optional linear equality and inequality constraints and an optional quadratic constraint w'Q\*w \<= c. ## Syntax *ReturnTarget*: expected return of the frontier portfolio *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix. Singular matrices are allowed if the efficient portfolios are unique, e.g. zero-variance cash assets *LowerBounds*: 1 x n vector with lower constituent exposure bounds *UpperBounds*: 1 x n vector with upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *A*: optional; m x n matrix of the linear equality constraints A\*w = b, with m the number of equality constraints; supplied together with b; default: no equality constraints *b*: optional; vector of the m values of the equality constraints A\*w = b, supplied together with A; default: no equality constraints *LowerPickMatrix*: optional; mL x n matrix of the inequality constraints LowerPickMatrix\*w \>= LowerValues, e.g. minimum group weights; supplied together with LowerValues; default: no lower inequality constraints *LowerValues*: optional; vector of the mL lower constraint values, supplied together with LowerPickMatrix; default: no lower inequality constraints *UpperPickMatrix*: optional; mU x n matrix of the inequality constraints UpperPickMatrix\*w \<= UpperValues, e.g. maximum group weights or a limit on the short book; supplied together with UpperValues; default: no upper inequality constraints *UpperValues*: optional; vector of the mU upper constraint values, supplied together with UpperPickMatrix; default: no upper inequality constraints *Q*: optional; n x n symmetric positive semidefinite matrix of the quadratic constraint w'Q\*w \<= c, e.g. a tracking error covariance matrix, or the identity matrix for a concentration limit; supplied together with c; default: no quadratic constraint *c*: optional; upper limit of the quadratic constraint w'Q\*w \<= c, e.g. the squared tracking error, or 1/(effective number of assets) for Q = identity matrix; supplied together with Q; default: no quadratic constraint *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns a 1 x (n + 2) row with the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights; FALSE returns the 1 x n weights only; default: FALSE ## Algorithm The solver depends on the optional constraints supplied. Without any optional constraint, the corner portfolios are calculated with the bounded critical line algorithm of apaMeanVariance.Restricted.Bounded.Frontier. With linear constraints only, the corner portfolios are calculated with the critical line algorithm generalized to linear equality and inequality constraints, following Niedermayer and Niedermayer, as in apaMeanVariance.Restricted.Bounded.Frontier.Axb. In both cases, the frontier is linear in the weights between two adjacent corner portfolios w(k) and w(k + 1): w(t) = w(k) + t d with d = w(k + 1) - w(k) and 0 \<= t \<= 1, its expected return R(t) = R(k) + t e'd is linear and its variance V(t) = V0 + L t + Q t² quadratic in t, with V0 = w(k)'Σw(k), L = 2 w(k)'Σd and Q = d'Σd. Without a quadratic constraint, the portfolio with the target return is obtained exactly by solving R(t) = ReturnTarget on the segment that contains the target. With Q and c, the quadratic constraint is handled by an exact homotopy: for θ in \[0, 1\], the critical line algorithm is applied to the trace-normalized matrix (1 - θ)Σ + θQ, subject to the bounds, the exposure constraint and the optional linear constraints. Where the quadratic constraint is slack, the frontier portfolio of θ = 0 (no quadratic constraint) is optimal. Otherwise θ is found by a safeguarded secant search such that w'Q\*w = c at the target return, which gives the exact optimum of the constrained problem; θ/(1 - θ) is the multiplier of the quadratic constraint. The minimum variance and maximum return portfolios are determined taking the quadratic constraint into account. The variance V(r) of the constrained frontier portfolio with expected return r is convex and non-decreasing between the minimum variance return rMin and the maximum return rMax. The portfolio with the target return is the exact constrained frontier portfolio at r = ReturnTarget. ## Remarks If ReturnTarget is below the expected return of the minimum variance portfolio, the return constraint is not binding and the minimum variance portfolio is returned. If ReturnTarget exceeds the expected return of the maximum return portfolio, no feasible portfolio exists and the function returns an error message. The results do not depend on the solver: a non-binding quadratic constraint gives the same portfolio as no quadratic constraint, up to round-off. Each row of a pick matrix defines one constraint, e.g. a row with ones for the equity constituents and zeros elsewhere limits the total equity weight. Leave A and b empty if only inequality constraints are needed. The equality constraints must be linearly independent, and all constraints must be jointly feasible. With Q equal to the identity matrix, the quadratic constraint limits the Herfindahl concentration index of the weights, i.e. c = 1/N enforces at least N effective assets. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Transform.Turnover(ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure, CurrentWeights, BuyCosts, SellCosts, TradeVariance, OutputType) URL: https://www.andreassteiner.net/help/apameanvariance.transform.turnover/ ## Result Returns one input of a bounded mean-variance problem with current weights w0 and proportional transaction costs, transformed so that it can be solved with the apaMeanVariance.Restricted.Bounded.Weights functions and apaMeanVariance.Restricted.Bounded.Frontier. Each function of the transformed problem receives the transformed ExpectedReturns, Covariances, LowerBounds, UpperBounds and PortfolioExposure, i.e. this function is called once per OutputType. The results are converted back into final weights, trades or turnover with apaMeanVariance.Transform.Turnover.Collapse. ## Syntax *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *LowerBounds*: 1 x n vector with lower bounds of the final constituent weights *UpperBounds*: 1 x n vector with upper bounds of the final constituent weights *PortfolioExposure*: total exposure of the final portfolio, i.e. the sum of the final constituent weights *CurrentWeights*: 1 x n vector with the current constituent weights w0; the final weights are w0 plus the trades *BuyCosts*: optional; proportional costs per unit bought, a single value or a 1 x n vector, in the units of ExpectedReturns (e.g. round-trip costs amortized over the holding period); must be non-negative; default: 0 *SellCosts*: optional; proportional costs per unit sold, a single value or a 1 x n vector, in the units of ExpectedReturns; must be non-negative; default: 0 *TradeVariance*: optional; positive variance added per squared unit bought or sold, i.e. a quadratic market-impact penalty, which keeps the transformed covariance matrix positive definite; default: 1E-6 x mean asset variance *OutputType*: optional; 0 transformed ExpectedReturns (1 x (2n + 1)), 1 transformed Covariances ((2n + 1) x (2n + 1)), 2 transformed LowerBounds, 3 transformed UpperBounds (both 1 x (2n + 1)), 4 transformed PortfolioExposure; default: 0 ## Algorithm The final weights are written as w = w0 + p + s with buys p \>= 0 and sells s \<= 0. The transformed problem has 2n + 1 variables: the current portfolio x0 fixed at 1, the n buys and the n sells. Its expected returns are (e'w0, e - BuyCosts, e + SellCosts), so that the expected return of a transformed portfolio is the expected return of the final portfolio net of the transaction costs. The transformed covariance matrix is the covariance matrix of the final portfolio expressed in these variables, \[\[w0'Σw0, w0'Σ, w0'Σ\], \[Σw0, Σ, Σ\], \[Σw0, Σ, Σ\]\], plus TradeVariance on the diagonal of the buy and sell blocks. The bounds of x0 are \[1, 1\]. The buys are bounded by \[max(0, LowerBounds - w0), max(0, UpperBounds - w0)\] and the sells by \[min(0, LowerBounds - w0), min(0, UpperBounds - w0)\], so that the final weights respect LowerBounds and UpperBounds, also if a current weight lies outside its bounds. The transformed PortfolioExposure is 1 + PortfolioExposure - sum(w0). Because buying and selling the same asset costs BuyCosts + SellCosts \> 0, the optimal solution never buys and sells the same asset. With zero costs, TradeVariance determines the split. ## Remarks The transformed problem is solved exactly by the FromRiskTolerance, FromReturn, FromVolatility, MVP, MRP and MSR variants of apaMeanVariance.Restricted.Bounded.Weights and by apaMeanVariance.Restricted.Bounded.Frontier, also with linear constraints (A, pick matrices) and a quadratic constraint (Q, c) on the 2n + 1 transformed variables. A linear row a'w on the final weights becomes the row (a'w0, a', a') on (x0, buys, sells). A turnover limit sum\|w - w0\| \<= L is the row (0, 1, ..., 1, -1, ..., -1) with UpperValues L; with CurrentWeights equal to zero, the same row limits the gross exposure sum\|w\|. A tracking-error cap (w - wb)'Σ(w - wb) \<= c becomes Q = M'ΣM with the n x (2n + 1) matrix M = \[w0 - wb, I, I\]; add TradeVariance to the diagonal of the buy and sell blocks of Q, because the quadratic solver can fail on the exactly singular M'ΣM. The volatilities and expected returns returned by functions solving the transformed problem include TradeVariance and are net of transaction costs. For the volatility of the final portfolio without TradeVariance, supply Covariances to apaMeanVariance.Transform.Turnover.Collapse. Volatilities are sample or population volatilities as Covariances is. A long-short portfolio with L1 penalty, such as a box-robust mean-variance problem with return uncertainty δ, follows with CurrentWeights equal to zero and BuyCosts = SellCosts = δ. # apaMeanVariance.Transform.Turnover.Collapse(Results, CurrentWeights, OutputType, Covariances) URL: https://www.andreassteiner.net/help/apameanvariance.transform.turnover.collapse/ ## Result Converts the results of a problem transformed with apaMeanVariance.Transform.Turnover into final weights, trades, buys, sells or turnover. Results may be weights (k x (2n + 1)) or rows with volatility, expected return and weights (k x (2n + 3)), e.g. a frontier or results with DoShowVolRetOtherwiseWeightsOnly = TRUE. ## Syntax *Results*: k x (2n + 1) weights or k x (2n + 3) rows with volatility, expected return and weights of the transformed problem *CurrentWeights*: 1 x n vector with the current constituent weights w0, as used in the transformation *OutputType*: optional; 0 final weights w0 + trades, preceded by volatility and expected return if Results has them (k x n or k x (n + 2)), 1 trades, 2 buys, 3 sells (negative), all k x n, 4 turnover sum\|trades\| (k x 1); default: 0 *Covariances*: optional; n x n covariance matrix; if supplied, the volatility in front of the final weights is recomputed as sqrt(w'Σw) of the final weights, i.e. without TradeVariance; default: volatility of the transformed problem ## Remarks The expected return in front of the final weights is the expected return net of transaction costs. The volatility is a sample or population volatility as Covariances is. If Results is an error message, it is returned unchanged. Rows of Results containing non-numeric cells (e.g. \#N/A) return \#N/A. # apaMeanVariance.Restricted.Bounded.Weights.FromRiskTolerance(RiskTolerance, ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure, A, b, LowerPickMatrix, LowerValues, UpperPickMatrix, UpperValues, Q, c, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.weights.fromrisktolerance/ ## Result Returns the 1 x n weights (optionally preceded by the portfolio volatility and expected return) of the restricted and bounded mean-variance efficient portfolio for a given risk tolerance, i.e. the portfolio that maximizes RiskTolerance \* e'w - w'Σw, with optional linear equality and inequality constraints and an optional quadratic constraint w'Q\*w \<= c. ## Syntax *RiskTolerance*: risk tolerance. Equals zero for the minimum variance portfolio (i.e. the portfolio of the most risk-averse investor) and increases until the maximum return portfolio is reached (i.e. the portfolio of the least risk-averse investor) *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix. Singular matrices are allowed if the efficient portfolios are unique, e.g. zero-variance cash assets *LowerBounds*: 1 x n vector with lower constituent exposure bounds *UpperBounds*: 1 x n vector with upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *A*: optional; m x n matrix of the linear equality constraints A\*w = b, with m the number of equality constraints; supplied together with b; default: no equality constraints *b*: optional; vector of the m values of the equality constraints A\*w = b, supplied together with A; default: no equality constraints *LowerPickMatrix*: optional; mL x n matrix of the inequality constraints LowerPickMatrix\*w \>= LowerValues, e.g. minimum group weights; supplied together with LowerValues; default: no lower inequality constraints *LowerValues*: optional; vector of the mL lower constraint values, supplied together with LowerPickMatrix; default: no lower inequality constraints *UpperPickMatrix*: optional; mU x n matrix of the inequality constraints UpperPickMatrix\*w \<= UpperValues, e.g. maximum group weights or a limit on the short book; supplied together with UpperValues; default: no upper inequality constraints *UpperValues*: optional; vector of the mU upper constraint values, supplied together with UpperPickMatrix; default: no upper inequality constraints *Q*: optional; n x n symmetric positive semidefinite matrix of the quadratic constraint w'Q\*w \<= c, e.g. a tracking error covariance matrix, or the identity matrix for a concentration limit; supplied together with c; default: no quadratic constraint *c*: optional; upper limit of the quadratic constraint w'Q\*w \<= c, e.g. the squared tracking error, or 1/(effective number of assets) for Q = identity matrix; supplied together with Q; default: no quadratic constraint *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns a 1 x (n + 2) row with the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights; FALSE returns the 1 x n weights only; default: FALSE ## Algorithm The solver depends on the optional constraints supplied. Without any optional constraint, the corner portfolios are calculated with the bounded critical line algorithm of apaMeanVariance.Restricted.Bounded.Frontier. With linear constraints only, the corner portfolios are calculated with the critical line algorithm generalized to linear equality and inequality constraints, following Niedermayer and Niedermayer, as in apaMeanVariance.Restricted.Bounded.Frontier.Axb. In both cases, the frontier is linear in the weights between two adjacent corner portfolios w(k) and w(k + 1): w(t) = w(k) + t d with d = w(k + 1) - w(k) and 0 \<= t \<= 1, its expected return R(t) = R(k) + t e'd is linear and its variance V(t) = V0 + L t + Q t² quadratic in t, with V0 = w(k)'Σw(k), L = 2 w(k)'Σd and Q = d'Σd. Without a quadratic constraint, the objective RiskTolerance \* R(t) - V(t) is maximized exactly on every segment, at t = (RiskTolerance \* e'd - L) / (2Q) clipped to \[0, 1\], and the best segment portfolio is returned. With Q and c, the quadratic constraint is handled by an exact homotopy: for θ in \[0, 1\], the critical line algorithm is applied to the trace-normalized matrix (1 - θ)Σ + θQ, subject to the bounds, the exposure constraint and the optional linear constraints. Where the quadratic constraint is slack, the frontier portfolio of θ = 0 (no quadratic constraint) is optimal. Otherwise θ is found by a safeguarded secant search such that w'Q\*w = c at the target return, which gives the exact optimum of the constrained problem; θ/(1 - θ) is the multiplier of the quadratic constraint. The minimum variance and maximum return portfolios are determined taking the quadratic constraint into account. The variance V(r) of the constrained frontier portfolio with expected return r is convex and non-decreasing between the minimum variance return rMin and the maximum return rMax. The objective RiskTolerance \* r - V(r) is therefore concave in r and is maximized by a golden-section search on r in \[rMin, rMax\], each candidate being the exact constrained frontier portfolio; the search stops when the return interval is below 1E-12 times rMax - rMin, and the end points rMin and rMax are compared as well. ## Remarks A negative risk tolerance is solved as \|RiskTolerance\| with the negative expected returns, i.e. it returns a portfolio on the inefficient branch. The results do not depend on the solver: a non-binding quadratic constraint gives the same portfolio as no quadratic constraint, up to round-off. Each row of a pick matrix defines one constraint, e.g. a row with ones for the equity constituents and zeros elsewhere limits the total equity weight. Leave A and b empty if only inequality constraints are needed. The equality constraints must be linearly independent, and all constraints must be jointly feasible. With Q equal to the identity matrix, the quadratic constraint limits the Herfindahl concentration index of the weights, i.e. c = 1/N enforces at least N effective assets. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bnbounded.Weights.FromRiskTolerance(RiskTolerance, ExpectedReturns, Covariances, PortfolioExposure) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bnbounded.weights.fromrisktolerance/ ## Result Returns the weights of the restricted mean-variance efficient portfolio for a given risk tolerance, without bounds on the constituent weights. ## Syntax *ExpectedReturns*: row vector containing expected returns *Covariances*: a covariance matrix *PortfolioExposure*: a real number representing the sum of asset exposures a portfolio is supposed to have (a value of 1 is the “no leverage” constraint) *Risk Tolerance:* risk tolerance. Zero for maximum risk aversion (i.e. the minimum variance investor), increasing towards plus infinity for minimum risk aversion (i.e. the maximum return investor) # apaMeanVariance.Restricted.Bounded.Weights.FromVolatility(VolatilityTarget, ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure, A, b, LowerPickMatrix, LowerValues, UpperPickMatrix, UpperValues, Q, c, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.weights.fromvolatility/ ## Result Returns the 1 x n weights (optionally preceded by the portfolio volatility and expected return) of the restricted and bounded mean-variance efficient portfolio with a given volatility, with optional linear equality and inequality constraints and an optional quadratic constraint w'Q\*w \<= c. ## Syntax *VolatilityTarget*: volatility of the frontier portfolio *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix. Singular matrices are allowed if the efficient portfolios are unique, e.g. zero-variance cash assets *LowerBounds*: 1 x n vector with lower constituent exposure bounds *UpperBounds*: 1 x n vector with upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *A*: optional; m x n matrix of the linear equality constraints A\*w = b, with m the number of equality constraints; supplied together with b; default: no equality constraints *b*: optional; vector of the m values of the equality constraints A\*w = b, supplied together with A; default: no equality constraints *LowerPickMatrix*: optional; mL x n matrix of the inequality constraints LowerPickMatrix\*w \>= LowerValues, e.g. minimum group weights; supplied together with LowerValues; default: no lower inequality constraints *LowerValues*: optional; vector of the mL lower constraint values, supplied together with LowerPickMatrix; default: no lower inequality constraints *UpperPickMatrix*: optional; mU x n matrix of the inequality constraints UpperPickMatrix\*w \<= UpperValues, e.g. maximum group weights or a limit on the short book; supplied together with UpperValues; default: no upper inequality constraints *UpperValues*: optional; vector of the mU upper constraint values, supplied together with UpperPickMatrix; default: no upper inequality constraints *Q*: optional; n x n symmetric positive semidefinite matrix of the quadratic constraint w'Q\*w \<= c, e.g. a tracking error covariance matrix, or the identity matrix for a concentration limit; supplied together with c; default: no quadratic constraint *c*: optional; upper limit of the quadratic constraint w'Q\*w \<= c, e.g. the squared tracking error, or 1/(effective number of assets) for Q = identity matrix; supplied together with Q; default: no quadratic constraint *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns a 1 x (n + 2) row with the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights; FALSE returns the 1 x n weights only; default: FALSE ## Algorithm The solver depends on the optional constraints supplied. Without any optional constraint, the corner portfolios are calculated with the bounded critical line algorithm of apaMeanVariance.Restricted.Bounded.Frontier. With linear constraints only, the corner portfolios are calculated with the critical line algorithm generalized to linear equality and inequality constraints, following Niedermayer and Niedermayer, as in apaMeanVariance.Restricted.Bounded.Frontier.Axb. In both cases, the frontier is linear in the weights between two adjacent corner portfolios w(k) and w(k + 1): w(t) = w(k) + t d with d = w(k + 1) - w(k) and 0 \<= t \<= 1, its expected return R(t) = R(k) + t e'd is linear and its variance V(t) = V0 + L t + Q t² quadratic in t, with V0 = w(k)'Σw(k), L = 2 w(k)'Σd and Q = d'Σd. Without a quadratic constraint, the segment that contains the target variance VolatilityTarget² is found and V(t) = VolatilityTarget² is solved exactly for t. With Q and c, the quadratic constraint is handled by an exact homotopy: for θ in \[0, 1\], the critical line algorithm is applied to the trace-normalized matrix (1 - θ)Σ + θQ, subject to the bounds, the exposure constraint and the optional linear constraints. Where the quadratic constraint is slack, the frontier portfolio of θ = 0 (no quadratic constraint) is optimal. Otherwise θ is found by a safeguarded secant search such that w'Q\*w = c at the target return, which gives the exact optimum of the constrained problem; θ/(1 - θ) is the multiplier of the quadratic constraint. The minimum variance and maximum return portfolios are determined taking the quadratic constraint into account. The variance V(r) of the constrained frontier portfolio with expected return r is convex and non-decreasing between the minimum variance return rMin and the maximum return rMax. With the quadratic constraint, the expected return r with V(r) = VolatilityTarget² is found by a safeguarded secant search on r, each candidate being the exact constrained frontier portfolio; the search stops when the variance deviates by at most 1E-12 times the target variance. ## Remarks If VolatilityTarget is below the volatility of the minimum variance portfolio, the minimum variance portfolio is returned; if it exceeds the volatility of the maximum return portfolio, the maximum return portfolio is returned. The results do not depend on the solver: a non-binding quadratic constraint gives the same portfolio as no quadratic constraint, up to round-off. Each row of a pick matrix defines one constraint, e.g. a row with ones for the equity constituents and zeros elsewhere limits the total equity weight. Leave A and b empty if only inequality constraints are needed. The equality constraints must be linearly independent, and all constraints must be jointly feasible. With Q equal to the identity matrix, the quadratic constraint limits the Herfindahl concentration index of the weights, i.e. c = 1/N enforces at least N effective assets. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bounded.Weights.MRP(ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure, A, b, LowerPickMatrix, LowerValues, UpperPickMatrix, UpperValues, Q, c, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.weights.mrp/ ## Result Returns the 1 x n weights (optionally preceded by the portfolio volatility and expected return) of the restricted and bounded maximum return portfolio with optional linear equality and inequality constraints and an optional quadratic constraint w'Q\*w \<= c. ## Syntax *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix. With optional constraints, if several portfolios have the maximum expected return, the one with the lowest variance is returned *LowerBounds*: 1 x n vector with lower constituent exposure bounds *UpperBounds*: 1 x n vector with upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *A*: optional; m x n matrix of the linear equality constraints A\*w = b, with m the number of equality constraints; supplied together with b; default: no equality constraints *b*: optional; vector of the m values of the equality constraints A\*w = b, supplied together with A; default: no equality constraints *LowerPickMatrix*: optional; mL x n matrix of the inequality constraints LowerPickMatrix\*w \>= LowerValues, e.g. minimum group weights; supplied together with LowerValues; default: no lower inequality constraints *LowerValues*: optional; vector of the mL lower constraint values, supplied together with LowerPickMatrix; default: no lower inequality constraints *UpperPickMatrix*: optional; mU x n matrix of the inequality constraints UpperPickMatrix\*w \<= UpperValues, e.g. maximum group weights or a limit on the short book; supplied together with UpperValues; default: no upper inequality constraints *UpperValues*: optional; vector of the mU upper constraint values, supplied together with UpperPickMatrix; default: no upper inequality constraints *Q*: optional; n x n symmetric positive semidefinite matrix of the quadratic constraint w'Q\*w \<= c, e.g. a tracking error covariance matrix, or the identity matrix for a concentration limit; supplied together with c; default: no quadratic constraint *c*: optional; upper limit of the quadratic constraint w'Q\*w \<= c, e.g. the squared tracking error, or 1/(effective number of assets) for Q = identity matrix; supplied together with Q; default: no quadratic constraint *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns a 1 x (n + 2) row with the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights; FALSE returns the 1 x n weights only; default: FALSE ## Algorithm Without any optional constraint, the maximum return portfolio is calculated by filling the constituents with the highest expected returns first; Covariances is not used. With linear constraints only, the maximum return portfolio is the last corner portfolio of the critical line algorithm generalized to linear equality and inequality constraints, following Niedermayer and Niedermayer, as in apaMeanVariance.Restricted.Bounded.Frontier.Axb. With Q and c, the maximum return portfolio of the linear problem is returned if it satisfies the quadratic constraint. Otherwise, the critical line path that minimizes w'Q\*w subject to the linear constraints is calculated. If its maximum return portfolio satisfies the quadratic constraint, the result is the maximum return end point of the homotopy described for apaMeanVariance.Restricted.Bounded.Frontier.Axb.xQxc; otherwise it is the point on that path with w'Q\*w = c, which is the highest expected return compatible with the quadratic constraint. ## Remarks The results do not depend on the solver: a non-binding quadratic constraint gives the same portfolio as no quadratic constraint, up to round-off. Each row of a pick matrix defines one constraint, e.g. a row with ones for the equity constituents and zeros elsewhere limits the total equity weight. Leave A and b empty if only inequality constraints are needed. The equality constraints must be linearly independent, and all constraints must be jointly feasible. With Q equal to the identity matrix, the quadratic constraint limits the Herfindahl concentration index of the weights, i.e. c = 1/N enforces at least N effective assets. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bounded.Weights.MSR(ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure, A, b, LowerPickMatrix, LowerValues, UpperPickMatrix, UpperValues, Q, c, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.weights.msr/ ## Result Returns the 1 x n weights (optionally preceded by the portfolio volatility and expected return) of the restricted and bounded maximum Sharpe ratio portfolio with optional linear equality and inequality constraints and an optional quadratic constraint w'Q\*w \<= c. The Sharpe ratio is calculated with a risk-free rate of zero. ## Syntax *ExpectedReturns*: 1 x n vector with expected constituent returns (excess returns over the risk-free rate) *Covariances*: n x n covariance matrix *LowerBounds*: 1 x n vector of lower constituent exposure bounds *UpperBounds*: 1 x n vector of upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures (a value of 1 is the “no leverage” constraint) *A*: optional; m x n matrix of the linear equality constraints A\*w = b, with m the number of equality constraints; supplied together with b; default: no equality constraints *b*: optional; vector of the m values of the equality constraints A\*w = b, supplied together with A; default: no equality constraints *LowerPickMatrix*: optional; mL x n matrix of the inequality constraints LowerPickMatrix\*w \>= LowerValues, e.g. minimum group weights; supplied together with LowerValues; default: no lower inequality constraints *LowerValues*: optional; vector of the mL lower constraint values, supplied together with LowerPickMatrix; default: no lower inequality constraints *UpperPickMatrix*: optional; mU x n matrix of the inequality constraints UpperPickMatrix\*w \<= UpperValues, e.g. maximum group weights or a limit on the short book; supplied together with UpperValues; default: no upper inequality constraints *UpperValues*: optional; vector of the mU upper constraint values, supplied together with UpperPickMatrix; default: no upper inequality constraints *Q*: optional; n x n symmetric positive semidefinite matrix of the quadratic constraint w'Q\*w \<= c, e.g. a tracking error covariance matrix, or the identity matrix for a concentration limit; supplied together with c; default: no quadratic constraint *c*: optional; upper limit of the quadratic constraint w'Q\*w \<= c, e.g. the squared tracking error, or 1/(effective number of assets) for Q = identity matrix; supplied together with Q; default: no quadratic constraint *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns a 1 x (n + 2) row with the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights; FALSE returns the 1 x n weights only; default: FALSE ## Algorithm The Sharpe ratio is calculated with a risk-free rate of zero: ``` math SR(w) = \frac{e^{\top}w}{\sqrt{w^{\top}\Sigma w}} ``` If the maximum Sharpe ratio is positive, the maximizing portfolio lies on the efficient frontier. The function therefore calculates the corner portfolios of the efficient frontier with the critical line algorithm, as in apaMeanVariance.Restricted.Bounded.Frontier, or, with linear constraints, with the critical line algorithm generalized to linear equality and inequality constraints, following Niedermayer and Niedermayer, as in apaMeanVariance.Restricted.Bounded.Frontier.Axb, from the minimum variance portfolio to the maximum return portfolio. Between two adjacent corner portfolios w(k) and w(k + 1), the frontier is linear in the weights, its return is linear and its variance quadratic in the segment parameter t: ``` math w(t) = w_{k} + t\, d,\quad\quad R(t) = R_{k} + \Delta R\, t,\quad\quad V(t) = V_{0} + L\, t + Q\, t^{2},\quad\quad t \in \lbrack 0,1\rbrack ``` with d = w(k + 1) - w(k), ΔR = e'd, V0 = w(k)'Σw(k), L = 2 w(k)'Σd and Q = d'Σd. The derivative of R(t) / sqrt(V(t)) has the sign of a linear function of t, so the Sharpe ratio has at most one stationary point on each segment: ``` math t^{*} = \frac{R_{k}\, L/2 - \Delta R\, V_{0}}{\Delta R\, L/2 - R_{k}\, Q} ``` The function evaluates the Sharpe ratio at both corner portfolios of every segment and at the stationary point if 0 \< t \< 1, and returns the portfolio with the highest value. Apart from the corner portfolios of the critical line algorithm, the solution is exact and requires no iterations. With Q and c, the quadratic constraint is handled by an exact homotopy: for θ in \[0, 1\], the critical line algorithm is applied to the trace-normalized matrix (1 - θ)Σ + θQ, subject to the bounds, the exposure constraint and the optional linear constraints. Where the quadratic constraint is slack, the frontier portfolio of θ = 0 (no quadratic constraint) is optimal. Otherwise θ is found by a safeguarded secant search such that w'Q\*w = c at the target return, which gives the exact optimum of the constrained problem; θ/(1 - θ) is the multiplier of the quadratic constraint. The minimum variance and maximum return portfolios are determined taking the quadratic constraint into account. The variance V(r) of the constrained frontier portfolio with expected return r is convex and non-decreasing between the minimum variance return rMin and the maximum return rMax. Because V(r) is convex, the Sharpe ratio r / sqrt(V(r)) is unimodal in r and is maximized by a golden-section search on r in \[rMin, rMax\], each candidate being the exact constrained frontier portfolio; the search stops when the return interval is below 1E-12 times rMax - rMin, and the end points are compared as well. ## Remarks Because the risk-free rate is zero, the expected returns should be excess returns over the risk-free rate. A cash asset is then entered with an expected return of 0 and a zero row and column in the covariance matrix. All combinations of cash and the tangency portfolio have the same Sharpe ratio; in that case the function returns the tangency portfolio without cash. If the minimum variance portfolio has zero volatility and a positive expected return, e.g. a cash asset with a positive excess return, the Sharpe ratio is unbounded and the function returns an error message. To absorb round-off errors, returns below 1E-12 times the largest absolute expected return and variances below 1E-14 times the largest variance (both scaled with the portfolio exposure) are treated as zero. If no feasible portfolio has a positive expected return, the function returns the frontier portfolio with the least negative Sharpe ratio. That portfolio is not a tangency portfolio and should be interpreted with care. The Sharpe ratio does not change if all weights are multiplied by a positive factor. With bounds proportional to the portfolio exposure, the weights therefore scale with the exposure. With a portfolio exposure of 0, the maximum is in general not unique, and the function returns the first maximizing frontier portfolio, whose leverage depends on the bounds. Negative portfolio exposures are allowed but the resulting Sharpe ratios are difficult to interpret. Duplicate assets, i.e. assets with identical covariances, leave the efficient portfolios non-unique, and the function returns the error message of the critical line algorithm. apaMeanVariance.Strategies.MostDiversified.Weights.FromCovars uses the same algorithm with the volatilities as expected returns. The results do not depend on the solver: a non-binding quadratic constraint gives the same portfolio as no quadratic constraint, up to round-off. Each row of a pick matrix defines one constraint, e.g. a row with ones for the equity constituents and zeros elsewhere limits the total equity weight. Leave A and b empty if only inequality constraints are needed. The equality constraints must be linearly independent, and all constraints must be jointly feasible. With Q equal to the identity matrix, the quadratic constraint limits the Herfindahl concentration index of the weights, i.e. c = 1/N enforces at least N effective assets. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bounded.Weights.MVP(Covariances, LowerBounds, UpperBounds, PortfolioExposure, A, b, LowerPickMatrix, LowerValues, UpperPickMatrix, UpperValues, Q, c, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.weights.mvp/ ## Result Returns the 1 x n weights (optionally preceded by the portfolio volatility and expected return) of the restricted and bounded minimum variance portfolio with optional linear equality and inequality constraints and an optional quadratic constraint w'Q\*w \<= c. ## Syntax *Covariances*: n x n covariance matrix. Singular matrices are allowed if the efficient portfolios are unique, e.g. zero-variance cash assets *LowerBounds*: 1 x n vector with lower constituent exposure bounds *UpperBounds*: 1 x n vector with upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *A*: optional; m x n matrix of the linear equality constraints A\*w = b, with m the number of equality constraints; supplied together with b; default: no equality constraints *b*: optional; vector of the m values of the equality constraints A\*w = b, supplied together with A; default: no equality constraints *LowerPickMatrix*: optional; mL x n matrix of the inequality constraints LowerPickMatrix\*w \>= LowerValues, e.g. minimum group weights; supplied together with LowerValues; default: no lower inequality constraints *LowerValues*: optional; vector of the mL lower constraint values, supplied together with LowerPickMatrix; default: no lower inequality constraints *UpperPickMatrix*: optional; mU x n matrix of the inequality constraints UpperPickMatrix\*w \<= UpperValues, e.g. maximum group weights or a limit on the short book; supplied together with UpperValues; default: no upper inequality constraints *UpperValues*: optional; vector of the mU upper constraint values, supplied together with UpperPickMatrix; default: no upper inequality constraints *Q*: optional; n x n symmetric positive semidefinite matrix of the quadratic constraint w'Q\*w \<= c, e.g. a tracking error covariance matrix, or the identity matrix for a concentration limit; supplied together with c; default: no quadratic constraint *c*: optional; upper limit of the quadratic constraint w'Q\*w \<= c, e.g. the squared tracking error, or 1/(effective number of assets) for Q = identity matrix; supplied together with Q; default: no quadratic constraint *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns a 1 x (n + 2) row with the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return, which is \#N/A because the function has no expected returns argument, and the n constituent weights; FALSE returns the 1 x n weights only; default: FALSE ## Algorithm Without a quadratic constraint, the minimum variance portfolio is calculated with the critical line algorithm (generalized to linear equality and inequality constraints if supplied, following Niedermayer and Niedermayer) using zero expected returns, so that the frontier collapses to the minimum variance portfolio. With Q and c, the minimum variance portfolio of the linear problem is returned if it satisfies the quadratic constraint. Otherwise, the trace-normalized matrix (1 - θ)Σ + θQ is minimized subject to the bounds, the exposure constraint and the optional linear constraints, with θ found by a safeguarded secant search such that w'Q\*w = c, which gives the exact constrained minimum variance portfolio. ## Remarks The results do not depend on the solver: a non-binding quadratic constraint gives the same portfolio as no quadratic constraint, up to round-off. Each row of a pick matrix defines one constraint, e.g. a row with ones for the equity constituents and zeros elsewhere limits the total equity weight. Leave A and b empty if only inequality constraints are needed. The equality constraints must be linearly independent, and all constraints must be jointly feasible. With Q equal to the identity matrix, the quadratic constraint limits the Herfindahl concentration index of the weights, i.e. c = 1/N enforces at least N effective assets. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Bounded.Weights.Resampled.FromRiskTolerance(RiskTolerance, ExpectedReturns, Covariances, LowerBounds, UpperBounds, PortfolioExposure, nSamples, SampleSize, UncertaintyType, IsSampleOtherwisePopulation, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.bounded.weights.resampled.fromrisktolerance/ ## Result Calculates the composition of a resampled portfolio on the Markowitz mean-variance efficient frontier for a given risk tolerance, i.e. the average of the optimal portfolios across resampled inputs. Important: this is not the Resampled Efficient Frontier by Michaud, which is copyright protected. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *RiskTolerance*: risk tolerance, i.e. the slope of the efficient frontier at the portfolio *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *LowerBounds*: 1 x n vector with lower constituent exposure bounds *UpperBounds*: 1 x n vector with upper constituent exposure bounds *PortfolioExposure*: value of the equality constraint on total portfolio exposure as the sum of constituent exposures *nSamples*: number of samples to generate *SampleSize*: number of observations in each sample *UncertaintyType*: 1 = uncertainty about both returns and covariances, 2 = uncertainty about covariances only, 3 = uncertainty about returns only *IsSampleOtherwisePopulation*: optional; TRUE for sample covariances (division by n-1), FALSE for population covariances (division by n); default: FALSE *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE ## Algorithm nSamples return samples of size SampleSize are simulated from a multivariate normal distribution with the given expected returns and covariances. ## Remarks The averaged portfolio satisfies the bounds and the total exposure constraint, but it is generally not efficient with respect to the original inputs. Covariances of the resampled data are sample (denominator n − 1) or population (denominator n) covariances, set by IsSampleOtherwisePopulation; default: population. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Unbounded.Frontier(nPointsInbetween, ExpectedReturns, Covariances, PortfolioExposure, MaximumReturn) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.frontier/ ## Result Calculates the restricted and unbounded mean-variance efficient frontier, from the minimum variance portfolio up to a given maximum return. ## Syntax *nPointsInbetween*: number of frontier portfolios to calculate *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *MaximumReturn*: return of the portfolio defining the upper end of the frontier Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Unbounded.Hyperbola.Center(ExpectedReturns, Covariances, PortfolioExposure) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.hyperbola.center/ ## Result Returns the coordinates of the center of the hyperbola which describes the restricted and unbounded efficient frontier in return/volatility space. ## Syntax *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image77.svg) > ![Formula](https://www.andreassteiner.net/help/assets/eq/image78.svg) Center of hyperbola: ![Formula](https://www.andreassteiner.net/help/assets/eq/image79.svg) # apaMeanVariance.Restricted.Unbounded.Hyperbola.Slope(ExpectedReturns, Covariances, PortfolioExposure) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.hyperbola.slope/ ## Result Returns the slope of the asymptote of the hyperbola which describes the restricted and unbounded efficient frontier in return/volatility space. ## Syntax *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image77.svg) > ![Formula](https://www.andreassteiner.net/help/assets/eq/image80.svg) > > ![Formula](https://www.andreassteiner.net/help/assets/eq/image81.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image82.svg) Asymptotes: ![Formula](https://www.andreassteiner.net/help/assets/eq/image83.svg) # apaMeanVariance.Restricted.Unbounded.IR.Frontier(nPointsInbetween, ExpectedReturns, Covariances, PortfolioExposure, BenchmarkWeights, MaximumTE) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.ir.frontier/ ## Result Calculates the information ratio efficient frontier, i.e. the frontier of portfolios with maximum active return per unit of tracking error (TE) relative to a benchmark, in return/volatility space. ## Syntax *nPointsInbetween*: number of frontier portfolios to calculate *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *BenchmarkWeights*: 1 x n vector of benchmark weights *MaximumTE*: tracking error (TE) of the active portfolio defining the upper end of the frontier Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Unbounded.IR.Frontier.ActiveReturnTESpace(nPoints, ExpectedReturns, Covariances, PortfolioExposure, BenchmarkWeights, MaximumTE) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.ir.frontier.activereturntespace/ ## Result Calculates the information ratio efficient frontier in active return/tracking error (TE) space. ## Syntax *nPoints*: number of frontier portfolios to calculate *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *BenchmarkWeights*: 1 x n vector of benchmark weights *MaximumTE*: tracking error (TE) of the active portfolio defining the upper end of the frontier Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Unbounded.LinearEqualityConstraints.Axb.Frontier(nPointsInbetween, ExpectedReturns, Covariances, A, b, MaximumReturn) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.linearequalityconstraints.axb.frontier/ ## Result Calculates the restricted and unbounded mean-variance efficient frontier subject to general linear equality constraints A\*w = b. ## Syntax *nPointsInbetween*: number of frontier portfolios to calculate between the minimum variance portfolio and the (imposed) maximum return portfolio *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *A*: m x n matrix of left-hand side parameters of the equality constraints A\*w = b, with m the number of equality constraints and n the number of assets *b*: m x 1 vector of right-hand side parameters of the equality constraints A\*w = b *MaximumReturn*: return of the portfolio defining the upper end of the frontier Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Unbounded.LinearEqualityConstraints.Axb.Weights.FromReturn(PortfolioReturn, ExpectedReturns, Covariances, A, b, MaximumReturn, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.linearequalityconstraints.axb.weights.fromreturn/ ## Result Returns the weights of the restricted and unbounded mean-variance efficient portfolio with a given return, subject to general linear equality constraints A\*w = b. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *PortfolioReturn*: return of the frontier portfolio *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *A*: m x n matrix of left-hand side parameters of the equality constraints A\*w = b, with m the number of equality constraints and n the number of assets *b*: m x 1 vector of right-hand side parameters of the equality constraints A\*w = b *MaximumReturn*: return of the portfolio defining the upper end of the frontier *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE # apaMeanVariance.Restricted.Unbounded.LinearEqualityConstraints.Axb.Weights.MVP(Covariances, A, b, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.linearequalityconstraints.axb.weights.mvp/ ## Result Returns the weights of the restricted and unbounded minimum variance portfolio subject to general linear equality constraints A\*w = b. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *Covariances*: n x n covariance matrix *A*: m x n matrix of left-hand side parameters of the equality constraints A\*w = b, with m the number of equality constraints and n the number of assets *b*: m x 1 vector of right-hand side parameters of the equality constraints A\*w = b *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return, which is \#N/A because the function has no expected returns argument, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE # apaMeanVariance.Restricted.Unbounded.LinearEqualityConstraints.Frontier(nPointsInbetween, ExpectedReturns, Covariances, PortfolioExposure, Betas, PortfolioBetas, MaximumReturn) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.linearequalityconstraints.frontier/ ## Result Calculates the restricted and unbounded mean-variance efficient frontier subject to additional linear equality constraints on portfolio betas. ## Syntax *nPointsInbetween*: number of frontier portfolios to calculate *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *Betas*: m x n matrix of betas, with m the number of additional linear equality constraints *PortfolioBetas*: m x 1 vector of target portfolio betas *MaximumReturn*: return of the portfolio defining the upper end of the frontier Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Unbounded.LinearEqualityConstraints.Weights.FromReturn(PortfolioReturn, ExpectedReturns, Covariances, PortfolioExposure, Betas, PortfolioBetas, MaximumReturn, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.linearequalityconstraints.weights.fromreturn/ ## Result Returns the weights of the restricted and unbounded mean-variance efficient portfolio with a given return, subject to additional linear equality constraints on portfolio betas. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *PortfolioReturn*: return of the frontier portfolio *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *Betas*: m x n matrix of betas, with m the number of additional linear equality constraints *PortfolioBetas*: m x 1 vector of target portfolio betas *MaximumReturn*: return of the portfolio defining the upper end of the frontier *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE # apaMeanVariance.Restricted.Unbounded.LinearEqualityConstraints.Weights.MVP(Covariances, PortfolioExposure, Betas, PortfolioBetas, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.linearequalityconstraints.weights.mvp/ ## Result Returns the weights of the restricted and unbounded minimum variance portfolio subject to additional linear equality constraints on portfolio betas. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *Betas*: m x n matrix of betas, with m the number of additional linear equality constraints *PortfolioBetas*: m x 1 vector of target portfolio betas *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return, which is \#N/A because the function has no expected returns argument, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE # apaMeanVariance.Restricted.Unbounded.Return.FromVolatility(VolatilityTarget, ExpectedReturns, Covariances, PortfolioExposure) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.return.fromvolatility/ ## Result Calculates the return of the restricted and unbounded frontier portfolio with a given volatility. ## Syntax *VolatilityTarget*: volatility of the frontier portfolio *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures # apaMeanVariance.Restricted.Unbounded.TE.Frontier(nPointsInBetween, ExpectedReturns, Covariances, PortfolioExposure, BenchmarkWeights, TE) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.te.frontier/ ## Result Calculates the constant tracking error (TE) frontier in return/volatility space, i.e. the efficient part of the TE ellipse around the benchmark. ## Syntax *nPointsInBetween*: number of portfolios to calculate between the minimum and the maximum volatility portfolios on the ellipse *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *BenchmarkWeights*: 1 x n vector of benchmark weights *TE*: target tracking error Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Unbounded.TE.Frontier.Ellipse(nPointsInBetween, ExpectedReturns, Covariances, PortfolioExposure, BenchmarkWeights, TE) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.te.frontier.ellipse/ ## Result Calculates the constant tracking error (TE) ellipse around a benchmark portfolio in return/volatility space. ## Syntax *nPointsInBetween*: number of portfolios to calculate between the minimum and the maximum volatility portfolios on the ellipse *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *BenchmarkWeights*: 1 x n vector of benchmark weights *TE*: target tracking error Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Restricted.Unbounded.TE.Frontier.SpecialPortfolios(ExpectedReturns, Covariances, PortfolioExposure, BenchmarkWeights, TE) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.te.frontier.specialportfolios/ ## Result Returns the volatility, return and composition of special portfolios on the constant tracking error (TE) frontier: ## Syntax *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *BenchmarkWeights*: 1 x n vector of benchmark weights *TE*: target tracking error # apaMeanVariance.Restricted.Unbounded.TE.Weights.FromVolatility(PortfolioVolatility, ExpectedReturns, Covariances, PortfolioExposure, BenchmarkWeights, TE, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.te.weights.fromvolatility/ ## Result Returns the composition of the portfolio on the constant tracking error (TE) frontier with a given volatility. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *PortfolioVolatility*: volatility of the portfolio on the TE frontier *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *BenchmarkWeights*: 1 x n vector of benchmark weights *TE*: target tracking error *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE # apaMeanVariance.Restricted.Unbounded.Volatility.FromReturn(ReturnTarget, ExpectedReturns, Covariances, PortfolioExposure) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.volatility.fromreturn/ ## Result Calculates the volatility of the restricted and unbounded frontier portfolio with a given return. ## Syntax *ReturnTarget*: return of the frontier portfolio *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures # apaMeanVariance.Restricted.Unbounded.Weights.FromVolatility(VolatilityTarget, ExpectedReturns, Covariances, PortfolioExposure, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.weights.fromvolatility/ ## Result Returns the weights of the restricted and unbounded mean-variance efficient portfolio with a given volatility. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *VolatilityTarget*: volatility of the frontier portfolio *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures (a value of 1 is the “no leverage” constraint) *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE # apaMeanVariance.Restricted.Unbounded.Weights.FromReturn(ReturnTarget, ExpectedReturns, Covariances, PortfolioExposure, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.weights.fromreturn/ ## Result Returns the weights of the restricted and unbounded mean-variance efficient portfolio with a given return. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *ReturnTarget*: return of the frontier portfolio *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures (a value of 1 is the “no leverage” constraint) *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE # apaMeanVariance.Restricted.Unbounded.Weights.FromRiskTolerance(RiskTolerance, ExpectedReturns, Covariances, PortfolioExposure, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.weights.fromrisktolerance/ ## Result Returns the weights of the restricted and unbounded mean-variance efficient portfolio for a given risk tolerance. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *RiskTolerance*: risk tolerance. Equals zero for the minimum variance portfolio (i.e. the portfolio of the most risk-averse investor) and increases towards plus infinity for less risk-averse investors *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures (a value of 1 is the “no leverage” constraint) *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE # apaMeanVariance.Restricted.Unbounded.Weights.MSR(ExpectedReturns, Covariances, PortfolioExposure, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.weights.msr/ ## Result Returns the weights of the restricted and unbounded maximum Sharpe ratio portfolio. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *ExpectedReturns*: 1 x n vector with expected constituent returns *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures (a value of 1 is the “no leverage” constraint) *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE ## Remarks - The calculations assume that the expected returns represent excess returns. - A numerical procedure is used to determine the asset weights. With certain inputs, the procedure can take long to find a result or not find a result at all. # apaMeanVariance.Restricted.Unbounded.Weights.MVP(Covariances, PortfolioExposure, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.restricted.unbounded.weights.mvp/ ## Result Returns the weights of the restricted and unbounded minimum variance portfolio. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *Covariances*: n x n covariance matrix *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures (a value of 1 is the “no leverage” constraint) *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return, which is \#N/A because the function has no expected returns argument, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE # apaMeanVariance.Strategies.MostDiversified.Weights.FromCovars(Covariances, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.strategies.mostdiversified.weights.fromcovars/ ## Result Returns the constituent weights of the fully invested and long-only “most diversified” portfolio, i.e. the portfolio which maximizes the risk reduction from imperfectly correlated assets. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *Covariances*: n x n covariance matrix *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return, which is \#N/A because the function has no expected returns argument, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE ## Algorithm A numerical algorithm is used to determine the constituent weights. ## Remarks The “most diversified” portfolio is the portfolio with the maximum diversification ratio. See apaDiversificationRatio for more details. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Strategies.RiskBudgeting.Weights.FromCovars(RiskBudget, Covariances, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.strategies.riskbudgeting.weights.fromcovars/ ## Result Returns the constituent weights of the fully invested and long-only risk budgeting portfolio, i.e. the portfolio which implements a target vector of percentage volatility contributions. The weights are positive, sum to 1, and the percentage contribution of each asset to portfolio volatility (as calculated by apaContribution.Volatility) equals its risk budget. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *RiskBudget*: 1 x n vector of target percentage contributions to portfolio volatility; budgets must be non-negative and are normalized to sum to 1; assets with a budget of 0 receive a weight of 0 *Covariances*: n x n covariance matrix; must be positive semidefinite *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return, which is \#N/A because the function has no expected returns argument, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE ## Algorithm With the risk budgets b(i) normalized to sum to 1 and the covariance matrix Σ, the risk budgeting portfolio solves ``` math \min_{w > 0}\mspace{6mu}\frac{1}{2}\ln\left( w^{\top}\Sigma w \right) - \sum_{i = 1}^{n}b_{i}\ln w_{i}\quad\quad\text{subject to}\quad\mathbf{1}^{\top}w = 1 ``` At the optimum, the percentage contribution of each asset to portfolio variance, and therefore also to portfolio volatility, equals its budget: ``` math \frac{w_{i}(\Sigma w)_{i}}{w^{\top}\Sigma w} = b_{i},\quad\quad i = 1,\ldots,n ``` Because the budgets sum to 1, the objective does not change if all weights are multiplied by a positive constant. The budget constraint therefore only fixes the scale, and the function solves the equivalent unconstrained and strictly convex problem of Spinu (2013), followed by a normalization of the solution: ``` math \min_{y > 0}\mspace{6mu} F(y) = \frac{1}{2}y^{\top}\Sigma y - \sum_{i = 1}^{n}b_{i}\ln y_{i},\quad\quad w = \frac{y}{\mathbf{1}^{\top}y} ``` The first-order conditions y(i) (Σy)(i) = b(i) are exactly the risk budgeting conditions. F is minimized with a damped Newton method. Gradient, Hessian, Newton decrement λ and update are ``` math g_{i} = (\Sigma y)_{i} - \frac{b_{i}}{y_{i}},\quad\quad H = \Sigma + diag\left( \frac{b_{i}}{y_{i}^{2}} \right) ``` ``` math \lambda = \sqrt{g^{\top}H^{- 1}g},\quad\quad y \leftarrow y - s\, H^{- 1}g,\quad\quad s = \left\{ \begin{matrix} 1/(1 + \lambda) & \lambda > 0.95\,(3 - \sqrt{5})/2 \\ 1 & \text{otherwise} \end{matrix} \right.\ ``` The iteration starts at y = b / sqrt(b'Σb). The Hessian is positive definite, and each Newton system is solved with a Cholesky factorization. The damped steps guarantee convergence from any starting point (F is self-concordant), and once the Newton decrement is small, full Newton steps converge quadratically. Steps are additionally shortened if necessary to keep all y(i) strictly positive. The iteration stops when λ falls below 1E-12, which typically takes fewer than 20 iterations; the risk contributions then match the budgets to machine precision. ## Remarks For a positive semidefinite covariance matrix and positive budgets, the solution exists and is unique, because the logarithmic terms keep all weights strictly positive. Singular covariance matrices, e.g. with duplicated assets, are accepted; matrices that are not positive semidefinite return an error message. The portfolio is long-only and fully invested; additional bounds or linear constraints are not supported, because with binding constraints the budgets can in general no longer be met. apaMeanVariance.Strategies.RiskParity.Weights.FromCovars is the special case with equal budgets. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Strategies.RiskParity.Robust.Weights.FromCovars(Covariances, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.strategies.riskparity.robust.weights.fromcovars/ ## Result Returns the constituent weights of the fully invested and long-only robust risk parity portfolio, i.e. the equal volatility contribution portfolio assuming equal correlations. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *Covariances*: n x n covariance matrix *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return, which is \#N/A because the function has no expected returns argument, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE ## Algorithm The weight of each asset in this portfolio is calculated as: ![Formula](https://www.andreassteiner.net/help/assets/eq/image84.svg) # apaMeanVariance.Strategies.RiskParity.Weights.FromCovars(Covariances, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.strategies.riskparity.weights.fromcovars/ ## Result Returns the constituent weights of the fully invested and long-only risk parity portfolio, i.e. the portfolio with equal contributions to portfolio volatility. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *Covariances*: n x n covariance matrix; must be positive semidefinite *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return, which is \#N/A because the function has no expected returns argument, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE ## Algorithm The risk parity portfolio is the risk budgeting portfolio with equal budgets b(i) = 1/n, i.e. the portfolio in which every asset contributes the same share of portfolio volatility: ``` math w_{i}(\Sigma w)_{i} = \frac{1}{n}\, w^{\top}\Sigma w,\quad\quad i = 1,\ldots,n ``` The weights are determined exactly as in apaMeanVariance.Strategies.RiskBudgeting.Weights.FromCovars: the convex problem of Spinu (2013) is minimized with a damped Newton method, and the solution is normalized to sum to 1. See that function for the formulas and the convergence properties. The risk contributions match 1/n to machine precision. ## Remarks The equal volatility contribution portfolio is also called the “risk parity portfolio” or “equal risk contribution portfolio”. If all correlations are equal, it coincides with the inverse volatility portfolio of apaMeanVariance.Strategies.RiskParity.Robust.Weights.FromCovars; with two assets this holds for any correlation. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Strategies.RiskParity.Hierarchical.Weights.FromCovars(Covariances, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.strategies.riskparity.hierarchical.weights.fromcovars/ ## Result Returns the constituent weights of the fully invested and long-only hierarchical risk parity (HRP) portfolio. HRP allocates capital by clustering assets, reordering the covariance structure and assigning weights through recursive bisection, rather than by inverting the covariance matrix. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *Covariances*: n x n covariance matrix *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return, which is \#N/A because the function has no expected returns argument, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE ## Algorithm The correlation structure implied by the covariance matrix is used to construct a hierarchical clustering of the assets. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Strategies.MaximumDecorrelation.FromCorrels(Correls) URL: https://www.andreassteiner.net/help/apameanvariance.strategies.maximumdecorrelation.fromcorrels/ ## Result Returns the constituent weights of the fully invested and long-only maximum decorrelation portfolio, i.e. the portfolio which minimizes the aggregate correlation exposure. ## Syntax *Correls*: n x n correlation matrix ## Algorithm The weights minimize w′Cw subject to full investment and no short sales: ``` math \min_{w}\mspace{6mu} w^{\top}C\, w,\quad\quad\sum_{i = 1}^{n}w_{i} = 1,\quad\quad w_{i} \geq 0 ``` where C is the correlation matrix. Unlike minimum variance methods, the maximum decorrelation approach uses correlations rather than covariances, so the asset volatilities do not affect the weights. The problem is the long-only minimum variance problem with C in place of the covariance matrix and is solved exactly with the critical line algorithm. ## Remarks The function returns an error message if the correlation matrix is singular, for example if there are more assets than observations or if an asset is a linear combination of others, since the optimal weights are then not unique. In this case, use a shrinkage estimator or apaCorrels.Fix. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Unrestricted.Unbounded.Frontier(nPointsInbetween, ExpectedReturns, Covariances, MinimumReturn, MaximumReturn) URL: https://www.andreassteiner.net/help/apameanvariance.unrestricted.unbounded.frontier/ ## Result Calculates the unrestricted and unbounded mean-variance efficient frontier. The first two columns of the result contain the volatilities and returns, the remaining n columns the constituent weights. ## Syntax *nPointsInbetween*: number of frontier portfolios to calculate between the minimum and maximum return portfolios *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *MinimumReturn*: return of the left-most frontier portfolio to calculate *MaximumReturn*: return of the right-most frontier portfolio to calculate Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaMeanVariance.Unrestricted.Unbounded.Weights.FromReturn(PortfolioReturn, ExpectedReturns, Covariances, DoShowVolRetOtherwiseWeightsOnly) URL: https://www.andreassteiner.net/help/apameanvariance.unrestricted.unbounded.weights.fromreturn/ ## Result Returns the composition of the portfolio with a given return on the unrestricted and unbounded mean-variance efficient frontier. Optionally, the portfolio volatility and expected return are shown in front of the weights. ## Syntax *PortfolioReturn*: target return of the portfolio *ExpectedReturns*: 1 x n vector of expected constituent returns *Covariances*: n x n covariance matrix *DoShowVolRetOtherwiseWeightsOnly*: optional; TRUE returns the portfolio volatility sqrt(w'Σw), calculated from Covariances and therefore a sample or population volatility as Covariances is, the portfolio expected return e'w, and the n constituent weights, i.e. a 1 x (n + 2) row; FALSE returns the weights only; default: FALSE # apaModifiedSharpeRatio(PortfolioReturns, RiskfreeReturns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apamodifiedsharperatio/ ## Result Calculates the modified Sharpe ratio, i.e. the average excess return divided by the modified value at risk (VaR). ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *RiskfreeReturns*: r x 1 vector of riskfree returns, or a single riskfree return *ConfidenceLevel*: confidence level of the modified VaR, e.g. 95% ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image85.svg) ## Remarks Uses population volatility, skewness and excess kurtosis (denominator n). # apaModifiedZScore(TimeSeries) URL: https://www.andreassteiner.net/help/apamodifiedzscore/ ## Result Calculates modified z-scores, i.e. deviations from the median in units of the median absolute deviation (MAD). ## Syntax *TimeSeries*: r x 1 data vector containing a time series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image86.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image87.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image88.svg) ## Remarks Both the median and the MAD are robust alternatives to the arithmetic average and the standard deviation. This makes apaModifiedZScore a robust alternative to apaZScore. # apaModigliani.M2(Returns, BenchmarkReturns, RiskfreeReturns, DoShowExcessOverBenchmark) URL: https://www.andreassteiner.net/help/apamodigliani.m2/ ## Result Returns the Modigliani risk-adjusted performance M², i.e. the return the portfolio would have earned at the volatility of the benchmark. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *BenchmarkReturns*: r x 1 vector (shared by all columns) or r x c matrix of benchmark returns *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 *DoShowExcessOverBenchmark*: optional; TRUE returns M² minus the mean benchmark return, FALSE returns M²; default: FALSE ## Algorithm M² = mean(rf) + mean(r − rf) / s(r − rf) · s(rb − rf) (Modigliani and Modigliani 1997). ## Remarks The result is a 1 x c row vector with one value per column of Returns. The ratio of standard deviations is the same for sample and population estimates. The result has the frequency of the input data. # apaMoments.All.Population.ShowStdev(DataMatrix, DoShowMoreOtherwiseShow) URL: https://www.andreassteiner.net/help/apamoments.all.population.showstdev/ ## Result Returns a table with the first four moments of all assets (population versions): mean, standard deviation (volatility), skewness and excess kurtosis. ## Syntax *DataMatrix*: r x c data matrix, each column containing a series *DoShowMoreOtherwiseShow*: optional; TRUE to show additional statistics (minimum, maximum), FALSE otherwise; default: FALSE # apaMoments.All.Population.ShowVariance(DataMatrix, DoNotShowMoreOtherwiseShow) URL: https://www.andreassteiner.net/help/apamoments.all.population.showvariance/ ## Result Returns a table with the first four moments of all assets (population versions): mean, variance, skewness and excess kurtosis. ## Syntax *DataMatrix*: r x c data matrix, each column containing a series *DoNotShowMoreOtherwiseShow*: optional; TRUE to show additional statistics (minimum, maximum, AR correlations), FALSE otherwise; default: FALSE # apaMoments.Rolling(TimeSeries, Nth, MomentType, WindowSize, DoCalcAllOtherwiseNth) URL: https://www.andreassteiner.net/help/apamoments.rolling/ ## Result Calculates rolling moments of various types (raw, central, standardized). Returns population moments (division by n, not n-1). The standardized fourth moment is the kurtosis (not excess kurtosis). The result is a rolling moment series or matrix, depending on the calculation mode. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *Nth*: order of the moment to calculate, e.g. 3 for skewness *MomentType*: moment type: 1 = raw, 2 = central, 3 = standardized *WindowSize*: size of the rolling data window *DoCalcAllOtherwiseNth*: TRUE to calculate the moments of order 1 up to Nth, FALSE to calculate the moment of order Nth only # apaMoments.TimeAggregation.Continuous(Returns, MaxIntegration, IsStartAtLastOtherwiseFirst, IsExtrapolOtherwiseTrunc) URL: https://www.andreassteiner.net/help/apamoments.timeaggregation.continuous/ ## Result Calculates the first four central and standardized moments of time-aggregated time series data. ## Syntax *Returns*: a return time series *MaxIntegration*: maximum number of times to aggregate the data *IsStartAtLastOtherwiseFirst*: TRUE to time-aggregate starting at the end of the time series, FALSE to start at the beginning *IsExtrapolOtherwiseTrunc*: TRUE to extrapolate missing data, FALSE to truncate excess observations in the time aggregation ## Remarks - “Time aggregation” refers to calculating, for example, weekly data by summing 5 daily observations or annual data by summing 12 monthly observations. # apaModifiedZScore.Outlier(TimeSeries) URL: https://www.andreassteiner.net/help/apamodifiedzscore.outlier/ ## Result Flags outliers based on modified z-scores: \* for \|z\| \>= 1, \*\* for \|z\| \>= 2 and \*\*\* for \|z\| \>= 3. ## Syntax *TimeSeries*: r x 1 data vector containing a time series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image89.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image90.svg) # apaMPPM(Returns, RiskfreeReturns, RiskAversion, PeriodsPerYear) URL: https://www.andreassteiner.net/help/apamppm/ ## Result Returns the manipulation-proof performance measure (MPPM), an annualized certainty-equivalent excess log return under power utility. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 *RiskAversion*: optional; relative risk aversion ρ (at least 0); 1 gives the mean log excess growth rate; default: 3 *PeriodsPerYear*: optional; number of return periods per year used to annualize the result, e.g. 12 for monthly data; default: 1 (per-period result) ## Algorithm MPPM = 1 / ((1 − ρ)·Δt) · ln( mean( ((1 + r) / (1 + rf))^(1 − ρ) ) ), with Δt = 1 / PeriodsPerYear (Goetzmann, Ingersoll, Spiegel and Welch 2007). For ρ = 1: MPPM = mean(ln((1 + r) / (1 + rf))) / Δt. ## Remarks The result is a 1 x c row vector with one value per column of Returns. Returns are discrete returns and must be greater than −1. The measure cannot be inflated by option-like return manipulation. # apaMultinomialLogit.Estimate(X, Y) URL: https://www.andreassteiner.net/help/apamultinomiallogit.estimate/ ## Result Estimates a multinomial logistic regression model by maximum likelihood and returns diagnostics, coefficients and in-sample predictions. The function is non-volatile. ## Syntax *X*: n x p matrix of predictors (an intercept is added automatically) *Y*: n x 1 vector of the dependent variable with integer classes 1..K ## Algorithm Class K is the reference category. For the classes k = 1..K - 1 the probabilities are ``` math P(y_{i} = k) = \frac{exp(x_{i}^{\top}\beta_{k})}{1 + \sum_{l = 1}^{K - 1}\exp(x_{i}^{\top}\beta_{l})},\quad\quad P(y_{i} = K) = \frac{1}{1 + \sum_{l = 1}^{K - 1}\exp(x_{i}^{\top}\beta_{l})} ``` where the vector x(i) of observation i includes a 1 for the intercept. The log-likelihood is concave in the coefficients and is maximized with Newton's method, using the exact gradient and Hessian, a backtracking line search and a Cholesky decomposition of the Hessian. The predictors are standardized internally, and the coefficients are transformed back to the units of X, so the result does not depend on the scaling of the predictors. The iteration stops when the Newton decrement falls below 1E-15 relative to the log-likelihood, typically after 4 to 10 iterations. ## Remarks The result consists of three blocks. The diagnostics block contains the log-likelihood, the negative log-likelihood, AIC, BIC, the numbers of observations, predictors, classes and parameters, the termination reason (Converged or IterationLimit), the number of Newton iterations (FunctionEvaluations), RestartCount (always 0) and the largest absolute element of the gradient at the solution with respect to the standardized coefficients (ErrorValue). The coefficient block contains one row per class 1..K - 1 with the intercept and the predictor coefficients. The last block contains, for each observation, the actual class, the predicted class (highest probability) and the K class probabilities. If some classes can be predicted perfectly or almost perfectly from the predictors (separation), the maximum likelihood coefficients are infinite, and the function returns an error message. The function also returns an error message if a predictor is constant (the intercept is already included) or if the predictors are collinear. Predictors are standardized internally with population moments (denominator n); the coefficients are reported on the original scale. # apaNaturalSpline(XValue, X, Y) URL: https://www.andreassteiner.net/help/apanaturalspline/ ## Result Natural spline interpolation. ## Syntax *XValue*: value at which to interpolate *X*: r x 1 vector of observations in dataset X *Y*: r x 1 vector of observations in dataset Y # apaNChooseK.All(n, k) URL: https://www.andreassteiner.net/help/apanchoosek.all/ ## Result Returns all combinations of k out of n items. The result is a (number of combinations) x n matrix, which can get very large very quickly. ## Syntax *n*: number of items available *k*: number of items selected # apaNChooseK.Count(n, k) URL: https://www.andreassteiner.net/help/apanchoosek.count/ ## Result Counts all possible combinations of k out of n items. The figures become very large very quickly. ## Syntax *n*: number of items available *k*: number of items selected # apaNChooseK.Random(n, k, s, DoAllowSubsets) URL: https://www.andreassteiner.net/help/apanchoosek.random/ ## Result Randomly selects k out of n items. Returns an indicator vector. ## Syntax *n*: number of items available *k*: number of items selected *s*: number of selections *DoAllowSubsets*: TRUE to select 1 to k items (subset resampling), FALSE to select k items (classical bootstrapping) # apaNelsonSiegel.ForwardRate(dT, beta0, beta1, beta2, tau1) URL: https://www.andreassteiner.net/help/apanelsonsiegel.forwardrate/ ## Result Calculates the forward rate from Nelson-Siegel yield curve parameters. ## Syntax *dT*: time to maturity in years *beta0*: Nelson-Siegel parameter beta0 (level) *beta1*: Nelson-Siegel parameter beta1 (slope) *beta2*: Nelson-Siegel parameter beta2 (curvature) *tau1*: Nelson-Siegel decay parameter tau1 ## Remarks - Time to maturity is calculated based on the 30/360 day count convention. - Continuous discount factor. # apaNelsonSiegel.PV(SettleDate, MaturityDate, Coupon, Frequency, beta0, beta1, beta2, tau1) URL: https://www.andreassteiner.net/help/apanelsonsiegel.pv/ ## Result Calculates the present value of a bond, in % of face value, discounted with a Nelson-Siegel term structure. ## Syntax *SettleDate*: settlement date of the valuation (“valuation date”, typically today’s date) *MaturityDate*: final maturity date *Coupon*: coupon in % of face value *Frequency*: number of coupon payments per year *beta0*: Nelson-Siegel parameter beta0 (level) *beta1*: Nelson-Siegel parameter beta1 (slope) *beta2*: Nelson-Siegel parameter beta2 (curvature) *tau1*: Nelson-Siegel decay parameter tau1 ## Algorithm Calculates the present value of the nominal and the coupon stream based on the yields derived from the specified Nelson-Siegel yield curve. ## Remarks - Time to maturity is calculated based on the 30/360 day count convention. - Continuous discount factor. # apaNelsonSiegel.Yield(dT, beta0, beta1, beta2, tau1) URL: https://www.andreassteiner.net/help/apanelsonsiegel.yield/ ## Result Calculates the spot rate (yield) from Nelson-Siegel yield curve parameters. ## Syntax *dT*: time to maturity in years *beta0*: Nelson-Siegel parameter beta0 (level) *beta1*: Nelson-Siegel parameter beta1 (slope) *beta2*: Nelson-Siegel parameter beta2 (curvature) *tau1*: Nelson-Siegel decay parameter tau1 ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image91.svg) # apaNelsonSiegel.Estimate(ObservedYields, ObservedMaturities, IsRandomInitGuess) URL: https://www.andreassteiner.net/help/apanelsonsiegel.estimate/ ## Result Estimates the Nelson-Siegel parameters beta0, beta1, beta2 and tau1 by fitting observed yields. ## Syntax *ObservedYields*: 1 x n vector of observed yields *ObservedMaturities*: 1 x n vector of observed maturities in years, in ascending order *IsRandomInitGuess*: TRUE for a random initial guess of the parameters, FALSE for a deterministic one ## Algorithm Numerical minimization of the sum of squared differences between the empirical and the fitted yield curve. # apaNelsonSiegel.ConstantTau.Estimate(ObservedYields, ObservedMaturities, Tau) URL: https://www.andreassteiner.net/help/apanelsonsiegel.constanttau.estimate/ ## Result Estimates the Nelson-Siegel parameters beta0, beta1 and beta2 by fitting observed yields, for a given (constant) decay parameter tau1. ## Syntax *ObservedYields*: 1 x n vector of observed yields *ObservedMaturities*: 1 x n vector of observed maturities in years, in ascending order *Tau*: Nelson-Siegel decay parameter tau1 ## Algorithm OLS estimation procedure of Diebold et al. # apaNelsonSiegelSvensson.ForwardRate(dT, beta0, beta1, beta2, beta3, tau1, tau2) URL: https://www.andreassteiner.net/help/apanelsonsiegelsvensson.forwardrate/ ## Result Calculates the forward rate from Nelson-Siegel-Svensson yield curve parameters. ## Syntax *dT*: time to maturity in years *beta0*: Nelson-Siegel parameter beta0 (level) *beta1*: Nelson-Siegel parameter beta1 (slope) *beta2*: Nelson-Siegel parameter beta2 (curvature) *beta3*: svensson parameter beta3 (second curvature) *tau1*: Nelson-Siegel decay parameter tau1 *tau2*: svensson decay parameter tau2 ## Remarks - Time to maturity is calculated based on the 30/360 day count convention. - Continuous discount factor. # apaNelsonSiegelSvensson.PV(SettleDate, MaturityDate, Coupon, Frequency, beta0, beta1, beta2, beta3, tau1, tau2) URL: https://www.andreassteiner.net/help/apanelsonsiegelsvensson.pv/ ## Result Calculates the present value of a bond, in % of face value, discounted with a Nelson-Siegel-Svensson term structure. ## Syntax *SettleDate*: settlement date of the valuation (“valuation date”, typically today’s date) *MaturityDate*: final maturity date *Coupon*: coupon in % of face value *Frequency*: number of coupon payments per year *beta0*: Nelson-Siegel parameter beta0 (level) *beta1*: Nelson-Siegel parameter beta1 (slope) *beta2*: Nelson-Siegel parameter beta2 (curvature) *beta3*: svensson parameter beta3 (second curvature) *tau1*: Nelson-Siegel decay parameter tau1 *tau2*: svensson decay parameter tau2 ## Algorithm Calculates the present value of the nominal and the coupon stream based on the yields derived from the specified Nelson-Siegel-Svensson yield curve. ## Remarks - Time to maturity is calculated based on the 30/360 day count convention. - Continuous discount factor. # apaNelsonSiegelSvensson.Yield(dT, beta0, beta1, beta2, beta3, tau1, tau2) URL: https://www.andreassteiner.net/help/apanelsonsiegelsvensson.yield/ ## Result Calculates the spot rate (yield) from Nelson-Siegel-Svensson yield curve parameters. ## Syntax *dT*: time to maturity in years *beta0*: Nelson-Siegel parameter beta0 (level) *beta1*: Nelson-Siegel parameter beta1 (slope) *beta2*: Nelson-Siegel parameter beta2 (curvature) *beta3*: svensson parameter beta3 (second curvature) *tau1*: Nelson-Siegel decay parameter tau1 *tau2*: svensson decay parameter tau2 ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image92.svg) # apaNelsonSiegelSvensson.Estimate(ObservedYields, ObservedMaturities, IsRandomInitGuess) URL: https://www.andreassteiner.net/help/apanelsonsiegelsvensson.estimate/ ## Result Estimates the Nelson-Siegel-Svensson parameters beta0 to beta3, tau1 and tau2 by fitting observed yields. ## Syntax *ObservedYields*: 1 x n vector of observed yields *ObservedMaturities*: 1 x n vector of observed maturities in years, in ascending order *IsRandomInitGuess*: TRUE for a random initial guess of the parameters, FALSE for a deterministic one ## Algorithm Numerical minimization of the sum of squared differences between the empirical and the fitted yield curve. # apaNinv(Probability, Mean, StandardDeviation) URL: https://www.andreassteiner.net/help/apaninv/ ## Result Inverse cumulative distribution function of the normal distribution. ## Syntax *Probability*: probability between 0 and 1 *Mean*: location parameter (mean) of the normal distribution *StandardDeviation*: dispersion parameter (standard deviation) of the normal distribution # apaNsim(nObs, nSeries, Mean, StandardDeviation) URL: https://www.andreassteiner.net/help/apansim/ ## Result Returns time series of random numbers drawn from a normal distribution. ## Syntax *nObs*: number of observations to generate *nSeries*: number of time series to generate *Mean*: location parameter (mean) of the normal distribution *StandardDeviation*: dispersion parameter (standard deviation) of the normal distribution ## Remarks This function is volatile, i.e. it is recalculated whenever a change occurs, even if not related to the function’s output. The function is also recalculated when pressing F9. # apaNsim.Multivariate(nSims, Means, Covars) URL: https://www.andreassteiner.net/help/apansim.multivariate/ ## Result Simulates random values from a multivariate normal distribution. ## Syntax *nSims*: number of observations to generate *Means*: 1 x n vector of means (first moments) *Covars*: n x n covariance matrix (second moments) ## Algorithm Based on the Cholesky decomposition of the covariance matrix. # apaNIGarg(m, v, S, k) URL: https://www.andreassteiner.net/help/apanigarg/ ## Result Returns the parameters alpha, beta, mu and delta (4 x 1, in this order) of the normal inverse Gaussian (NIG) distribution with the given mean, variance, skewness and kurtosis. ## Syntax *m*: mean *v*: variance; must be positive *S*: skewness *k*: kurtosis (not excess kurtosis); must exceed 3 + (5/3)·S² ## Remarks Note that the NIG distribution is only defined when the kurtosis (not excess kurtosis) exceeds 3 + (5/3)·S², where S is the skewness. The moments are the population moments of the distribution. To use estimates from data, pass e.g. the sample variance and 3 + the sample excess kurtosis; apaNIGest does this directly. An excess kurtosis must be converted by adding 3; e.g. k = 0 is not feasible. A non-positive variance or a kurtosis at or below the bound returns an error message. # apaNIGarg.randomized(m_lb, m_ub, v_lb, v_ub, s_lb, s_ub, k_lb, k_ub) URL: https://www.andreassteiner.net/help/apanigarg.randomized/ ## Result Returns a set of random NIG parameters implied by moments drawn randomly between lower and upper bounds. ## Syntax *m_lb*: lower bound of the mean *m_ub*: upper bound of the mean *v_lb*: lower bound of the variance; must be positive *v_ub*: upper bound of the variance; must be positive *s_lb*: lower bound of the skewness *s_ub*: upper bound of the skewness *k_lb*: lower bound of the kurtosis (not excess kurtosis) *k_ub*: upper bound of the kurtosis (not excess kurtosis) ## Remarks The NIG distribution is only defined when the kurtosis (not excess kurtosis) exceeds 3 + (5/3)·S², where S is the skewness. If the random kurtosis value is too small, it is increased until the set of NIG parameters is valid. A non-positive variance bound or a non-finite bound returns an error message. # apaNIGcdf(x, alpha, beta, mu, delta) URL: https://www.andreassteiner.net/help/apanigcdf/ ## Result Cumulative distribution function of the normal inverse Gaussian (NIG) distribution. ## Syntax *x*: value at which to evaluate the function *alpha*: NIG parameter alpha (tail heaviness) *beta*: NIG parameter beta (asymmetry) *mu*: NIG parameter mu (location) *delta*: NIG parameter delta (scale) ## Remarks Note that the NIG distribution is only defined when the kurtosis (not excess kurtosis) exceeds 3 + (5/3)·S², where S is the skewness. # apaNIGest(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apanigest/ ## Result Estimates the NIG parameters alpha, beta, mu and delta for each time series by moment matching. Returns a 4 x c matrix, each column containing the parameters of the corresponding time series. ## Syntax *TimeSeriesMatrix*: r x c data matrix, each column containing a time series ## Algorithm Moment matching. ## Remarks Note that the NIG distribution is only defined when the kurtosis (not excess kurtosis) exceeds 3 + (5/3)·S², where S is the skewness. Matches the sample mean, sample variance (n − 1), sample skewness and sample excess kurtosis (as Excel SKEW and KURT). Each column is estimated separately and needs at least 4 observations and must not be constant. With more than one column, columns that cannot be estimated show \#N/A; with a single column, an error message is returned. # apaNIGinv(probability, alpha, beta, mu, delta) URL: https://www.andreassteiner.net/help/apaniginv/ ## Result Inverse cumulative distribution function of the normal inverse Gaussian (NIG) distribution. ## Syntax *probability*: probability *alpha*: NIG parameter alpha (tail heaviness) *beta*: NIG parameter beta (asymmetry) *mu*: NIG parameter mu (location) *delta*: NIG parameter delta (scale) ## Remarks Note that the NIG distribution is only defined when the kurtosis (not excess kurtosis) exceeds 3 + (5/3)·S², where S is the skewness. # apaNIGmom(alpha, beta, mu, delta) URL: https://www.andreassteiner.net/help/apanigmom/ ## Result Returns the first four moments implied by the four parameters of the normal inverse Gaussian (NIG) distribution: mean, variance, skewness and kurtosis (not excess kurtosis). ## Syntax *alpha*: NIG parameter alpha (tail heaviness) *beta*: NIG parameter beta (asymmetry) *mu*: NIG parameter mu (location) *delta*: NIG parameter delta (scale) ## Remarks Note that the NIG distribution is only defined when the kurtosis (not excess kurtosis) exceeds 3 + (5/3)·S², where S is the skewness. # apaNIGsim(n, alpha, beta, mu, delta) URL: https://www.andreassteiner.net/help/apanigsim/ ## Result Returns a vector of random values drawn from a normal inverse Gaussian (NIG) distribution. ## Syntax *n*: number of observations to simulate *alpha*: NIG parameter alpha (tail heaviness) *beta*: NIG parameter beta (asymmetry) *mu*: NIG parameter mu (location) *delta*: NIG parameter delta (scale) ## Remarks This function is volatile, i.e. it is recalculated whenever a change occurs, even if not related to the function’s output. The function is also recalculated when pressing F9. Note that the NIG distribution is only defined when the kurtosis (not excess kurtosis) exceeds 3 + (5/3)·S², where S is the skewness. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaNIGsim.randomized(n, m_lb, m_ub, v_lb, v_ub, s_lb, s_ub, k_lb, k_ub, AC1_lb, AC1_ub) URL: https://www.andreassteiner.net/help/apanigsim.randomized/ ## Result Returns a vector of random values drawn from a NIG distribution with randomized moments, drawn between lower and upper bounds, and a randomized first order autocorrelation. ## Syntax *n*: number of observations to simulate *m_lb*: lower bound of the mean *m_ub*: upper bound of the mean *v_lb*: lower bound of the variance; must be positive *v_ub*: upper bound of the variance; must be positive *s_lb*: lower bound of the skewness *s_ub*: upper bound of the skewness *k_lb*: lower bound of the kurtosis (not excess kurtosis) *k_ub*: upper bound of the kurtosis (not excess kurtosis) *AC1_lb*: lower bound of the first order autocorrelation *AC1_ub*: upper bound of the first order autocorrelation ## Remarks The NIG distribution is only defined when the kurtosis (not excess kurtosis) exceeds 3 + (5/3)·S², where S is the skewness. If the random kurtosis value is too small, it is increased such that the random skewness value becomes feasible. A non-positive variance bound or a non-finite bound returns an error message. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaNIGsim.Correlated(nSims, NIGparameters, Correlations, Method) URL: https://www.andreassteiner.net/help/apanigsim.correlated/ ## Result Simulates correlated normal inverse Gaussian (NIG) distributed random variables whose Pearson correlations equal the target correlations. Returns an nSims x c matrix, each column containing a variable. ## Syntax *nSims*: number of observations to simulate *NIGparameters*: 4 x c matrix of NIG parameters alpha, beta, mu and delta (rows), each column containing a variable *Correlations*: c x c target Pearson correlation matrix of the NIG variables *Method*: optional; 0 = normal variance-mean mixture with independent mixing variables, 1 = Gaussian copula with exact NIG marginals; default: 0 ## Algorithm Method 0: each variable is a normal variance-mean mixture X(j) = mu(j) + beta(j)·Z(j) + √Z(j)·W(j), where the mixing variables Z(j) are independent inverse Gaussian draws with parameters delta(j) and gamma(j) = √(alpha(j)² − beta(j)²), and W is multivariate standard normal with correlation matrix R. The Pearson correlation of the NIG variables is Corr(X(i), X(j)) = R(i,j)·m(i,j), with m(i,j) = E\[√Z(i)\]·E\[√Z(j)\] / √(Var X(i)·Var X(j)), E\[√Z\] = √(delta/gamma)·K0(delta·gamma) / K1/2(delta·gamma) and Var X = delta·alpha² / gamma³. R is set to R(i,j) = Correlations(i,j) / m(i,j). *Method 0:* Gaussian copula X(j) = F(j)⁻¹(Φ(W(j))), where F(j) is the NIG cdf of variable j and W is multivariate standard normal with correlation matrix R. F(j)⁻¹(Φ(z)) is tabulated on a fine grid from the numerically integrated NIG density, with exponential tails beyond the grid. For each pair, R(i,j) is found by bisection such that the Pearson correlation of X(i) and X(j), computed from the Hermite expansion Σk ck(i)·ck(j)·R(i,j)^k / (σ(i)·σ(j)), equals Correlations(i,j). *Method 1* is the NORTA (normal to anything) method of Cario and Nelson (1997); the Hermite expansion of the Pearson correlation as a polynomial in R(i,j) follows Xiao and Zhou (2019). Cario, M. C. and Nelson, B. L. (1997), Modeling and generating random vectors with arbitrary marginal distributions and correlation matrix, Technical Report, Department of Industrial Engineering and Management Sciences, Northwestern University, https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.48.281. Xiao, Q. and Zhou, S. (2019), Matching a correlation coefficient by a Gaussian copula, Communications in Statistics – Theory and Methods 48(7), 1728–1747, https://doi.org/10.1080/03610926.2018.1439962. ## Remarks Correlations are population (distribution) correlations; the sample correlations of a simulated matrix deviate from them by sampling error. Both methods reproduce the NIG marginals and the target Pearson correlations. In Method 0 the attainable absolute correlation is limited to m(i,j) \< 1, which decreases with heavier tails and stronger skewness; observed correlations of heavy-tailed return series may exceed it. Method 1 builds the quantile tables once per call and attains correlations up to those of perfectly comonotonic or countermonotonic variables (close to ±1 for similar marginals) and produces joint tail events. A target outside the attainable range (the error message states the range), a set of targets for which R is not positive semi-definite, invalid parameters (alpha must exceed \|beta\|, delta must be positive) and a Correlations matrix that is not a valid correlation matrix return an error message. The function is volatile and the results change with each recalculation. Pressing Esc aborts the calculation; the function then returns "Calculation aborted by user." # apaNIGpdf(x, alpha, beta, mu, delta) URL: https://www.andreassteiner.net/help/apanigpdf/ ## Result Probability density function of the normal inverse Gaussian (NIG) distribution. ## Syntax *x*: value at which to evaluate the function *alpha*: NIG parameter alpha (tail heaviness) *beta*: NIG parameter beta (asymmetry) *mu*: NIG parameter mu (location) *delta*: NIG parameter delta (scale) ## Remarks Note that the NIG distribution is only defined when the kurtosis (not excess kurtosis) exceeds 3 + (5/3)·S², where S is the skewness. # apaNIGrnd(alpha, beta, mu, delta) URL: https://www.andreassteiner.net/help/apanigrnd/ ## Result Returns a random value drawn from a normal inverse Gaussian (NIG) distribution. ## Syntax *alpha*: NIG parameter alpha (tail heaviness) *beta*: NIG parameter beta (asymmetry) *mu*: NIG parameter mu (location) *delta*: NIG parameter delta (scale) ## Remarks Note that the NIG distribution is only defined when the kurtosis (not excess kurtosis) exceeds 3 + (5/3)·S², where S is the skewness. # apaNN.MLPClassifier.Estimate(X, Y, L2Penalty) URL: https://www.andreassteiner.net/help/apann.mlpclassifier.estimate/ ## Result Estimates a multiclass neural network classifier with one hidden layer (multilayer perceptron, MLP) and returns diagnostics, parameters and in-sample predictions. The function is non-volatile. ## Syntax *X*: n x p matrix of predictors *Y*: n x 1 vector of the dependent variable with integer classes 1..K *L2Penalty*: optional; L2 penalty on the weights, \>= 0. Default value: 0.01 ## Algorithm The predictors are standardized with their means and sample standard deviations (denominator n − 1). For the standardized predictor vector z(i) of observation i, the network has 12 tanh hidden units and a softmax output over the K classes: ``` math h_{i} = tanh\left( W_{1}^{\top}z_{i} + b_{1} \right),\quad\quad P(y_{i} = k) = \frac{\exp\left( w_{2,k}^{\top}h_{i} + b_{2,k} \right)}{\sum_{l = 1}^{K}\exp\left( w_{2,l}^{\top}h_{i} + b_{2,l} \right)} ``` The weights minimize the L2-penalized mean log-loss ``` math f = - \frac{1}{n}\sum_{i = 1}^{n}\log P(y_{i}) + \frac{\lambda}{2}\left( \left\| W_{1} \right\|^{2} + \left\| W_{2} \right\|^{2} \right) ``` where the penalty λ is L2Penalty and the biases b(1) and b(2) are not penalized. The objective is minimized with the limited-memory BFGS method (L-BFGS, memory 10) with exact gradients from backpropagation and a weak Wolfe line search. The starting weights are uniform random numbers with a fixed seed (123), scaled by 1/sqrt(p) and 1/sqrt(12), and the starting biases are 0, so the results are reproducible. The iteration stops when the largest absolute gradient component falls below 1E-6 (GradientTolerance), when the objective no longer decreases (FunctionTolerance), when the line search fails (LineSearchFailed) or after 10000 iterations (IterationLimit). ## Remarks The result starts with a diagnostics block. The first two columns contain the log-likelihood, the negative log-likelihood, AIC, BIC, the numbers of observations, predictors, classes and hidden units, the number of L-BFGS iterations and the termination reason. The next two columns contain the L2 penalty, the random seed, the number of parameters, the model type, the penalized objective f and the largest absolute gradient component at the solution. The diagnostics are followed by the blocks W1 (p x 12), b1, W2 (12 x K) and b2, where the weights W1 refer to the standardized predictors. The last block contains, for each observation, the actual class, the predicted class (highest probability) and the K class probabilities. The objective is not convex, so the solution is a local minimum that depends on the starting weights. AIC and BIC use the full number of weights and biases; since the weights of a neural network are not identified, they are only rough indications. If the number of observations is small relative to the number of parameters, the network can fit the training data almost perfectly, and the in-sample accuracy overstates the accuracy on new data. A larger L2Penalty reduces this overfitting; with L2Penalty = 0 the fit can become arbitrarily close to perfect, with very large weights. The function returns an error message if a predictor is constant or if X contains non-finite values. # apaNonNormality.Contributions(TimeSeries, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apanonnormality.contributions/ ## Result Calculates the incremental contributions of all observations of a time series to non-normality, i.e. to the Jarque-Bera test statistic. ## Syntax *TimeSeries*: n x 1 data vector *ConfidenceLevel*: confidence level of the Jarque-Bera test, e.g. 95% ## Remarks This function can be used to identify unusual observations or groups of observations. The methodology detects more than just tail events. Uses sample skewness and sample excess kurtosis (as Excel SKEW and KURT). # apaNonNormality.nObsToDropUntilNormal(TimeSeries, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apanonnormality.nobstodropuntilnormal/ ## Result Calculates the number of observations with large contributions to non-normality which need to be dropped until a time series passes the Jarque-Bera test for normality, divided by the total number of observations. The result expresses the degree of non-normality of a time series. ## Syntax *TimeSeries*: n x 1 data vector *ConfidenceLevel*: confidence level of the Jarque-Bera test, e.g. 95% ## Remarks This function can be used to quantify the “degree of non-normality” of a time series. Expressed as a percentage (nObsToDrop divided by the total nObs), it allows comparisons between time series with differing nObs. Uses sample skewness and sample excess kurtosis (as Excel SKEW and KURT). # apaNormalMixture.Estimate(DataMatrix, numComponents, nMultiStarts, Seed) URL: https://www.andreassteiner.net/help/apanormalmixture.estimate/ ## Result Estimates a multivariate Gaussian mixture model with the multi-start EM algorithm and returns the component parameters and the per-sample responsibilities. The function is non-volatile. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *numComponents*: number of mixture components *nMultiStarts*: optional; number of multi-starts. Default value: 1 (also used if omitted or below 1) *Seed*: optional; seed of the random number generator. Default value: 1 (also used if omitted or 0) ## Algorithm Inputs are validated: non-empty DataMatrix, 1 ≤ numComponents ≤ r. Each start draws the initial component centres by k-means++ seeding: the first centre is a randomly chosen observation, and each further centre is an observation drawn with probability proportional to its squared distance to the nearest centre already chosen. Each observation is assigned to its nearest centre, and the initial weights, means and covariances are those of the resulting clusters; clusters with fewer than c + 1 members start with the sample covariance. The EM algorithm then alternates the computation of the responsibilities with the responsibility-weighted update of weights, means and covariances until the change of the log-likelihood falls below 1E-7. A floor of 1E-6 times the average population variance (denominator n) of the series is added to the diagonal of each component covariance matrix, so the results do not depend on the scale of the data. A component is re-seeded, with its mean at a randomly drawn observation and the population covariance matrix (denominator n) of all observations, when its effective number of observations falls below max(1, 0.001·r) or when one of its variances falls below 1E-4 times the population variance (denominator n) of that series, i.e. when it collapses onto repeated values such as zero returns from stale prices. At most 10·numComponents re-seeds are made per start. Starts that end with such a degenerate component are only returned if no start avoids one; otherwise the start with the highest log-likelihood is returned. AIC and BIC count numComponents·c means, numComponents·c(c+1)/2 covariance parameters and numComponents − 1 weights. ## Remarks Covariances are maximum-likelihood (EM) estimates: probability-weighted, population-type, no small-sample correction. # apaNormalMixture.Moments(Weights, Means, CovariancesVech) URL: https://www.andreassteiner.net/help/apanormalmixture.moments/ ## Result Returns the means, volatilities, skewness, excess kurtosis and correlations of a normal mixture distribution with any number of components. ## Syntax *Weights*: nComponents x 1 vector of mixture weights *Means*: nComponents x nAssets matrix of component means *CovariancesVech*: nComponents x nAssets(nAssets+1)/2 matrix, each row containing the vech of a component covariance matrix (lower triangle including the diagonal, stacked column by column) ## Algorithm The weights are normalized to sum to one. With component weights w(k), means μ(k) and covariance matrices Σ(k), the mixture mean is μ = Σ w(k) μ(k) and the mixture covariance matrix is Σ w(k) (Σ(k) + d(k) d(k)′) with d(k) = μ(k) − μ. For each asset, the third and fourth central moments are Σ w(k) (3 d s + d³) and Σ w(k) (3 s² + 6 d² s + d⁴), where d is the asset's element of d(k) and s its variance in component k; skewness and excess kurtosis divide them by σ³ and σ⁴ (minus 3). The output has 4 + nAssets rows and nAssets columns: means, volatilities, skewness, excess kurtosis, followed by the correlation matrix. # apaNormalMixture.Responsibilities URL: https://www.andreassteiner.net/help/apanormalmixture.responsibilities/ ## Result Returns the component responsibilities (posterior mixture weights) of each observation under an estimated Gaussian mixture model. ## Syntax DataMatrix: $`r \times c`$data matrix used in estimation. ModelOutput: Gaussian mixture estimation result (e.g., from apaNormalMixture.Estimate). ## Algorithm The responsibilities (posterior probabilities of component membership) of each observation are computed from the fitted mixture model. Return a matrix with $`r`$rows (observations) and $`K`$columns (components), each row summing to 1. # apaNormalMixture.StateTrajectory URL: https://www.andreassteiner.net/help/apanormalmixture.statetrajectory/ ## Result Returns the most probable mixture component index for each observation. ## Syntax ResponsibilitiesMatrix: $`r \times K`$matrix of component responsibilities. ## Algorithm For each row of ResponsibilitiesMatrix, the column index of the maximum value is determined. The result is a column vector of component indices (1..K), representing the state trajectory. # apaNormalToLognormal.Mean(NormalMean, NormalVolatility) URL: https://www.andreassteiner.net/help/apanormaltolognormal.mean/ ## Result Converts the mean and volatility of a normal variable into the mean of the corresponding lognormal variable. ## Syntax *NormalMean*: mean of the normal variable *NormalVolatility*: volatility of the normal variable ## Algorithm See our research note “Discrete and Continuous Correlation” for details. # apaNormalToLognormal.Volatility(NormalMean, NormalVolatility) URL: https://www.andreassteiner.net/help/apanormaltolognormal.volatility/ ## Result Converts the mean and volatility of a normal variable into the volatility of the corresponding lognormal variable. ## Syntax *NormalMean*: mean of the normal variable *NormalVolatility*: volatility of the normal variable ## Algorithm See our research note “Discrete and Continuous Correlation” for details. # apaNormalToLognormal.Covariance(NormalMean1, NormalMean2, NormalVolatility1, NormalVolatility2, NormalCovariance) URL: https://www.andreassteiner.net/help/apanormaltolognormal.covariance/ ## Result Converts the covariance of two normal variables into the covariance of the corresponding lognormal variables. ## Syntax *NormalMean1*: mean of the first normal variable *NormalMean2*: mean of the second normal variable *NormalVolatility1*: volatility of the first normal variable *NormalVolatility2*: volatility of the second normal variable *NormalCovariance*: covariance of the normal variables ## Algorithm See our research note “Discrete and Continuous Correlation” for details. # apaNormalToLognormal.Correlation(NormalVolatility1, NormalVolatility2, NormalCorrelation) URL: https://www.andreassteiner.net/help/apanormaltolognormal.correlation/ ## Result Converts the correlation of two normal variables into the correlation of the corresponding lognormal variables. ## Syntax *NormalVolatility1*: volatility of the first normal variable *NormalVolatility2*: volatility of the second normal variable *NormalCorrelation*: correlation of the normal variables ## Algorithm See our research note “Discrete and Continuous Correlation” for details. # apaNormalQQ.Correl(Returns) URL: https://www.andreassteiner.net/help/apanormalqq.correl/ ## Result Calculates the normal probability plot correlation coefficient, a test for normality, i.e. the correlation between the empirical cumulative distribution and the cumulative probabilities of a normal distribution with the same mean and standard deviation. ## Syntax *Returns*: r x 1 vector of returns ## Remarks The lower the correlation coefficient, the lower the probability that the data is normally distributed. Standardizes with the sample standard deviation (denominator n − 1). # apaNormalQQ.Plot(Returns) URL: https://www.andreassteiner.net/help/apanormalqq.plot/ ## Result Calculates the data for a normal QQ plot, i.e. the sorted observations and the corresponding quantiles of a normal distribution with the same mean and standard deviation. ## Syntax *Returns*: r x 1 vector of returns ## Remarks Standardizes with the sample standard deviation (denominator n − 1). # apaNcdf(Nvals, Mean, StdDev) URL: https://www.andreassteiner.net/help/apancdf/ ## Result Cumulative distribution function of the normal distribution, evaluated elementwise for a matrix of values. ## Syntax *Nvals*: r x c matrix of values at which to evaluate the function *Mean*: the mean of the normal distribution *StdDev*: the standard deviation of the normal distribution ## Remarks The result has the same dimensions as Nvals. # apaNpdf.Multivariate(X, Means, Covars) URL: https://www.andreassteiner.net/help/apanpdf.multivariate/ ## Result Probability density function of a multivariate normal distribution. ## Syntax *X*: 1 x n vector of X values *Means*: 1 x n vector of means (first moments) *Covars*: n x n covariance matrix (second moments) ## Algorithm f(x) = exp(−½·(x − μ)ᵀ Σ⁻¹ (x − μ)) / √((2π)^n · det Σ) ## Remarks *X* and *Means* can be row or column vectors. *Covars* must be positive definite. # apaOmega(PortfolioReturns, Threshold) URL: https://www.andreassteiner.net/help/apaomega/ ## Result Calculates the Omega ratio, a risk-adjusted performance measure, i.e. 1 + the average return in excess of the threshold divided by the first lower partial moment. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *Threshold*: return threshold ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image93.svg) ## Remarks Partial moments divide by the total number of observations n (population-type). # apaOLS.Fitted(X, Y) URL: https://www.andreassteiner.net/help/apaols.fitted/ ## Result Returns the fitted Y values of an OLS regression. If there is more than one Y variable, returns the results for all Y_i with the same X. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x 1 matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. ## Remarks The calculations do not assume an intercept. To model a constant, add a column of ones to the X matrix. # apaOLS.Betas(X, Y) URL: https://www.andreassteiner.net/help/apaols.betas/ ## Result Returns the ordinary least squares (OLS) regression coefficients (betas). If there is more than one Y variable, returns the results for all Y_i with the same X. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x nCols matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image94.svg) ## Remarks The calculations do not assume an intercept. To model a constant, add a column of ones to the X matrix. # apaOLS.Betas.ConfidenceIntervals(X, Y, ConfidenceLevel, nSamples) URL: https://www.andreassteiner.net/help/apaols.betas.confidenceintervals/ ## Result Returns confidence intervals for the OLS regression coefficients (betas) based on resampling. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x 1 matrix of the Y variable *ConfidenceLevel*: confidence level, e.g. 95%. *nSamples*: number of samples to generate (1000 is a good starting point) ## Remarks - Resampling does not make any distributional assumptions, but is based strictly on the input data. - Resampling does not take into account any form of serial dependency in the input data. # apaOLS.ForwardStagewise(X, Y, StepSize, nSteps) URL: https://www.andreassteiner.net/help/apaols.forwardstagewise/ ## Result Performs an incremental forward stagewise linear regression for nSteps steps and returns the coefficient path: a matrix of nSteps rows and 2 + columns(X) columns. Column 1 holds the R2, column 2 the intercept and the remaining columns the betas of the X variables in their original units, each row after the corresponding step. ## Syntax *X*: rows x columns matrix of regressors, one variable per column *Y*: rows x 1 vector of the dependent variable *StepSize*: positive increment of the standardized coefficient added in each step, typically a small number such as 0.01 *nSteps*: number of steps to calculate, at least 1 ## Remarks The X columns are standardized internally to mean 0 and population standard deviation 1, and Y is centered. In each step the standardized variable with the largest absolute covariance with the current residual (equivalently the largest absolute correlation) is selected; ties go to the lowest column index. Its standardized coefficient is moved by StepSize in the direction of that covariance and the residual is updated. The betas are converted back to the original units, so the result does not depend on the scaling of X, and the intercept equals the mean of Y minus the means of X times the betas. The R2 is the in-sample coefficient of determination of the fitted values including the intercept, 1 - SSR/SST, with SST the sum of squared deviations of Y from its mean. The algorithm does not stop at convergence; it executes the number of steps given. For a small StepSize the betas approach the OLS betas with an intercept; once there, one coefficient oscillates by StepSize. If the residual is explained exactly, the remaining rows show \#N/A. Constant X columns are never selected and keep a beta of 0. X and Y must have the same number of rows and must not contain missing values. # apaOLS.kFold(X, Y, k, IsAveragedOtherwiseShowFolds, FoldingType) URL: https://www.andreassteiner.net/help/apaols.kfold/ ## Result Performs a k-fold OLS estimation. ## Syntax *X*: rows x columns matrix of data. Each column containing a variable. *Y*: rows x 1 vector of data *k*: number of folds to perform on the data. When averaged results are chosen, k can be a rows x 1 vector of k values. *IsAveragedOtherwiseShowFolds*: show results averaged over all folds, otherwise results per fold *FoldingType*: optional; folding type: 1 = standard k-fold, 2 = time series rolling k-fold, 3 = time series cumulative k-fold; default: 1 # apaOLS.Betas.Evaluation(X, Y, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaols.betas.evaluation/ ## Result Returns the standard errors, t-values, two-sided critical t-values and two-sided p-values of the OLS regression coefficients. A coefficient is significant if its p-value \< 1 - ConfidenceLevel. If there is more than one Y variable, returns the results for all Y_i with the same X. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x nCols matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. *ConfidenceLevel*: confidence level between 0 and 1 for the two-sided test, e.g. 0.95. ## Algorithm The significance test is based on the t-statistic of each regression coefficient… ![Formula](https://www.andreassteiner.net/help/assets/eq/image95.svg) …with ![Formula](https://www.andreassteiner.net/help/assets/eq/image96.svg)being the standard error of each regression coefficient. The critical value is calculated from the t distribution. The p-value is the smallest significance level at which the coefficient is considered statistically different from zero. ## Remarks The null hypothesis is bi = 0. A coefficient is statistically different from zero if \|t-value\| \> critical t-value, or equivalently if p-value \< 1 - ConfidenceLevel. Residual variance is SSE/(n − k), i.e. degrees-of-freedom corrected. # apaOLS.Betas.CriticalValue(X, Y, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaols.betas.criticalvalue/ ## Result Returns the two-sided critical t-values of the OLS regression coefficients. A coefficient is significant if \|t-value\| \> critical t-value. If there is more than one Y variable, returns the results for all Y_i with the same X. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x 1 matrix of the Y variables *ConfidenceLevel*: confidence level between 0 and 1 for the two-sided test, e.g. 0.95. ## Remarks t quantile with n − k degrees of freedom. # apaOLS.Betas.tValue(X, Y) URL: https://www.andreassteiner.net/help/apaols.betas.tvalue/ ## Result Returns the t-values of the OLS regression coefficients. If there is more than one Y variable, returns the results for all Y_i with the same X. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x nCols matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. ## Remarks Residual variance is SSE/(n − k), i.e. degrees-of-freedom corrected. # apaOLS.Betas.pValue(X, Y) URL: https://www.andreassteiner.net/help/apaols.betas.pvalue/ ## Result Returns the two-sided p-values of the OLS regression coefficients (null hypothesis: coefficient = 0). If there is more than one Y variable, returns the results for all Y_i with the same X. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x nCols matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. ## Remarks Residual variance is SSE/(n − k), i.e. degrees-of-freedom corrected. # apaOLS.Betas.StandardError(X, Y, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaols.betas.standarderror/ ## Result Returns the standard errors of the OLS regression coefficients. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x nCols matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. *ConfidenceLevel*: confidence level between 0 and 1 ## Remarks Residual variance is SSE/(n − k), i.e. degrees-of-freedom corrected. # apaOLS.Ftest(X, Y, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apaols.ftest/ ## Result Performs an F-test of the regression model. Returns the F-value (test statistic), the critical value and the p-value. If there is more than one Y variable, returns the results for all Y_i with the same X. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x nCols matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. *ConfidenceLevel*: confidence level, e.g. 0.95. # apaOLS.R2(X, Y) URL: https://www.andreassteiner.net/help/apaols.r2/ ## Result Returns the R-squared of an OLS regression. If there is more than one Y variable, returns the results for all Y_i with the same X. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x nCols matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image97.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image98.svg) are the fitted values. ## Remarks There exist different approaches to calculating R-squared. The method chosen here makes R-squared independent of any constant values. # apaOLS.R2.ConfidenceIntervals(X, Y, ConfidenceLevel, nSamples) URL: https://www.andreassteiner.net/help/apaols.r2.confidenceintervals/ ## Result Returns resampled confidence intervals for the R-squared of an OLS regression. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x 1 matrix of the Y variable *ConfidenceLevel*: confidence level, e.g. 95%. *nSamples*: number of samples to generate (1000 is a good starting point) ## Remarks There exist different approaches to calculating R-squared. The method chosen here makes R-squared independent of any constant values. # apaOLS.R2.Adjusted(X, Y) URL: https://www.andreassteiner.net/help/apaols.r2.adjusted/ ## Result Returns the R-squared of an OLS regression, adjusted for the number of variables. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: r x 1 data matrix ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image99.svg) n is the number of observations, k the number of variables (including constants). ## Remarks Adjusted with the factor (n − 1)/(n − k). # apaOLS.Ridge.Betas(X, Y, Lambda) URL: https://www.andreassteiner.net/help/apaols.ridge.betas/ ## Result Estimates the betas of a linear ridge regression. ## Syntax *X*: rows x columns matrix of data. Each column containing a variable. *Y*: rows x 1 vector of data *Lambda*: ridge regression lambda, i.e. the shrinkage parameter. # apaOLS.Ridge.kFold(X, Y, Lambda, k, IsAveragedOtherwiseShowFolds, FoldingType) URL: https://www.andreassteiner.net/help/apaols.ridge.kfold/ ## Result Performs a k-fold linear ridge regression estimation. ## Syntax *X*: rows x columns matrix of data. Each column containing a variable. *Y*: rows x 1 vector of data *Lambda*: ridge regression lambda, i.e. the shrinkage parameter. When averaged results are chosen, lambda can be a rows x 1 vector of lambda values. *k*: number of folds to perform on the data *IsAveragedOtherwiseShowFolds*: show results averaged over all folds, otherwise results per fold *FoldingType*: optional; folding type: 1 = standard k-fold, 2 = time series rolling k-fold, 3 = time series cumulative k-fold; default: 1 # apaOLS.Residuals(X, Y) URL: https://www.andreassteiner.net/help/apaols.residuals/ ## Result Returns the residuals of an OLS regression. If there is more than one Y variable, returns the results for all Y_i with the same X. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x nCols matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. ## Remarks The calculations do not assume an intercept. To model a constant, add a column of ones to the X matrix. # apaOLS.SSE(X, Y) URL: https://www.andreassteiner.net/help/apaols.sse/ ## Result Calculates the sum of squares error (SSE), i.e. the sum of squared deviations of the fitted Y values from the observed Y values. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x nCols matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. # apaOLS.SSR(X, Y) URL: https://www.andreassteiner.net/help/apaols.ssr/ ## Result Calculates the sum of squares regression (SSR), i.e. the sum of squared deviations of the fitted Y values from the mean of Y. ## Syntax *X*: nRows x nCols matrix of X variables. Each column contains one variable. *Y*: nRows x nCols matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. # apaOLS.SST(Y) URL: https://www.andreassteiner.net/help/apaols.sst/ ## Result Calculates the sum of squares total (SST), i.e. the sum of squared deviations of the Y values from the mean of Y. ## Syntax *Y*: nRows x nCols matrix of the Y variables. If there is more than one Y variable, gives results for all Y_i with the same X. # apaOneHotEncoding(DataVector) URL: https://www.andreassteiner.net/help/apaonehotencoding/ ## Result Performs one-hot encoding on a categorical data vector. ## Syntax *DataVector*: nObs x 1 column vector of category indices ## Algorithm DataVector is treated as a vector of integer category indices. # apaOLS.Stepwise(X, Y) URL: https://www.andreassteiner.net/help/apaols.stepwise/ ## Result Performs a forward stepwise linear regression with an intercept and returns the full selection path: a matrix with columns(X) rows and 2 x columns(X) + 4 columns, one row per step. Column 1 holds the adjusted R2, column 2 the R2, column 3 a flag that is 1 for the row with the highest adjusted R2 and 0 otherwise, the next columns(X) columns the numbers of the variables in their order of entry, followed by the intercept and the betas of all X variables in their original column order. ## Syntax *X*: rows x columns matrix of regressors, one variable per column; do not include a column of ones, the intercept is added internally *Y*: rows x 1 vector of the dependent variable ## Remarks Each step adds the variable that yields the highest adjusted R2, which within a step is the same as the highest R2 or the lowest sum of squared residuals; ties go to the lowest column index. Variables are never removed, and the function does not stop on its own: all steps are reported, and the flag in column 3 marks the step with the highest adjusted R2 as the suggested model. R2 = 1 - SSR/SST, with SST the sum of squared deviations of Y from its mean. The adjusted R2 is 1 - (1 - R2)(n - 1)/(n - p - 1), with n the number of observations and p the number of selected variables (excluding the intercept). Cells without a result show \#N/A: variable numbers not yet entered, betas of variables not yet selected, and all cells of steps that cannot be computed. A candidate is skipped if it is constant or (nearly) collinear with the intercept and the variables already selected, i.e. if 1 - R2 of its regression on them is below 1E-10 (variance inflation factor above 1E10); selection also ends when n \<= p + 1. If Y is constant, or X and Y differ in their number of rows, an error message is returned. # apaPercentile(Data, Ptile) URL: https://www.andreassteiner.net/help/apapercentile/ ## Result Percentile function (as the Excel function PERCENTILE), i.e. returns the data point which constitutes a certain percentile. Interpolates between observations. ## Syntax *Data*: n x 1 vector of observations *Ptile*: percentile value between 0 and 1 ## Remarks Values in between actual observations are interpolated. # apaPercentile.Inverse(Data, X) URL: https://www.andreassteiner.net/help/apapercentile.inverse/ ## Result Inverse percentile function (inverse of the Excel function PERCENTILE), i.e. returns the percentile (cumulative probability) of a data point X in the dataset. Interpolates between observations. ## Syntax *Data*: n x 1 vector of observations *X*: one data point ## Remarks X values which are not actual observations are interpolated. # apaPainIndex(Returns) URL: https://www.andreassteiner.net/help/apapainindex/ ## Result Returns the pain index, the mean depth of the drawdowns over all periods. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. ## Algorithm Pain index = mean over all periods of \|D(t)\|, where D(t) = W(t) / max(1, max\_{s≤t} W(s)) − 1 is the underwater curve of the wealth W(t) compounded from the discrete returns, starting from 1 (Zephyr). ## Remarks The result is a 1 x c row vector with one value per column of Returns. Unlike the ulcer index, drawdowns are not squared. # apaPainRatio(Returns, RiskfreeReturns, PeriodsPerYear) URL: https://www.andreassteiner.net/help/apapainratio/ ## Result Returns the pain ratio, the mean excess return divided by the pain index. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 *PeriodsPerYear*: optional; number of return periods per year used to annualize the mean excess return, e.g. 12 for monthly data; default: 1 (per-period result) ## Algorithm Pain ratio = PeriodsPerYear · mean(r − rf) / pain index, see apaPainIndex. ## Remarks The result is a 1 x c row vector with one value per column of Returns. \#N/A is returned if the series has no drawdown. # apaPartialAutoCorrel(Returns, Lag, DoNotShowConfidenceBandsOtherwiseShow) URL: https://www.andreassteiner.net/help/apapartialautocorrel/ ## Result Returns the partial autocorrelation coefficients up to a certain lag, optionally with approximate 95% confidence bands ±2/√n, where n is the number of observations. ## Syntax *Returns*: n x 1 time series vector *Lag*: maximum lag to shift the data *DoNotShowConfidenceBandsOtherwiseShow*: optional; TRUE (default) to return the coefficients only, FALSE to add the lower and upper confidence bands in the last two columns. ## Remarks More than one time series can be processed. # apaPatternRecognition.ChangePoints.FromProfile(profileIndex, windowSize, topK, minSpacing) URL: https://www.andreassteiner.net/help/apapatternrecognition.changepoints.fromprofile/ ## Result Returns the top regime change candidates derived from a matrix profile index vector. ## Syntax *profileIndex*: k x 1 or 1 x k vector of 1-based matrix profile indices *windowSize*: length of the subsequences (window size) *topK*: number of change points to return. Default value: 3 *minSpacing*: minimum spacing between change points. Default value: −1, i.e. windowSize ## Algorithm The segmentation profile is calculated (see apaPatternRecognition.SegmentationProfile.FromProfile). ## Remarks The result contains a header row and one row per change point with the columns Rank, Position (1-based) and Score. # apaPatternRecognition.ChangePoints.FromSeries(series, windowSize, topK, minSpacing) URL: https://www.andreassteiner.net/help/apapatternrecognition.changepoints.fromseries/ ## Result Calculates the matrix profile for a univariate time series and returns the top regime change candidates. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *windowSize*: length of the subsequences (window size) *topK*: number of change points to return. Default value: 3 *minSpacing*: minimum spacing between change points. Default value: −1, i.e. windowSize ## Algorithm The matrix profile index and the segmentation profile are calculated (see apaPatternRecognition.SegmentationProfile.FromSeries). ## Remarks The result contains a header row and one row per change point with the columns Rank, Position (1-based) and Score. # apaPatternRecognition.ExpandProfile.ToSeries(profile, windowSize) URL: https://www.andreassteiner.net/help/apapatternrecognition.expandprofile.toseries/ ## Result Expands a matrix profile vector to the length of the original time series, using the minimum over all overlapping windows. ## Syntax *profile*: k x 1 or 1 x k matrix profile vector *windowSize*: length of the subsequences (window size) ## Algorithm Each matrix profile value is assigned to all windowSize observations of its subsequence. For each observation, the minimum of the assigned values is returned. ## Remarks The result has k + windowSize − 1 elements, i.e. the length of the original time series. # apaPatternRecognition.GetWindowsData(data, windowSize) URL: https://www.andreassteiner.net/help/apapatternrecognition.getwindowsdata/ ## Result Returns all overlapping subsequences (sliding windows) of a time series. ## Syntax *data*: r x 1 or 1 x r data vector containing a time series *windowSize*: length of the subsequences (window size) ## Remarks The result is a windowSize x (r − windowSize + 1) matrix, each column containing one subsequence. # apaPatternRecognition.MatrixProfile(series, windowSize) URL: https://www.andreassteiner.net/help/apapatternrecognition.matrixprofile/ ## Result Returns the matrix profile and the 1-based matrix profile index for a univariate time series. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *windowSize*: length of the subsequences (window size) ## Algorithm The series is split into all k = r − windowSize + 1 overlapping subsequences of length windowSize. ## Remarks The result is a k x 2 matrix with the matrix profile in the first and the matrix profile index in the second column. # apaPatternRecognition.MatrixProfile.AdjacencyMatrix(series, windowSize, exclusionZone) URL: https://www.andreassteiner.net/help/apapatternrecognition.matrixprofile.adjacencymatrix/ ## Result Returns the self-join distance matrix between all subsequences of a time series, e.g. as input for graph functions. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *windowSize*: length of the subsequences (window size) *exclusionZone*: exclusion zone in window units, 0 for none. Default value: −1, i.e. ceiling(windowSize/4) ## Algorithm The series is split into all overlapping subsequences of length windowSize. ## Remarks The result is a k x k matrix with k = r − windowSize + 1 and zeros on the main diagonal. # apaPatternRecognition.MotifExtraction.TopMotifPairs.FromProfile(profile, profileIndex, windowSize, topK) URL: https://www.andreassteiner.net/help/apapatternrecognition.motifextraction.topmotifpairs.fromprofile/ ## Result Returns the top non-overlapping motif pairs, i.e. the most similar pairs of subsequences, from matrix profile and matrix profile index vectors. ## Syntax *profile*: k x 1 or 1 x k matrix profile vector *profileIndex*: k x 1 or 1 x k vector of 1-based matrix profile indices *windowSize*: length of the subsequences (window size) *topK*: number of motif pairs to return. Default value: 10 ## Algorithm The subsequences are sorted by ascending matrix profile value, i.e. distance to their nearest neighbor. ## Remarks The result contains a header row and one row per motif pair with the columns Rank, Start1, Start2 (both 1-based) and Distance. # apaPatternRecognition.MotifGroups.FromProfile(profile, profileIndex, windowSize, topKPairs) URL: https://www.andreassteiner.net/help/apapatternrecognition.motifgroups.fromprofile/ ## Result Returns motif groups extracted from matrix profile and matrix profile index vectors using index-link grouping. ## Syntax *profile*: k x 1 or 1 x k matrix profile vector *profileIndex*: k x 1 or 1 x k vector of 1-based matrix profile indices *windowSize*: length of the subsequences (window size) *topKPairs*: number of seed motif pairs to use. Default value: 5 ## Algorithm The top non-overlapping motif pairs are extracted (see apaPatternRecognition.MotifExtraction.TopMotifPairs.FromProfile) and used as seeds. ## Remarks The result contains a header row and one row per group with the columns GroupId, SeedStart1, SeedStart2, SeedDistance, Count and the 1-based start indices Member1, Member2, … . # apaPatternRecognition.MotifGroups.FromSeries(series, windowSize, topKPairs, radiusMultiplier) URL: https://www.andreassteiner.net/help/apapatternrecognition.motifgroups.fromseries/ ## Result Returns motif groups extracted from a univariate time series using distance-based grouping. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *windowSize*: length of the subsequences (window size) *topKPairs*: number of seed motif pairs to use. Default value: 5 *radiusMultiplier*: multiplier applied to the seed motif distance to obtain the group radius. Default value: 1.5 ## Algorithm The matrix profile is calculated and the top non-overlapping motif pairs are extracted as seeds. ## Remarks The result contains a header row and one row per group with the columns GroupId, SeedStart1, SeedStart2, SeedDistance, Count and the 1-based start indices Member1, Member2, … . # apaPatternRecognition.RegimeSegments.FromChangePoints(changePoints, seriesLength, minRegimeLength) URL: https://www.andreassteiner.net/help/apapatternrecognition.regimesegments.fromchangepoints/ ## Result Builds contiguous regime segments from change point positions and scores. ## Syntax *changePoints*: change point matrix as returned by apaPatternRecognition.ChangePoints.FromProfile or apaPatternRecognition.ChangePoints.FromSeries *seriesLength*: total length of the series or total number of windows to segment *minRegimeLength*: minimum regime length, shorter regimes are merged with a neighbor. Default value: 1 ## Algorithm The change points are sorted by position. Each change point starts a new regime. ## Remarks The result contains a header row and one row per regime with the columns RegimeId, Start, End, Length, LeftBoundaryScore and RightBoundaryScore. # apaPatternRecognition.RegimeSegments.FromSeries(series, windowSize, topKChangePoints, minSpacing, minRegimeLength) URL: https://www.andreassteiner.net/help/apapatternrecognition.regimesegments.fromseries/ ## Result Calculates change points from a time series and returns contiguous regime segments. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *windowSize*: length of the subsequences (window size) *topKChangePoints*: number of top change points to extract. Default value: 3 *minSpacing*: minimum spacing between change points. Default value: −1, i.e. windowSize *minRegimeLength*: minimum regime length, shorter regimes are merged with a neighbor. Default value: 1 ## Algorithm The change points are calculated (see apaPatternRecognition.ChangePoints.FromSeries). ## Remarks The result has the same columns as apaPatternRecognition.RegimeSegments.FromChangePoints. # apaPatternRecognition.RegimeTrajectory.FromSeries(series, windowSize, topKChangePoints, minSpacing, minRegimeLength) URL: https://www.andreassteiner.net/help/apapatternrecognition.regimetrajectory.fromseries/ ## Result Calculates change points from a time series and returns the regime trajectory, i.e. the 1-based regime index for each observation. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *windowSize*: length of the subsequences (window size) *topKChangePoints*: number of top change points to extract. Default value: 3 *minSpacing*: minimum spacing between change points. Default value: −1, i.e. windowSize *minRegimeLength*: minimum regime length, shorter regimes are merged with a neighbor. Default value: 1 ## Algorithm The regime segments are calculated (see apaPatternRecognition.RegimeSegments.FromSeries) and each observation is assigned the index of its regime. ## Remarks The result has the same length as the time series. # apaPatternRecognition.SegmentationProfile.FromProfile(profileIndex, windowSize) URL: https://www.andreassteiner.net/help/apapatternrecognition.segmentationprofile.fromprofile/ ## Result Returns the segmentation profile derived from a matrix profile index vector, i.e. a score for each position indicating the likelihood of a regime change. ## Syntax *profileIndex*: k x 1 or 1 x k vector of 1-based matrix profile indices *windowSize*: length of the subsequences (window size) ## Algorithm Each subsequence is connected with its nearest neighbor by an arc. For each position, the number of arcs passing over it is counted. ## Remarks Low segmentation scores indicate regime changes, since few subsequences have their nearest neighbor on the other side of the position. # apaPatternRecognition.SegmentationProfile.FromSeries(series, windowSize) URL: https://www.andreassteiner.net/help/apapatternrecognition.segmentationprofile.fromseries/ ## Result Calculates the matrix profile for a univariate time series and returns the segmentation profile, i.e. a score for each position indicating the likelihood of a regime change. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *windowSize*: length of the subsequences (window size) ## Algorithm The matrix profile index is calculated (see apaPatternRecognition.MatrixProfile). ## Remarks The result contains a header row and one row per position with the columns Position (1-based), ArcCount and SegmentationScore. # apaPatternRecognition.SelectTopNonRedundantShapelets(scoredShapelets, trainingSeriesMatrix, labels, shapeletSourceSeries, shapeletStarts, windowSize, topK, maxDistanceCorrelation, sourceName) URL: https://www.andreassteiner.net/help/apapatternrecognition.selecttopnonredundantshapelets/ ## Result Selects the top non-redundant shapelets from a scored shapelet table, filtering shapelets with highly correlated distance profiles across the training series. ## Syntax *scoredShapelets*: scored shapelet matrix as returned by apaPatternRecognition.ShapeletScoresBinary or apaPatternRecognition.ShapeletScoresBinary.Auto *trainingSeriesMatrix*: r x n matrix of training series, one series per column *labels*: 1 x n or n x 1 vector of binary labels (0 or 1), one per training series *shapeletSourceSeries*: data vector containing the source time series used to rebuild the candidate shapelets *shapeletStarts*: vector of 1-based start indices of the candidate shapelets *windowSize*: length of the subsequences (window size) *topK*: maximum number of shapelets to select. Default value: 10 *maxDistanceCorrelation*: maximum absolute correlation between the distance profiles of two selected shapelets, between 0 and 1. Default value: 0.95 *sourceName*: label stored with each rebuilt shapelet. Default value: “Manual” ## Algorithm For each shapelet, the distance profile is calculated, i.e. the vector of best-match distances across all training series. ## Remarks The result has the same columns as apaPatternRecognition.ShapeletScoresBinary, with the column Selected indicating the selected shapelets. # apaPatternRecognition.ShapeletFeatures.FromDiscords(shapeletSourceSeries, targetSeries, discordStarts, windowSize) URL: https://www.andreassteiner.net/help/apapatternrecognition.shapeletfeatures.fromdiscords/ ## Result Builds shapelets from discord start indices and returns distance-based shapelet features for a target time series. ## Syntax *shapeletSourceSeries*: r x 1 or 1 x r data vector containing the source time series from which the discord shapelets are extracted *targetSeries*: r x 1 or 1 x r data vector containing the target time series to transform into shapelet features *discordStarts*: n x 1 or 1 x n vector of 1-based discord start indices *windowSize*: length of the subsequences (window size) ## Algorithm For each start index, the subsequence of length windowSize of the source series is used as a shapelet. ## Remarks The result contains a header row and one row per shapelet with the columns ShapeletId, Source, Length, BestDistance and BestMatchStart (1-based). # apaPatternRecognition.ShapeletFeatures.FromMotifs(shapeletSourceSeries, targetSeries, motifStarts, windowSize) URL: https://www.andreassteiner.net/help/apapatternrecognition.shapeletfeatures.frommotifs/ ## Result Builds shapelets from motif start indices and returns distance-based shapelet features for a target time series. ## Syntax *shapeletSourceSeries*: r x 1 or 1 x r data vector containing the source time series from which the motif shapelets are extracted *targetSeries*: r x 1 or 1 x r data vector containing the target time series to transform into shapelet features *motifStarts*: n x 1 or 1 x n vector of 1-based motif start indices *windowSize*: length of the subsequences (window size) ## Algorithm For each start index, the subsequence of length windowSize of the source series is used as a shapelet. ## Remarks The result contains a header row and one row per shapelet with the columns ShapeletId, Source, Length, BestDistance and BestMatchStart (1-based). # apaPatternRecognition.ShapeletFeatures.FromSeries.Auto(shapeletSourceSeries, targetSeries, windowSize, topKMotifs, topKDiscords) URL: https://www.andreassteiner.net/help/apapatternrecognition.shapeletfeatures.fromseries.auto/ ## Result Determines motif and discord shapelets from a source time series and returns distance-based shapelet features for a target time series. ## Syntax *shapeletSourceSeries*: r x 1 or 1 x r data vector containing the source time series used to discover the motif and discord shapelets *targetSeries*: r x 1 or 1 x r data vector containing the target time series to transform into shapelet features *windowSize*: length of the subsequences (window size) *topKMotifs*: number of motif-derived shapelets to include, 0 for none. Default value: 3 *topKDiscords*: number of discord-derived shapelets to include, 0 for none. Default value: 3 ## Algorithm The matrix profile of the source series is calculated (see apaPatternRecognition.MatrixProfile). ## Remarks The result contains a header row and one row per shapelet with the columns ShapeletId, Source, Length, BestDistance and BestMatchStart (1-based). # apaPatternRecognition.ShapeletScoresBinary(trainingSeriesMatrix, labels, shapeletSourceSeries, shapeletStarts, windowSize, sourceName) URL: https://www.andreassteiner.net/help/apapatternrecognition.shapeletscoresbinary/ ## Result Scores candidate shapelets for binary classification, based on the separation of the best-match distances between training series with label 0 and label 1. ## Syntax *trainingSeriesMatrix*: r x n matrix of training series, one series per column *labels*: 1 x n or n x 1 vector of binary labels (0 or 1), one per training series *shapeletSourceSeries*: data vector containing the source time series used to build the candidate shapelets *shapeletStarts*: vector of 1-based start indices of the candidate shapelets *windowSize*: length of the subsequences (window size) *sourceName*: label stored with each shapelet. Default value: “Manual” ## Algorithm For each candidate shapelet and training series, the best-match distance is calculated, i.e. the smallest z-normalized Euclidean distance to any subsequence of the training series. ## Remarks The result contains a header row and one row per shapelet with the columns Rank, ShapeletId, Source, StartIndex, Length, Score, MeanDistanceLabel0, MeanDistanceLabel1, StdDistanceLabel0, StdDistanceLabel1 and Selected. StartIndex is the 1-based start index of the shapelet in shapeletSourceSeries, so the table can be passed on unchanged to apaPatternRecognition.SelectTopNonRedundantShapelets. # apaPatternRecognition.ShapeletScoresBinary.Auto(trainingSeriesMatrix, labels, shapeletSourceSeries, windowSize, topKMotifs, topKDiscords) URL: https://www.andreassteiner.net/help/apapatternrecognition.shapeletscoresbinary.auto/ ## Result Determines motif- and discord-derived candidate shapelets from a source time series and scores them for binary classification. ## Syntax *trainingSeriesMatrix*: r x n matrix of training series, one series per column *labels*: 1 x n or n x 1 vector of binary labels (0 or 1), one per training series *shapeletSourceSeries*: data vector containing the source time series used to discover the candidate shapelets *windowSize*: length of the subsequences (window size) *topKMotifs*: number of motif-derived shapelets to include, 0 for none. Default value: 3 *topKDiscords*: number of discord-derived shapelets to include, 0 for none. Default value: 3 ## Algorithm The matrix profile of the source series is calculated and the top motif pairs and discords are turned into candidate shapelets. ## Remarks The result has the same columns as apaPatternRecognition.ShapeletScoresBinary. # apaPatternRecognition.TopDiscords.FromProfile(profile, profileIndex, windowSize, topK) URL: https://www.andreassteiner.net/help/apapatternrecognition.topdiscords.fromprofile/ ## Result Returns the top non-overlapping discords, i.e. the most unusual subsequences, from matrix profile and matrix profile index vectors. ## Syntax *profile*: k x 1 or 1 x k matrix profile vector *profileIndex*: k x 1 or 1 x k vector of 1-based matrix profile indices *windowSize*: length of the subsequences (window size) *topK*: number of discords to return. Default value: 10 ## Algorithm The subsequences are sorted by descending matrix profile value, i.e. distance to their nearest neighbor. ## Remarks The result contains a header row and one row per discord with the columns Rank, Start, NearestNeighborStart (both 1-based) and Distance. # apaPatternRecognition.TopDiscords.FromSeries(series, windowSize, topK) URL: https://www.andreassteiner.net/help/apapatternrecognition.topdiscords.fromseries/ ## Result Calculates the matrix profile for a univariate time series and returns the top non-overlapping discords, i.e. the most unusual subsequences. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *windowSize*: length of the subsequences (window size) *topK*: number of discords to return. Default value: 10 ## Algorithm The matrix profile is calculated (see apaPatternRecognition.MatrixProfile). ## Remarks The result contains a header row and one row per discord with the columns Rank, Start, NearestNeighborStart (both 1-based) and Distance. # apaPatternRecognition.WindowPatternFeatures(windowCount, motifGroups, discordStarts, changePoints) URL: https://www.andreassteiner.net/help/apapatternrecognition.windowpatternfeatures/ ## Result Builds features for each subsequence window from motif groups, discords and optionally change points, e.g. as input for classification or regression models. ## Syntax *windowCount*: number of subsequence windows, typically r − windowSize + 1 *motifGroups*: motif group matrix as returned by apaPatternRecognition.MotifGroups.FromProfile or apaPatternRecognition.MotifGroups.FromSeries *discordStarts*: n x 1 or 1 x n vector of 1-based discord start indices *changePoints*: change point matrix as returned by apaPatternRecognition.ChangePoints.FromProfile or apaPatternRecognition.ChangePoints.FromSeries, or a vector of 1-based positions only. Empty to ignore ## Remarks The result contains a header row and one row per window with the columns Start, MotifGroupId, MotifMemberCount, MotifSeedDistance, DistanceToNearestMotifSeed, DiscordFlag, DiscordRank, DistanceToNearestDiscord, TimeSinceLastMotif, TimeSinceLastDiscord, DistanceToNearestChangePoint and NearestChangePointScore. NearestChangePointScore is the score of the change point nearest to the window; if two change points are equally near, the earlier one is used. # apaPatternRecognition.WindowPatternFeatures.FromSeries(series, windowSize, topKPairs, radiusMultiplier, topKDiscords, topKChangePoints, minSpacing) URL: https://www.andreassteiner.net/help/apapatternrecognition.windowpatternfeatures.fromseries/ ## Result Calculates motif groups, discords and change points from a time series and returns features for each subsequence window. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *windowSize*: length of the subsequences (window size) *topKPairs*: number of seed motif pairs for the motif grouping. Default value: 5 *radiusMultiplier*: multiplier applied to the seed motif distance to obtain the group radius. Default value: 1.5 *topKDiscords*: number of top discords to include. Default value: 5 *topKChangePoints*: number of top change points to include. Default value: 3 *minSpacing*: minimum spacing between change points. Default value: −1, i.e. windowSize ## Algorithm The matrix profile is calculated (see apaPatternRecognition.MatrixProfile). ## Remarks The result has the same columns as apaPatternRecognition.WindowPatternFeatures. # apaPiecewiseRegression.B(Y, X, nPieces) URL: https://www.andreassteiner.net/help/apapiecewiseregression.b/ ## Result ## Returns the parameters for a piecewise linear regression of n pieces. ## Syntax *Y*: data vector of the explained variable *X*: data vector of the explanatory variable *nPieces*: number of pieces (quantiles) # apaPiecewiseRegression.R2(Y, X, nPieces) URL: https://www.andreassteiner.net/help/apapiecewiseregression.r2/ ## Result ## Returns R2 for a piecewise linear regression of n pieces. ## Syntax *Y*: data vector of the explained variable *X*: data vector of the explanatory variable *nPieces*: number of pieces (quantiles) # apaPiecewiseRegression.Res(Y, X, nPieces) URL: https://www.andreassteiner.net/help/apapiecewiseregression.res/ ## Result ## Returns residuals for a piecewise linear regression of n pieces. ## Syntax *Y*: data vector of the explained variable *X*: data vector of the explanatory variable *nPieces*: number of pieces (quantiles) # apaPiecewiseRegression.X(Y, X, nPieces) URL: https://www.andreassteiner.net/help/apapiecewiseregression.x/ ## Result ## Returns X variables for a piecewise linear regression of n pieces. ## Syntax *Y*: data vector of the explained variable *X*: data vector of the explanatory variable *nPieces*: number of pieces (quantiles) # apaPiecewiseRegression.X.Breakpoints(Y, Breakpoints) URL: https://www.andreassteiner.net/help/apapiecewiseregression.x.breakpoints/ ## Result Returns the X variables (design matrix) of a piecewise linear regression with connected segments, defined by n breakpoints. ## Syntax *Y*: data vector of the explained variable *Breakpoints*: row vector of breakpoint indices # apaPiecewiseRegression.Yhat(Y, X, nPieces) URL: https://www.andreassteiner.net/help/apapiecewiseregression.yhat/ ## Result ## Returns fitted values for a piecewise linear regression of n pieces. ## Syntax *Y*: data vector of the explained variable *X*: data vector of the explanatory variable *nPieces*: number of pieces (quantiles) # apaPcdf(k, Lambda) URL: https://www.andreassteiner.net/help/apapcdf/ ## Result Cumulative distribution function of the Poisson distribution, i.e. the probability of at most k events. ## Syntax *k*: number of events *Lambda*: expected number of events (Poisson parameter lambda) # apaPinv(Prob, Lambda) URL: https://www.andreassteiner.net/help/apapinv/ ## Result Inverse cumulative distribution function of the Poisson distribution, i.e. the smallest number of events k with a probability of at most k events of at least Prob. ## Syntax *Prob*: probability between 0 and 1 *Lambda*: expected number of events (Poisson parameter lambda) # apaPpdf(k, Lambda) URL: https://www.andreassteiner.net/help/apappdf/ ## Result Probability mass function of the Poisson distribution, i.e. the probability of exactly k events. ## Syntax *k*: number of events *Lambda*: expected number of events (Poisson parameter lambda) # apaPrnd(Lambda) URL: https://www.andreassteiner.net/help/apaprnd/ ## Result Returns a random number drawn from a Poisson distribution, i.e. a random number of events. ## Syntax *Lambda*: expected number of events (Poisson parameter lambda) # apaProfitFactor(Returns) URL: https://www.andreassteiner.net/help/apaprofitfactor/ ## Result Returns the profit factor, the sum of gains divided by the sum of losses. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. ## Algorithm Profit factor = Σ max(r, 0) / Σ max(−r, 0). ## Remarks The result is a 1 x c row vector with one value per column of Returns. Equals apaOmega with a threshold of 0. \#N/A is returned if there are no negative returns. # apaProspectRatio(Returns, Threshold, LossAversion) URL: https://www.andreassteiner.net/help/apaprospectratio/ ## Result Returns the prospect ratio, a downside-risk ratio that weights losses more heavily than gains, as in prospect theory. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *Threshold*: optional; minimum acceptable return per period, e.g. the riskfree rate; default: 0 *LossAversion*: optional; loss aversion coefficient applied to negative returns (at least 0); default: 2.25 ## Algorithm Prospect ratio = (mean(max(r, 0) + LossAversion · min(r, 0)) − Threshold) / σD (Watanabe 2006, Bacon 2013). σD = sqrt(Σ max(Threshold − r, 0)² / n) is the downside deviation below Threshold (population, denominator n). ## Remarks The result is a 1 x c row vector with one value per column of Returns. \#N/A is returned if no return lies below Threshold. # apaPsim(nObs, Lambda) URL: https://www.andreassteiner.net/help/apapsim/ ## Result Returns a vector of random numbers drawn from a Poisson distribution, i.e. random numbers of events. ## Syntax *nObs*: number of observations to simulate *Lambda*: expected number of events (Poisson parameter lambda) ## Remarks This function is volatile, i.e. it is recalculated whenever a change occurs, even if not related to the function’s output. The function is also recalculated when pressing F9. # apaPolygon.Concave(X, Y) URL: https://www.andreassteiner.net/help/apapolygon.concave/ ## Result Selects the points of a set of two-dimensional observations (X,Y) which constitute the concave polygon around the dataset. ## Syntax *X*: r x 1 vector of observations in dataset X *Y*: r x 1 vector of observations in dataset Y ## Remarks > See [Concave polygon - Wikipedia](https://en.wikipedia.org/wiki/Concave_polygon) # apaPolygon.Convex(X, Y) URL: https://www.andreassteiner.net/help/apapolygon.convex/ ## Result Selects the points of a set of two-dimensional observations (X,Y) which constitute the convex polygon around the dataset. ## Syntax *X*: r x 1 vector of observations in dataset X *Y*: r x 1 vector of observations in dataset Y ## Remarks See [*Convex polygon - Wikipedia*](https://en.wikipedia.org/wiki/Convex_polygon) # apaPolygon.Regular.Layout(CenterX, CenterY, nCorners, nPointsInterpolated) URL: https://www.andreassteiner.net/help/apapolygon.regular.layout/ ## Result Returns the layout of a regular polygon with given center coordinates and number of corners. ## Syntax *CenterX*: X coordinate of the center *CenterY*: Y coordinate of the center *nCorners*: number of corner points defining the polygon *nPointsInterpolated*: number of points to interpolate between the corner points # apaPolynomial.Roots(Coeffs) URL: https://www.andreassteiner.net/help/apapolynomial.roots/ ## Result Returns all real and complex roots of a polynomial with integer exponents. ## Syntax *Coeffs*: 1 x n vector of coefficients. The first element is a(n), the last element is a(0), i.e. the constant # apaPortfolio.Resampled.MeanReturn(Weights, ReturnMatrix, ConfidenceLevel, SampleSize, NumberOfResamples) URL: https://www.andreassteiner.net/help/apaportfolio.resampled.meanreturn/ ## Result Resamples the asset returns and calculates the mean and the lower/upper confidence bounds of the portfolio mean return. ## Syntax *Weights*: 1 x c vector of portfolio constituent weights *ReturnMatrix*: r x c matrix of asset returns, each column containing a times series *ConfidenceLevel*: confidence level of the confidence interval, e.g. 95% *SampleSize*: number of observations per resample. A good starting point is the number of observations in the return matrix *NumberOfResamples*: number of times to resample. 1000 is a good starting point # apaPortfolio.Resampled.Volatility(Weights, ReturnMatrix, ConfidenceLevel, SampleSize, NumberOfResamples) URL: https://www.andreassteiner.net/help/apaportfolio.resampled.volatility/ ## Result Resamples the asset returns and calculates the mean and the lower/upper confidence bounds of the portfolio volatility. ## Syntax *Weights*: 1 x c vector of portfolio constituent weights *ReturnMatrix*: r x c matrix of asset returns, each column containing a times series *ConfidenceLevel*: confidence level of the confidence interval, e.g. 95% *SampleSize*: number of observations per resample. A good starting point is the number of observations in the return matrix *NumberOfResamples*: number of times to resample. 1000 is a good starting point ## Remarks Bootstrapped volatilities are sample volatilities (denominator SampleSize − 1). # apaPortfolio.Resampled.VolatilityContr(Weights, ReturnMatrix, ConfidenceLevel, SampleSize, NumberOfResamples) URL: https://www.andreassteiner.net/help/apaportfolio.resampled.volatilitycontr/ ## Result Resamples the asset returns and calculates the mean and the lower/upper confidence bounds of the portfolio volatility contributions. The result is a matrix with the mean, the lower confidence bound and the upper confidence bound of the volatility contributions. ## Syntax *Weights*: 1 x c vector of portfolio constituent weights *ReturnMatrix*: r x c matrix of asset returns, each column containing a times series *ConfidenceLevel*: confidence level of the confidence interval, e.g. 95% *SampleSize*: number of observations per resample. A good starting point is the number of observations in the return matrix *NumberOfResamples*: number of times to resample. 1000 is a good starting point ## Remarks Bootstrapped volatilities and covariances are sample moments (denominator SampleSize − 1). # apaPriceSim.BB(InitialPrice, TerminalPrice, nSims, nPaths, dt, mu, sigma) URL: https://www.andreassteiner.net/help/apapricesim.bb/ ## Result Simulates prices which follow a Brownian bridge, i.e. a geometric Brownian motion with a deterministic ending value. Each row contains an observation, each column a price path. ## Syntax *InitialPrice*: beginning price, e.g. 100. *TerminalPrice*: ending price, e.g. 125. *nSims*: number of observations to simulate *nPaths*: number of price paths to simulate *dt*: time step between two observations, e.g. 1/12 for monthly, 1 for annual and 1/250 for daily prices *mu*: expected mean of the noise term, e.g. zero for no drift. *sigma*: volatility of noise term # apaPriceSim.GBM(IntialPrice, nSims, nPaths, dt, mu, sigma) URL: https://www.andreassteiner.net/help/apapricesim.gbm/ ## Result Simulates prices which follow a geometric Brownian motion. Each row contains an observation, each column a price path. ## Syntax *IntialPrice*: beginning price, e.g. 100. *nSims*: number of observations to simulate *nPaths*: number of price paths to simulate *dt*: time step between two observations, e.g. 1/12 for monthly, 1 for annual and 1/250 for daily prices *mu*: expected mean of the noise term, e.g. zero for no drift. *sigma*: volatility of noise term ## Remarks The continuous price returns are expected to follow a geometric Brownian motion. # apaPriceSim.MN(IntialPrice, nSims, nPaths, dt, prob1, mu1, sigma1, mu2, sigma2) URL: https://www.andreassteiner.net/help/apapricesim.mn/ ## Result Simulates prices which follow a normal mixture process. Each row contains an observation, each column a price path. ## Syntax *IntialPrice*: beginning price, e.g. 100. *nSims*: number of observations to simulate *nPaths*: number of price paths to simulate *dt*: time step between two observations, e.g. 1/12 for monthly, 1 for annual and 1/250 for daily prices *prob1*: probability of state 1 (e.g. normal market conditions with a probability of 90%) *mu1*: mean in state 1 *sigma1*: volatility in state 1 *mu2*: mean in state 2 *sigma2*: volatility in state 2 ## Remarks The continuous price returns are expected to follow a normal mixture distribution. # apaPriceSim.JDLN(IntialPrice, nSims, nPaths, dt, mu, sigma, JumpIntensity, JumpSize, JumpVola) URL: https://www.andreassteiner.net/help/apapricesim.jdln/ ## Result Simulates prices which follow a jump-diffusion process with lognormally distributed jumps (Hull). Each row contains an observation, each column a price path. ## Syntax *IntialPrice*: beginning price, e.g. 100. *nSims*: number of observations to simulate *nPaths*: number of price paths to simulate *dt*: time step between two observations, e.g. 1/12 for monthly, 1 for annual and 1/250 for daily prices *mu*: mean of noise term *sigma*: volatility of noise term *JumpIntensity*: jump intensity, i.e. the expected number of jumps p.a. *JumpSize*: expected jump size p.a. *JumpVola*: jump volatility p.a. ## Remarks The continuous price returns are expected to follow a jump-diffusion process. # apaPriceSim.GARCH11(IntialPrice, nSims, nPaths, dt, mu, sigma, a, b) URL: https://www.andreassteiner.net/help/apapricesim.garch11/ ## Result Simulates prices which follow a GARCH(1,1) process. Each row contains an observation, each column a price path. ## Syntax *IntialPrice*: initial price, e.g. 100. *nSims*: number of observations to simulate *nPaths*: number of price paths to simulate *dt*: time step between two observations, e.g. 1/12 for monthly, 1 for annual and 1/250 for daily prices *mu*: expected mean of the noise term, e.g. zero for no drift. *sigma*: annualized unconditional (long-run) volatility, e.g. 0.2 for 20% *a*: GARCH parameter a (alpha, weight of the squared shocks) *b*: GARCH parameter b (beta, weight of the lagged variance) ## Algorithm Each path starts at the unconditional variance and follows the recursion ``` math v_{0} = \sigma^{2},\quad\quad\varepsilon_{t} = z_{t}\sqrt{v_{t - 1}\,\Delta t},\quad\quad v_{t} = (1 - a - b)\,\sigma^{2} + a\,\frac{\varepsilon_{t}^{2}}{\Delta t} + b\, v_{t - 1} ``` The price path is ``` math P_{t} = P_{t - 1}\exp\left( \mu\,\Delta t + \varepsilon_{t} \right) ``` where z(t) are independent standard normal random numbers, Δt is dt and v(t) is the annualized conditional variance. Because the squared shock is annualized with 1/dt in the variance update, the long-run (unconditional) volatility of the simulated returns equals sigma for any time step dt. ## Remarks The continuous price returns are expected to follow a GARCH(1,1) process. a + b must be smaller than one for the process to be stationary. # apaPriceSim.ARMA22(IntialPrice, nSims, nPaths, dt, mu, sigma, AR1, AR2, MA1, MA2) URL: https://www.andreassteiner.net/help/apapricesim.arma22/ ## Result Simulates prices which follow an ARMA(2,2) process. Each row contains an observation, each column a price path. ## Syntax *IntialPrice*: initial price, e.g. 100. *nSims*: number of observations to simulate *nPaths*: number of price paths to simulate *dt*: time step between two observations, e.g. 1/12 for monthly, 1 for annual and 1/250 for daily prices *mu*: expected mean of the noise term, e.g. zero for no drift. *sigma*: volatility of the noise term *AR1*: the first autoregressive coefficient *AR2*: the second autoregressive coefficient *MA1*: the first moving average coefficient *MA2*: the second moving average coefficient ## Remarks The continuous price returns are expected to follow an ARMA(2,2) process. # apaPrivateMarkets.Simulate.Fund.MultiPath(ParameterSet, PathCount) URL: https://www.andreassteiner.net/help/apaprivatemarkets.simulate.fund.multipath/ ## Result Runs a multi-path private fund J-curve simulation for a single fund parameter set and returns the assumptions and percentile summaries across simulation paths. ## Syntax *ParameterSet*: n x 1 vector of parameter values *PathCount*: number of Monte Carlo simulation paths ## Algorithm ParameterSet is mapped into the initial state, the J-curve parameters and the scenario settings of the fund, as in apaPrivateMarkets.Simulate.Fund.OnePath. # apaPrivateMarkets.Simulate.Portfolio.SharedFactor.OnePath(FundMatrix, SharedSeed) URL: https://www.andreassteiner.net/help/apaprivatemarkets.simulate.portfolio.sharedfactor.onepath/ ## Result Runs a one-path portfolio private fund J-curve simulation with fund-specific shared-factor betas, using a fund parameter matrix and common shocks across funds. ## Syntax *FundMatrix*: n x 25 matrix, each row containing one fund *SharedSeed*: optional; random seed of the common quarterly shocks; default: 987654 ## Algorithm Inputs are validated: FundMatrix non-empty, at least one fund, at least 25 columns. # apaPrivateMarkets.Simulate.Fund.OnePath(ParameterSet) URL: https://www.andreassteiner.net/help/apaprivatemarkets.simulate.fund.onepath/ ## Result Runs a single-path private fund J-curve simulation with a parameter vector and returns the assumptions and the full time series output. ## Syntax *ParameterSet*: n x 1 vector of parameter values ## Algorithm ParameterSet is mapped to the initial fund state (commitment, NAV, unfunded, paid-in, distributions, age), the J-curve parameters (life, investment period, harvest start, call and yield rates, growth rate, tail parameters, maximum fractions) and the scenario parameters (exit delay, tail extension, write-down shock, noise volatility). # apaPrivateMarkets.Simulate.Portfolio.MultiPath(FundMatrix, PathCount) URL: https://www.andreassteiner.net/help/apaprivatemarkets.simulate.portfolio.multipath/ ## Result Runs a multi-path (Monte Carlo) portfolio private fund J-curve simulation for a matrix of fund parameters and returns percentile summaries. ## Syntax *FundMatrix*: n x 22 matrix, each row containing one fund *PathCount*: number of Monte Carlo simulation paths ## Algorithm Inputs are validated: FundMatrix non-empty with at least one fund and 22 columns; PathCount \> 0. # apaPrivateMarkets.Simulate.Portfolio.SharedFactor.MultiPath(FundMatrix, PathCount, SharedSeed) URL: https://www.andreassteiner.net/help/apaprivatemarkets.simulate.portfolio.sharedfactor.multipath/ ## Result Runs a multi-path portfolio private fund J-curve simulation with fund-specific shared-factor betas and returns percentile summaries across paths. ## Syntax *FundMatrix*: n x 25 matrix, each row containing one fund *PathCount*: number of Monte Carlo simulation paths *SharedSeed*: optional; random seed of the common quarterly shocks; default: 987654 ## Algorithm Inputs are validated: FundMatrix and PathCount. # apaPrivateMarkets.Simulate.Portfolio.OnePath(FundMatrix) URL: https://www.andreassteiner.net/help/apaprivatemarkets.simulate.portfolio.onepath/ ## Result Runs a one-path portfolio private fund J-curve simulation for a matrix of fund parameters. ## Syntax *FundMatrix*: n x 22 matrix, each row containing one fund ## Algorithm Inputs are validated: FundMatrix non-empty, at least one fund, at least 22 columns. # apaQuantileRegression.Betas(X, Y, Quantile) URL: https://www.andreassteiner.net/help/apaquantileregression.betas/ ## Result Estimates the coefficients of a quantile regression of Y on the X variables for a given quantile (intercept first). ## Syntax *X*: nRows x nCols matrix of X variables, each column containing one variable *Y*: nRows x 1 vector of the Y variable *Quantile*: quantile to estimate, strictly between 0 and 1, e.g. 0.5 for median regression. # apaRachevRatio(PortfolioReturns, ConfidenceLevelLosses, ConfidenceLevelGains) URL: https://www.andreassteiner.net/help/aparachevratio/ ## Result Calculates the Rachev ratio, a risk-adjusted performance measure, i.e. the conditional value at gain (CVaG) divided by the conditional value at risk (CVaR). ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *ConfidenceLevelLosses*: confidence level of the losses (CVaR), e.g. 95% *ConfidenceLevelGains*: confidence level of the gains (CVaG), e.g. 95% ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image100.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image101.svg) ## Remarks CVaG is the average of the returns above the ConfidenceLevelGains percentile (for 0.95 the best 5% of returns); CVaR is the average of the returns below the 1 − ConfidenceLevelLosses percentile (for 0.95 the worst 5%). # apaRegressogram(X, Y, nBins, IsSortedXYOtherwiseY) URL: https://www.andreassteiner.net/help/aparegressogram/ ## Result Regressogram, a non-parametric method for estimating a regression function, i.e. the regression analogue of a histogram: the mean of Y within bins of X. ## Syntax *X*: n x 1 vector of the independent variable *Y*: n x 1 vector of the dependent variable *nBins*: number of bins to segment the data *IsSortedXYOtherwiseY*: TRUE to return the result sorted in ascending order of X, FALSE to retain the original order of X # apaResidualRisk(PortfolioReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/aparesidualrisk/ ## Result Calculates the residual risk, i.e. the volatility of the residuals of a single-index (one-factor) model, a measure of tracking error. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image102.svg) σε = √max(0, σP² − Cov(rP, rB)² / σB²), with sample moments (denominator n − 1). # apaRandomForest.Regression.MDI(Y, X, maxDepth, minSamplesSplit, nTrees, minObs, maxObs, minFeatures, maxFeatures) URL: https://www.andreassteiner.net/help/aparandomforest.regression.mdi/ ## Result Calculates the random forest regression feature importance as mean decrease in impurity (MDI). ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of predictors *maxDepth*: maximum depth of the trees (determines the number of branches) *minSamplesSplit*: minimum number of observations required to split a node *nTrees*: number of trees in the forest *minObs*: minimum number of observations sampled per tree *maxObs*: maximum number of observations sampled per tree *minFeatures*: minimum number of features sampled per tree *maxFeatures*: maximum number of features sampled per tree # apaRandomForest.Regression.PredictionsWithIntervals(Y, X, predictedX, maxDepth, minSamplesSplit, nTrees, minObs, maxObs, minFeatures, maxFeatures) URL: https://www.andreassteiner.net/help/aparandomforest.regression.predictionswithintervals/ ## Result Returns random forest regression predictions with confidence intervals. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of predictors *predictedX*: m x c matrix of predictors for which to predict *maxDepth*: maximum depth of the trees (determines the number of branches) *minSamplesSplit*: minimum number of observations required to split a node *nTrees*: number of trees in the forest *minObs*: minimum number of observations sampled per tree *maxObs*: maximum number of observations sampled per tree *minFeatures*: minimum number of features sampled per tree *maxFeatures*: maximum number of features sampled per tree # apaDecisionTree.Regression.PredictorsAndTheirSplits(Y, X, predictedX, maxDepth, minSamplesSplit) URL: https://www.andreassteiner.net/help/apadecisiontree.regression.predictorsandtheirsplits/ ## Result Decision tree regression: returns the selected predictor variables and their split points. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of predictors *predictedX*: m x c matrix of predictors for which to predict *maxDepth*: maximum depth of the tree (determines the number of branches) *minSamplesSplit*: minimum number of observations required to split a node # apaRandomForest.Regression.R2(Y, X, maxDepth, minSamplesSplit, nLags, nTrees, minObs, maxObs, minFeatures, maxFeatures) URL: https://www.andreassteiner.net/help/aparandomforest.regression.r2/ ## Result Returns the R-squared of a random forest regression. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of predictors *maxDepth*: maximum depth of the trees (determines the number of branches) *minSamplesSplit*: minimum number of observations required to split a node *nLags*: number of lags *nTrees*: number of trees in the forest *minObs*: minimum number of observations sampled per tree *maxObs*: maximum number of observations sampled per tree *minFeatures*: minimum number of features sampled per tree *maxFeatures*: maximum number of features sampled per tree # apaRandomForest.Regression.Timeseries.ForecastWithIntervals(Y, maxDepth, minSamplesSplit, nLags, nAhead, nTrees, minObs, maxObs, minFeatures, maxFeatures) URL: https://www.andreassteiner.net/help/aparandomforest.regression.timeseries.forecastwithintervals/ ## Result Random forest time series regression: returns forecasts with confidence intervals. ## Syntax *Y*: r x 1 data vector containing a time series *maxDepth*: maximum depth of the trees (determines the number of branches) *minSamplesSplit*: minimum number of observations required to split a node *nLags*: number of lags used as predictors *nAhead*: number of periods ahead to forecast *nTrees*: number of trees in the forest *minObs*: minimum number of observations sampled per tree *maxObs*: maximum number of observations sampled per tree *minFeatures*: minimum number of features sampled per tree *maxFeatures*: maximum number of features sampled per tree # apaRandomForest.Regression.Timeseries.R2(Y, maxDepth, minSamplesSplit, nLags, nTrees, minObs, maxObs, minFeatures, maxFeatures) URL: https://www.andreassteiner.net/help/aparandomforest.regression.timeseries.r2/ ## Result Random forest time series regression: returns the R-squared. ## Syntax *Y*: r x 1 data vector containing a time series *maxDepth*: maximum depth of the trees (determines the number of branches) *minSamplesSplit*: minimum number of observations required to split a node *nLags*: number of lags used as predictors *nTrees*: number of trees in the forest *minObs*: minimum number of observations sampled per tree *maxObs*: maximum number of observations sampled per tree *minFeatures*: minimum number of features sampled per tree *maxFeatures*: maximum number of features sampled per tree # apaRandomForest.Regression.YhatWithIntervalsAndResiduals(Y, X, maxDepth, minSamplesSplit, nTrees, minObs, maxObs, minFeatures, maxFeatures) URL: https://www.andreassteiner.net/help/aparandomforest.regression.yhatwithintervalsandresiduals/ ## Result Random forest regression: returns the fitted Y values, their confidence intervals and the residuals. ## Syntax *Y*: r x 1 vector of the dependent variable *X*: r x c matrix of predictors *maxDepth*: maximum depth of the trees (determines the number of branches) *minSamplesSplit*: minimum number of observations required to split a node *nTrees*: number of trees in the forest *minObs*: minimum number of observations sampled per tree *maxObs*: maximum number of observations sampled per tree *minFeatures*: minimum number of features sampled per tree *maxFeatures*: maximum number of features sampled per tree # apaRandomWeights.Restricted(NumberOfAllocations, PortfolioExposure, LowerBounds, UpperBounds) URL: https://www.andreassteiner.net/help/aparandomweights.restricted/ ## Result Generates random allocations subject to lower and upper bounds and a constraint on total exposure. The algorithm used is Latin hypercube sampling. ## Syntax *NumberOfAllocations*: number of random allocations to generate *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *LowerBounds*: 1 x c vector of constituent lower bounds *UpperBounds*: 1 x c vector of constituent upper bounds ## Algorithm Each allocation is generated in two steps. First, every constituent weight is drawn by Latin hypercube sampling within its bounds: the range from the lower to the upper bound is divided into NumberOfAllocations intervals of equal width, and each interval is used exactly once per constituent across the allocations. Second, the equality constraint is imposed. With the residual e = PortfolioExposure - sum of the weights, all weights are moved towards their upper bounds if e \> 0, or towards their lower bounds if e \< 0, each in proportion to its remaining room: w(j) + s (UpperBound(j) - w(j)) or w(j) - s (w(j) - LowerBound(j)), where s is the absolute residual divided by the total remaining room. Every allocation then sums exactly to PortfolioExposure and respects all bounds. ## Remarks The constraints are feasible if the sum of the lower bounds does not exceed PortfolioExposure and PortfolioExposure does not exceed the sum of the upper bounds; otherwise the function returns an error message. The adjustment in the second step changes the distribution of the weights, so the individual columns are no longer exactly Latin hypercube stratified, and the allocations are not uniformly distributed over the feasible set. With symmetric bounds the expected weights are equal across constituents. # apaRandomWeights.Restricted.Subspace(NumberOfAllocations, PortfolioExposure, LowerBounds, UpperBounds, nSubspaceMinimum) URL: https://www.andreassteiner.net/help/aparandomweights.restricted.subspace/ ## Result Generates random allocations subject to lower and upper bounds and a constraint on total exposure. Subspace method, i.e. the number of constituents in a portfolio is allowed to be smaller than the number of assets. ## Syntax *NumberOfAllocations*: number of random allocations to generate *PortfolioExposure*: value of the equality constraint on total portfolio exposure, i.e. the sum of constituent exposures *LowerBounds*: 1 x c vector of constituent lower bounds *UpperBounds*: 1 x c vector of constituent upper bounds *nSubspaceMinimum*: minimum number of portfolio constituents # apaRandomWeights.Filter(Allocations, LowerBounds, UpperBounds) URL: https://www.andreassteiner.net/help/aparandomweights.filter/ ## Result Extracts the allocations which are within given lower and upper bounds. ## Syntax *Allocations*: matrix of weights, each row containing a different allocation *LowerBounds*: 1 x c vector of lower bounds *UpperBounds*: 1 x c vector of upper bounds # apaRating.EndingAllocation(InitialAllocation, RatingTransitionMatrix) URL: https://www.andreassteiner.net/help/aparating.endingallocation/ ## Result Calculates the expected ending rating allocation, given an initial allocation and a rating transition matrix. ## Syntax *InitialAllocation*: 1 x n vector with the initial allocation across rating classes *RatingTransitionMatrix*: n x n rating transition matrix, each row containing the transition probabilities of a rating class ## Algorithm MMULT(InitialAllocation, RatingTransitionMatrix) # apaRating.TransitionMatrix.Compound(RatingTransitionMatrix, nYears) URL: https://www.andreassteiner.net/help/aparating.transitionmatrix.compound/ ## Result Compounds (extrapolates) a rating transition matrix over n years. ## Syntax *RatingTransitionMatrix*: n x n rating transition matrix, each row containing the transition probabilities of a rating class *nYears*: number of years (periods) over which to compound ## Algorithm RatingTransitionMatrix^nYears # apaRegimes.States.FromResponsibilities(Responsibilities) URL: https://www.andreassteiner.net/help/aparegimes.states.fromresponsibilities/ ## Result Derives the state trajectory vector from a matrix of responsibilities, i.e. the most probable state of each observation. ## Syntax *Responsibilities*: r x c matrix of responsibilities, each column containing a state # apaRegimes.TransitionMatrix.FromStates(States, IsStateProbsOtherwiseTransitionProbs) URL: https://www.andreassteiner.net/help/aparegimes.transitionmatrix.fromstates/ ## Result Calculates the transition matrix from a state trajectory vector. Read the matrix as from row to column. ## Syntax *States*: r x 1 vector of states *IsStateProbsOtherwiseTransitionProbs*: TRUE to return the state probabilities, FALSE to return the transition probabilities # apaRegression.Betas.kFold(X, Y, B, k, IsAveragedOtherwiseShowFolds, FoldingType) URL: https://www.andreassteiner.net/help/aparegression.betas.kfold/ ## Result Applies given regression betas to k-folded data. The betas are not necessarily estimated from the data. ## Syntax *X*: rows x columns matrix of data. Each column containing a variable. *Y*: rows x 1 of data *B*: 1 x c vector of regression betas (not necessarily estimated from X and Y; can be any estimator) *k*: number of folds to perform on the data. When averaged results are chosen, k can be a rows x 1 vector of k values. *IsAveragedOtherwiseShowFolds*: show results averaged over all folds, otherwise results per fold *FoldingType*: optional; folding type: 1 = standard k-fold, 2 = time series rolling k-fold, 3 = time series cumulative k-fold; default: 1 # apaRegression.Fitted(X, B) URL: https://www.andreassteiner.net/help/aparegression.fitted/ ## Result Calculates the fitted Y values from X and given betas. The betas are not necessarily estimated from the same data. ## Syntax *X*: rows x columns matrix of data. Each column containing a variable. *B*: 1 x c vector of regression betas (not necessarily estimated from X and Y; can be any estimator) # apaRegression.MSE(X, Y, B) URL: https://www.andreassteiner.net/help/aparegression.mse/ ## Result Calculates the mean squared error (MSE) from X, Y and given betas. The betas are not necessarily estimated from the data. ## Syntax *X*: rows x columns matrix of data. Each column containing a variable. *Y*: rows x 1 of data *B*: 1 x c vector of regression betas (not necessarily estimated from X and Y; can be any estimator) ## Remarks MSE = SSE/n, without degrees-of-freedom correction. # apaRegression.R2(X, Y, B) URL: https://www.andreassteiner.net/help/aparegression.r2/ ## Result Calculates the R-squared from X, Y and given betas. The betas are not necessarily estimated from the data. ## Syntax *X*: rows x columns matrix of data. Each column containing a variable. *Y*: rows x 1 of data *B*: 1 x c vector of regression betas (not necessarily estimated from X and Y; can be any estimator) # apaRegression.Residuals(X, Y, B) URL: https://www.andreassteiner.net/help/aparegression.residuals/ ## Result Calculates the residuals from X, Y and given betas. The betas are not necessarily estimated from the data. ## Syntax *X*: rows x columns matrix of data. Each column containing a variable. *Y*: rows x 1 of data *B*: 1 x c vector of regression betas (not necessarily estimated from X and Y; can be any estimator) # apaReplicateRiskReturn(nObservations, ExpectedReturns, Volatilites, Correlations) URL: https://www.andreassteiner.net/help/apareplicateriskreturn/ ## Result Generates random return time series with a given number of observations which exactly replicate given vectors of expected returns and volatilities and a given correlation matrix. ## Syntax *nObservations*: number of observations to generate *ExpectedReturns*: 1 x n vector with expected constituent returns *Volatilites*: 1 x n vector of constituent volatilities *Correlations*: n x n correlation matrix ## Remarks Typically, simulations in financial markets applications result in time series which are statistically equivalent to given risk and return characteristics. This function simulates a special case, namely time series which are exactly equivalent, in the sense that they perfectly replicate the inputs. Each time series is normally distributed. The simulated data reproduce the target volatilities as population volatilities (denominator n). # apaResample.TimeSeries(TimeSeries, nSeries, nObs, ProbNeighbour) URL: https://www.andreassteiner.net/help/aparesample.timeseries/ ## Result Resamples a time series with replacement (bootstrap), optionally as a stationary block bootstrap, generating several resampled series. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *nSeries*: number of time series to generate (determines the number of columns of the result) *nObs*: number of observations to generate (determines the number of rows of the result) *ProbNeighbour*: probability that the next observation drawn is the chronological neighbour of the previous one. Zero for a simple bootstrap. ## Algorithm The resampling algorithm performs “drawing with replacement”, i.e. a particular observation can occur more than once. ## Remarks ProbNeighbour can be used to preserve the autocorrelation structure of the original time series. Use the autocorrelation functions to analyze the original time series first. # apaResample.TimeSeries.WithoutReplacement(TimeSeries, nSeries, nObs) URL: https://www.andreassteiner.net/help/aparesample.timeseries.withoutreplacement/ ## Result Resamples (shuffles) a time series without replacement, generating several resampled series. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *nSeries*: number of time series to generate (determines the number of columns of the result) *nObs*: number of observations to generate (determines the number of rows of the result) ## Algorithm For each series, a random permutation of the observations is drawn and the first nObs observations are returned. ## Remarks The resampling algorithm performs “drawing without replacement”, i.e. each observation occurs at most once per series. nObs must therefore not exceed the number of observations. # apaResample.TimeSeriesMatrix(TimeSeriesMatrix, nObs, ProbNeighbour) URL: https://www.andreassteiner.net/help/aparesample.timeseriesmatrix/ ## Result Resamples the rows of a time series matrix with replacement (bootstrap), optionally as a stationary block bootstrap, i.e. preserving the dependency structure of multivariate data. ## Syntax *TimeSeriesMatrix*: r x c time series matrix, each column containing a time series *nObs*: number of observations to generate (determines the number of rows of the result) *ProbNeighbour*: probability that the next observation drawn is the chronological neighbour of the previous one. Zero for a simple bootstrap. ## Algorithm The resampling algorithm performs “drawing with replacement”, i.e. a particular observation can occur more than once. ## Remarks ProbNeighbour can be used to preserve the autocorrelation structure of the original time series. Use the autocorrelation functions to analyze the original time series first. # apaResample.TimeSeriesMatrix.WithoutReplacement(TimeSeriesMatrix, nObs) URL: https://www.andreassteiner.net/help/aparesample.timeseriesmatrix.withoutreplacement/ ## Result Resamples (shuffles) the rows of a time series matrix without replacement, preserving the cross-sectional dependence. ## Syntax *TimeSeriesMatrix*: time series matrix, each column a time series *nObs*: number of observations to generate ## Algorithm A random permutation of the row indices is drawn and the first nObs rows of the permuted matrix are returned. ## Remarks The resampling algorithm performs “drawing without replacement”, i.e. each observation occurs at most once. nObs must therefore not exceed the number of observations. # apaReturn.Annualize.FromDates(r, StartDate, EndDate) URL: https://www.andreassteiner.net/help/apareturn.annualize.fromdates/ ## Result Annualizes a return figure calculated over the period from a start date to an end date. ## Syntax *r*: a return figure *StartDate*: start calendar date *EndDate*: end calendar date ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image103.svg) PeriodLengthPerAnnum is determined from the start and end dates. The day count convention 30/360 assumes that a month has 30 days and a year 360. Act/Act calculates with actual calendar days. ## Remarks The date values must be valid Excel dates. # apaReturn.Average.Continuous.FromWeights(Weights, Returns) URL: https://www.andreassteiner.net/help/apareturn.average.continuous.fromweights/ ## Result Calculates portfolio returns from constituent weights and returns. ## Syntax *Weights*: 1 x c vector of constituent weights *Returns*: r x c matrix of constituent returns ## Remarks A constant allocation portfolio is calculated, i.e. it is assumed that the portfolio is always perfectly rebalanced to its initial weights. # apaReturn.IRR(BMV, EMV, CF, CFTime) URL: https://www.andreassteiner.net/help/apareturn.irr/ ## Result Calculates the money-weighted return, also known as internal rate of return (IRR) or dollar-weighted return, from a beginning and an ending market value and cash in- and outflows. ## Syntax *BMV*: beginning market value *EMV*: ending market value *CF*: n x 1 vector of portfolio cash in- and outflows (contributions and withdrawals) *CFTime*: n x 1 vector of the cash flow time points, between 0 and 1 ## Algorithm The bisection method is used, starting from the maximum/minimum possible figures that can be processed in Excel. The search is carried out until a solution as close to zero as 0.00001 has been found. If no solution is found, the search is stopped after 1’000’000 trials, returning an error value. ## Remarks It is assumed that the time period between beginning and end equals one. Therefore, CFTime values are between 0 and 1. CFTime is measured from the beginning of the period to the point in time the cash flow occurs. E.g. a value of 0.25 means that the flow occurred after 25% of the investment period had passed, i.e. was invested for 75% of the investment period. # apaReturn.IRR.All(BMV, EMV, CF, CFTime, nPeriods, IsPeriodResult) URL: https://www.andreassteiner.net/help/apareturn.irr.all/ ## Result Calculates all real and complex IRR solutions. ## Syntax *BMV*: beginning market value *EMV*: ending market value *CF*: n x 1 vector of portfolio cash in- and outflows (contributions and withdrawals) *CFTime*: n x 1 vector with cash flow time points (integer values) *nPeriods*: number of periods per year *IsPeriodResult*: TRUE to express the IRR solutions as subperiod returns, FALSE to express them as returns over the full investment period ## Algorithm A polynomial equation is solved to find the IRR values. # apaReturn.IRR.AvgCapital(BMV, EMV, CF, CFTime) URL: https://www.andreassteiner.net/help/apareturn.irr.avgcapital/ ## Result Calculates the average capital invested which is implied by the money-weighted return (IRR). ## Syntax *BMV*: beginning market value *EMV*: ending market value *CF*: n x 1 cash flow vector *CFTime*: n x 1 vector of the cash flow time points, between 0 and 1 ## Algorithm The average capital is calculated as the profit or loss divided by the IRR (see apaReturn.IRR and apaReturn.ProfitLoss). ## Remarks See apaReturn.IRR for the conventions on CFTime. # apaReturn.ModifiedDietz(BMV, EMV, CF, CFTime) URL: https://www.andreassteiner.net/help/apareturn.modifieddietz/ ## Result Calculates the time-weighted return according to the Modified Dietz methodology. ## Syntax *BMV*: beginning market value *EMV*: ending market value *CF*: n x 1 vector of portfolio cash in- and outflows (contributions and withdrawals) *CFTime*: n x 1 vector of the cash flow time points, between 0 and 1 ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image104.svg) ## Remarks To get the original Dietz return, set all CFTime values equal to 0.5. It is assumed that the time period between beginning and end equals one. Therefore, CFTime values are between 0 and 1. CFTime is measured from the beginning of the period to the point in time the cash flow occurs. E.g. a value of 0.25 means that the flow occurred after 25% of the investment period had passed, i.e. was invested for 75% of the investment period. # apaReturn.ModifiedDietz.AvgCapital(BMV, CF, CFTime) URL: https://www.andreassteiner.net/help/apareturn.modifieddietz.avgcapital/ ## Result Calculates the average capital invested according to the Modified Dietz methodology. ## Syntax *BMV*: beginning market value *CF*: n x 1 cash flow vector *CFTime*: n x 1 vector of the cash flow time points, between 0 and 1 ## Algorithm The average capital is calculated as the beginning market value plus the time-weighted cash flows, each cash flow weighted with the fraction of the period it is invested, i.e. 1 − CFTime. ## Remarks Cash flows with CFTime = 0 are added to the beginning market value. Cash flows with CFTime = 1 are not considered. # apaReturn.Dietz(BMV, EMV, CF) URL: https://www.andreassteiner.net/help/apareturn.dietz/ ## Result Calculates the time-weighted return according to the original Dietz methodology. ## Syntax *BMV*: beginning market value *EMV*: ending market value *CF*: n x 1 vector of portfolio cash in- and outflows (contributions and withdrawals) ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image105.svg) ## Remarks It is assumed that all cash flows occur in the middle of the period, i.e. that they were invested for half of the investment period. # apaReturn.Dietz.AvgCapital(BMV, CF) URL: https://www.andreassteiner.net/help/apareturn.dietz.avgcapital/ ## Result Calculates the average capital invested according to the original Dietz methodology. ## Syntax *BMV*: beginning market value *CF*: n x 1 cash flow vector ## Algorithm The average capital is calculated as the beginning market value plus half of the sum of the cash flows. ## Remarks It is assumed that all cash flows occur in the middle of the period. # apaReturn.ProfitLoss(BMV, EMV, CF, CFTime) URL: https://www.andreassteiner.net/help/apareturn.profitloss/ ## Result Calculates the profit or loss from beginning and ending market values and cash flows. ## Syntax *BMV*: beginning market value *EMV*: ending market value *CF*: n x 1 cash flow vector *CFTime*: n x 1 vector of the cash flow time points, between 0 and 1 ## Algorithm The profit or loss is calculated as EMV − BMV − sum of cash flows. ## Remarks Cash flows with CFTime = 0 are treated as part of the beginning market value. # apaReturns.FromAllocations.Gross(Allocations, Returns) URL: https://www.andreassteiner.net/help/apareturns.fromallocations.gross/ ## Result Calculates portfolio returns from asset returns and allocations, without considering transaction costs. ## Syntax *Allocations*: matrix of target weights (beginning of period), each column containing an asset. The first column is the time period index *Returns*: time series matrix of asset returns, each column containing a time series # apaReturns.FromAllocations.Net(Allocations, Returns, TransactionCosts) URL: https://www.andreassteiner.net/help/apareturns.fromallocations.net/ ## Result Calculates portfolio returns from asset returns and allocations, net of transaction costs, assuming either equal costs for all assets or asset-specific costs. ## Syntax *Allocations*: matrix of target weights (beginning of period), each column containing an asset. The first column is the time period index *Returns*: time series matrix of asset returns, each column containing a time series *TransactionCosts*: 1 x 1 or 1 x n vector of transaction costs, expressed as cost per unit of portfolio weight traded, i.e. the cost incurred for changing the weight of an asset by one unit (e.g. from 0.10 to 1.10) # apaReturns.Means.Arithmetic(TimeSeries) URL: https://www.andreassteiner.net/help/apareturns.means.arithmetic/ ## Result Returns the arithmetic means of a time series matrix. ## Syntax *TimeSeries*: time series matrix, each column containing a series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image106.svg) # apaReturns.Means.Arithmetic.Jagged(TimeSeries) URL: https://www.andreassteiner.net/help/apareturns.means.arithmetic.jagged/ ## Result Returns the arithmetic means of a jagged time series matrix. ## Syntax *TimeSeries*: time series matrix, each column containing a series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image106.svg) for all existing r ## Remarks Each column is evaluated on its own numeric observations; empty cells, text, logical values and error values are skipped. The output is a 1 x c row vector. A column without numeric observations returns \#N/A. # apaReturns.Means.ExpWeighted(TimeSeries, HalfLife) URL: https://www.andreassteiner.net/help/apareturns.means.expweighted/ ## Result Returns the exponentially weighted means of a time series matrix. ## Syntax *TimeSeries*: matrix containing time series data, each column a series *HalfLife*: half-life of the exponential weighting scheme # apaReturns.Means.Geometric(TimeSeries) URL: https://www.andreassteiner.net/help/apareturns.means.geometric/ ## Result Returns the geometric means of a time series matrix. ## Syntax *TimeSeries*: time series matrix, each column containing a series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image107.svg) # apaReturns.Means.Geometric.Jagged(TimeSeries) URL: https://www.andreassteiner.net/help/apareturns.means.geometric.jagged/ ## Result Returns the geometric means of a jagged time series matrix. ## Syntax *TimeSeries*: time series matrix, each column containing a series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image107.svg) for all existing r ## Remarks Each column is evaluated on its own numeric observations; empty cells, text, logical values and error values are skipped. The output is a 1 x c row vector. A column without numeric observations, or with a return of -100% or lower, returns \#N/A. # apaReturns.Bear(PortfolioReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/apareturns.bear/ ## Result Returns the bear market returns, i.e. the portfolio returns when the benchmark return is negative. ## Syntax *PortfolioReturns*: r x c matrix of portfolio returns *BenchmarkReturns*: r x 1 data vector # apaReturns.BoomBust(ReturnTimeSeries, MinDrawdown, OutputType, DoSplit, MinDrawdownLength, DoShowCumReturnsOtherwiseBoomBustReturns) URL: https://www.andreassteiner.net/help/apareturns.boombust/ ## Result Identifies retrospective boom and bust phases of a return time series, based on high-water-mark drawdown episodes. The output has the length and orientation of ReturnTimeSeries, or two columns if DoSplit is TRUE; each observation is assigned to the phase that ends at or after it. Entries without figures contain 0. If DoShowCumReturnsOtherwiseBoomBustReturns is TRUE, the output instead contains the cumulative returns, grouped into a boom and a bust column, for charting. ## Syntax *ReturnTimeSeries*: r x 1 (or 1 x r) vector of simple returns in decimal form (0.01 = +1%) in chronological order *MinDrawdown*: optional minimum peak-to-trough drawdown in \[0, 1) required to retain a bust phase, e.g. 0.1 for 10%; default 0, i.e. every drawdown episode is retained *OutputType*: optional output type; 0 (default): return since phase start; 1: phase indicator with +1 = boom, -1 = bust, +2 = provisional boom, -2 = provisional bust; 2: phase number in chronological order *DoSplit*: optional; TRUE: boom figures in the first and bust figures in the second column (r x 2, or 2 x r for a row vector), with 0 where a phase does not apply; FALSE (default): one vector *MinDrawdownLength*: optional minimum length of a drawdown in periods, i.e. the number of observations from peak to trough, required to retain a bust phase; default 0, i.e. no length requirement *DoShowCumReturnsOtherwiseBoomBustReturns*: optional; TRUE: cumulative returns since the start of the sample, W(t) - 1, with boom phases in the first and bust phases in the second column (r x 2, or 2 x r for a row vector) and \#N/A where a phase does not apply; OutputType and DoSplit are then ignored; FALSE (default): output as defined by OutputType and DoSplit ## Algorithm The wealth index starts at 1 one period before the first return and compounds the returns, W(t) = (1 + r(1)) x ... x (1 + r(t)). A drawdown episode begins at a running high-water mark, continues while wealth remains below it and ends when wealth recovers to or exceeds it. For equal high-water marks the most recent one is the peak; for equal lows the first one is the trough. Episodes with a drawdown W(trough) / W(peak) - 1 of at least MinDrawdown in magnitude and a peak-to-trough length of at least MinDrawdownLength periods are retained. Bust phase: from a retained peak to the subsequent trough of the same episode. Boom phase: from the previous retained trough, or the start of the sample, to the next retained peak. The interval from the last retained trough to the last observation is a provisional boom phase. An unrecovered final drawdown is a provisional bust phase. Return since phase start: W(t) / W(start) - 1, i.e. each phase is rebased separately and starts at zero. Cumulative returns (DoShowCumReturnsOtherwiseBoomBustReturns = TRUE): W(t) - 1 in the column of the phase that contains t. Each phase also shows the observation at which it starts, i.e. the last observation of the preceding phase, so this boundary value appears in both columns and consecutive boom and bust segments join without a gap when the two columns are plotted as line series. ## Remarks Turning points are identified retrospectively, so the results are descriptive and not a trading signal. The trough of a provisional bust phase can still be revised lower. Smaller or shorter drawdown episodes are absorbed into the surrounding boom phase, so boom phases can contain temporary declines and bust phases temporary rallies; this is not a zig-zag turning-point algorithm. Blank or non-numeric cells are omitted, not imputed, and are returned as 0 (as \#N/A for cumulative returns); returns of -100% or less produce an error. The sample start and end affect the identified phases. To chart the phases, plot both columns of the cumulative-return output as line series with different colours against the dates. Excel line charts leave \#N/A entries as gaps when the setting Show \#N/A as an empty cell is active and empty cells are shown as gaps (the defaults under Select Data, Hidden and Empty Cells). Replacing \#N/A by 0 would draw the lines down to zero. # apaReturns.Bull(PortfolioReturns, BenchmarkReturns) URL: https://www.andreassteiner.net/help/apareturns.bull/ ## Result Returns the bull market returns, i.e. the portfolio returns when the benchmark return is larger than or equal to zero. ## Syntax *PortfolioReturns*: r x c matrix of portfolio returns *BenchmarkReturns*: r x 1 data vector # apaReturns.ContinuousToDiscrete(Returns) URL: https://www.andreassteiner.net/help/apareturns.continuoustodiscrete/ ## Result Converts continuous returns into discrete returns. ## Syntax *Returns*: r x c return matrix ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image108.svg) # apaReturns.Cumulative.Arithmetic(TimeSeries, DoShowEach) URL: https://www.andreassteiner.net/help/apareturns.cumulative.arithmetic/ ## Result Returns the cumulative return based on continuous subperiod returns, i.e. arithmetic sums. ## Syntax *TimeSeries*: time series matrix, each column containing a series *DoShowEach*: TRUE to show all cumulative values, FALSE to show the final cumulative result only ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image109.svg) # apaReturns.Cumulative.Geometric(TimeSeries, DoShowEach) URL: https://www.andreassteiner.net/help/apareturns.cumulative.geometric/ ## Result Returns the cumulative return based on discrete subperiod returns, i.e. chain-linking. ## Syntax *TimeSeries*: time series matrix, each column containing a series *DoShowEach*: TRUE to show all cumulative values, FALSE to show the final cumulative result only ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image110.svg) # apaReturns.FromConstWeights(Weights, Returns) URL: https://www.andreassteiner.net/help/apareturns.fromconstweights/ ## Result Calculates portfolio return time series from a matrix of constant constituent weights and a matrix of constituent returns. Each column of the result corresponds to a different portfolio. ## Syntax *Weights*: p x c matrix of constituent weights, each row containing a different portfolio. The sum of each row gives the total exposure (typically one) *Returns*: r x c matrix of constituent returns, each column containing a return time series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image111.svg) t = 1, 2, …, T-2, T-1, T # apaReturns.FromWeights(Weights, Returns) URL: https://www.andreassteiner.net/help/apareturns.fromweights/ ## Result Calculates a portfolio return time series from time-varying weights and returns. ## Syntax *Weights*: r x c matrix of weights (beginning of period), each column containing an asset and each row a point in time. The sum of each row gives the total exposure (typically one) *Returns*: r x c matrix of constituent returns, each column containing a return time series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image112.svg) t = 1, 2, …, T-2, T-1, T # apaReturns.FromPrices(Prices, IsDiscreteOtherwiseContinuous) URL: https://www.andreassteiner.net/help/apareturns.fromprices/ ## Result Converts prices into discrete or continuous returns. ## Syntax *Prices*: r x c matrix of prices *IsDiscreteOtherwiseContinuous*: optional; TRUE (or missing) for discrete returns, FALSE for continuous returns; default: TRUE ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image113.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image114.svg) ## Remarks The calculations do not reflect any income received (dividends, coupons, distributions) and are therefore price returns only. # apaReturns.DiscreteToContinuous(Returns) URL: https://www.andreassteiner.net/help/apareturns.discretetocontinuous/ ## Result Converts discrete returns into continuous returns. ## Syntax *Returns*: r x c return matrix ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image115.svg) # apaReturns.Down(Returns) URL: https://www.andreassteiner.net/help/apareturns.down/ ## Result Returns the down market returns, i.e. all negative returns. ## Syntax *Returns*: r x 1 data vector # apaReturns.HoldingPeriods.Arithmetic(TimeSeries) URL: https://www.andreassteiner.net/help/apareturns.holdingperiods.arithmetic/ ## Result Calculates the cumulative arithmetic returns for all possible holding periods. Entry points are in rows, the number of holding periods in columns. ## Syntax *TimeSeries*: time series vector, each row containing an observation # apaReturns.HoldingPeriods.Geometric(TimeSeries) URL: https://www.andreassteiner.net/help/apareturns.holdingperiods.geometric/ ## Result Calculates the cumulative geometric (chain-linked) returns for all possible holding periods. Entry points are in rows, the number of holding periods in columns. ## Syntax *TimeSeries*: time series vector, each row containing an observation # apaReturns.Random(nAssets) URL: https://www.andreassteiner.net/help/apareturns.random/ ## Result Generates a 1 x nAssets vector of uniformly distributed random returns between -100% and +100%. Multiply with a constant \< 1 to generate returns from a narrower range. ## Syntax *nAssets*: number of assets ## Remarks The returns are uniformly distributed between -100% and +100%. Multiply with a scalar \< 1 to draw from a narrower range. # apaReturns.Rolling(Returns, WindowSize, WindowIndex, IsNoOverlap, IsCum) URL: https://www.andreassteiner.net/help/apareturns.rolling/ ## Result Returns the data of a particular rolling window. ## Syntax *Returns*: r x c matrix of data *WindowSize*: window size *WindowIndex*: index of the window (1 returns the most recent window) *IsNoOverlap*: TRUE for non-overlapping windows, FALSE for overlapping windows *IsCum*: TRUE for cumulative (compounded) window returns, FALSE for the returns within the window # apaReturns.Rolling.All(Returns, WindowSize, IsNoOverlap) URL: https://www.andreassteiner.net/help/apareturns.rolling.all/ ## Result Returns all rolling windows, each column containing a window. ## Syntax *Returns*: r x c data matrix *WindowSize*: number of observations in the window *IsNoOverlap*: FALSE for overlapping windows, TRUE for non-overlapping rolling windows # apaReturns.Rolling.NumberOfWindows(nObs, WindowSize, IsNoOverlap) URL: https://www.andreassteiner.net/help/apareturns.rolling.numberofwindows/ ## Result Determines the number of rolling windows which can be calculated. ## Syntax *nObs*: number of observations in the data *WindowSize*: number of observations in the window *IsNoOverlap*: FALSE for overlapping windows, TRUE for non-overlapping rolling windows ## Algorithm For non-overlapping windows, the number of windows equals INT(nObs / WindowSize). For overlapping windows, it equals nObs − WindowSize + 1 (at least zero). ## Remarks The function is volatile. # apaReturns.Shrink.Hi(Returns, Shrinkage) URL: https://www.andreassteiner.net/help/apareturns.shrink.hi/ ## Result Shrinks a vector of cross-sectional returns towards the highest return. ## Syntax *Returns*: 1 x c return vector *Shrinkage*: shrinkage factor between 0% and 100% ## Algorithm Each element is calculated as (1 − Shrinkage) \* r(i) + Shrinkage \* max(r). ## Remarks The function is volatile. # apaReturns.Shrink.Lo(Returns, Shrinkage) URL: https://www.andreassteiner.net/help/apareturns.shrink.lo/ ## Result Shrinks a vector of cross-sectional returns towards the lowest return. ## Syntax *Returns*: 1 x c return vector *Shrinkage*: shrinkage factor between 0% and 100% ## Algorithm Each element is calculated as (1 − Shrinkage) \* r(i) + Shrinkage \* min(r). ## Remarks The function is volatile. # apaReturns.Shrink.Mean(Returns, Shrinkage) URL: https://www.andreassteiner.net/help/apareturns.shrink.mean/ ## Result Shrinks a vector of cross-sectional returns towards the mean return. ## Syntax *Returns*: 1 x c return vector *Shrinkage*: shrinkage factor between 0% and 100% ## Algorithm Each element is calculated as (1 − Shrinkage) \* r(i) + Shrinkage \* mean(r). ## Remarks The function is volatile. # apaReturns.Simulate.ARMA22(nSims, nPaths, dt, mu, sigma, AR1, AR2, MA1, MA2) URL: https://www.andreassteiner.net/help/apareturns.simulate.arma22/ ## Result Simulates returns which follow an ARMA(2,2) process. See apaPriceSim.ARMA22 for details. ## Syntax *nSims*: number of observations to simulate *nPaths*: number of paths to simulate *dt*: time step dt, e.g. 1/12 for monthly frequency *mu*: expected mean of the noise term, e.g. zero for no drift. *sigma*: volatility of the noise term *AR1*: the first autoregressive coefficient *AR2*: the second autoregressive coefficient *MA1*: the first moving average coefficient *MA2*: the second moving average coefficient # apaReturns.Simulate.GARCH11(nSims, nPaths, dt, mu, sigma, a, b) URL: https://www.andreassteiner.net/help/apareturns.simulate.garch11/ ## Result Simulates returns which follow a GARCH(1,1) process. See apaPriceSim.GARCH11 for details. ## Syntax *nSims*: number of observations to simulate *nPaths*: number of paths to simulate *dt*: time step dt, e.g. 1/12 for monthly frequency *mu*: expected mean of the noise term, e.g. zero for no drift. *sigma*: annualized unconditional (long-run) volatility, e.g. 0.2 for 20% *a*: GARCH parameter a (alpha, weight of the squared shocks) *b*: GARCH parameter b (beta, weight of the lagged variance) ## Algorithm Each path starts at the unconditional variance and follows the recursion ``` math v_{0} = \sigma^{2},\quad\quad\varepsilon_{t} = z_{t}\sqrt{v_{t - 1}\,\Delta t},\quad\quad v_{t} = (1 - a - b)\,\sigma^{2} + a\,\frac{\varepsilon_{t}^{2}}{\Delta t} + b\, v_{t - 1} ``` The simulated returns are ``` math r_{t} = \mu\,\Delta t + \varepsilon_{t} ``` where z(t) are independent standard normal random numbers, Δt is dt and v(t) is the annualized conditional variance. Because the squared shock is annualized with 1/dt in the variance update, the long-run (unconditional) volatility of the simulated returns equals sigma for any time step dt. ## Remarks a + b must be smaller than one for the process to be stationary. # apaReturns.Simulate.GBM(nSims, nPaths, dt, mu, sigma) URL: https://www.andreassteiner.net/help/apareturns.simulate.gbm/ ## Result Simulates returns which follow a geometric Brownian motion. See apaPriceSim.GBM for details. ## Syntax *nSims*: number of observations to simulate *nPaths*: number of paths to simulate *dt*: time step dt, e.g. 1/12 for monthly frequency *mu*: expected mean of the noise term, e.g. zero for no drift. *sigma*: volatility of noise term # apaReturns.Lower(PortfolioReturns, BenchmarkReturns, Threshold) URL: https://www.andreassteiner.net/help/apareturns.lower/ ## Result Extracts the lower returns, defined as the conditional portfolio returns rp \| rb \< Threshold. ## Syntax *PortfolioReturns*: r x c matrix of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *Threshold*: threshold value ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image116.svg) t is the threshold. # apaReturns.Upper(PortfolioReturns, BenchmarkReturns, Threshold) URL: https://www.andreassteiner.net/help/apareturns.upper/ ## Result Extracts the upper returns, defined as the conditional portfolio returns rp \| rb \>= Threshold. ## Syntax *PortfolioReturns*: r x c matrix of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *Threshold*: threshold value ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image117.svg) t is the threshold. # apaReturns.Up(Returns) URL: https://www.andreassteiner.net/help/apareturns.up/ ## Result Returns the up market returns, i.e. all positive returns. ## Syntax *Returns*: r x 1 data vector # apaRuns.Losing(Returns) URL: https://www.andreassteiner.net/help/aparuns.losing/ ## Result Returns the losing runs, i.e. the cumulative losses of consecutive negative returns. ## Syntax *Returns*: r x 1 vector of returns # apaRuns.Winning(Returns) URL: https://www.andreassteiner.net/help/aparuns.winning/ ## Result Returns the winning runs, i.e. the cumulative gains of consecutive positive returns. ## Syntax *Returns*: r x 1 vector of returns # apaSSA.Signal(TimeSeries, nLags, nComponents) URL: https://www.andreassteiner.net/help/apassa.signal/ ## Result Returns the signal of a singular spectrum analysis (SSA) of time series data, reconstructed from the leading components. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *nLags*: embedding dimension, i.e. number of lags. *nComponents*: number of components used to reconstruct the signal ## Remarks See the literature on singular spectrum analysis for details, for example Hassani H.: “Singular Spectrum Analysis: Methodology and Comparison”, Journal of Data Science 5(2007), p239-257 or Zhigljavsky A.: “Singular Spectrum Analysis: present, past and future”, conference presentation. > If the input data has several time series, multivariate SSA will be performed automatically. # apaSSA.Signal.Forecast(TimeSeries, nLags, nComponents, nForecasts) URL: https://www.andreassteiner.net/help/apassa.signal.forecast/ ## Result Returns forecasts (forward linear prediction) of the signal of a singular spectrum analysis (SSA) of time series data. ## Syntax *TimeSeries*: nRows x nCols matrix of data, each column containing a time series *nLags*: embedding dimension, i.e. integer number of lags *nComponents*: integer number of components used to reconstruct the signal *nForecasts*: integer number of forecasts ## Remarks See the literature on singular spectrum analysis for details, for example Hassani H.: “Singular Spectrum Analysis: Methodology and Comparison”, Journal of Data Science 5(2007), p239-257 or Zhigljavsky A.: “Singular Spectrum Analysis: present, past and future”, conference presentation. > If the input data has several time series, multivariate SSA will be performed automatically. # apaSSA.Signal.Redrawn(TimeSeries, nLags, nComponents, StartRedraw) URL: https://www.andreassteiner.net/help/apassa.signal.redrawn/ ## Result Recalculates the singular spectrum analysis (SSA) signal on expanding windows, showing how the signal is redrawn when new observations arrive. Returns a matrix of signals. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *nLags*: embedding dimension, i.e. number of lags. *nComponents*: number of components used to reconstruct the signal *StartRedraw*: number of observations in the first window ## Remarks See the literature on singular spectrum analysis for details, for example Hassani H.: “Singular Spectrum Analysis: Methodology and Comparison”, Journal of Data Science 5(2007), p239-257 or Zhigljavsky A.: “Singular Spectrum Analysis: present, past and future”, conference presentation. > If the input data has several time series, multivariate SSA will be performed automatically. # apaSSA.Components(TimeSeries, nLags) URL: https://www.andreassteiner.net/help/apassa.components/ ## Result Returns the component signal matrix of a singular spectrum analysis (SSA) of time series data. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *nLags*: embedding dimension, i.e. number of lags. ## Remarks - Components are additive, i.e. each row of the matrix adds up to the actual observation of the original time series. - If the input data has several time series, multivariate SSA will be performed automatically. - See the literature on singular spectrum analysis for details, for example Hassani H.: “Singular Spectrum Analysis: Methodology and Comparison”, Journal of Data Science 5(2007), p239-257 or Zhigljavsky A.: “Singular Spectrum Analysis: present, past and future”, conference presentation. # apaSSA.Components.Forecast(TimeSeries, nLags, nForecasts) URL: https://www.andreassteiner.net/help/apassa.components.forecast/ ## Result Returns forecasts (forward linear prediction) of the components of a singular spectrum analysis (SSA) of time series data. ## Syntax *TimeSeries*: nRows x nCols matrix of data, each column containing a time series *nLags*: embedding dimension, i.e. integer number of lags *nForecasts*: integer number of forecasts ## Remarks See the literature on singular spectrum analysis for details, for example Hassani H.: “Singular Spectrum Analysis: Methodology and Comparison”, Journal of Data Science 5(2007), p239-257 or Zhigljavsky A.: “Singular Spectrum Analysis: present, past and future”, conference presentation. > If the input data has several time series, multivariate SSA will be performed automatically. # apaSSA.Spectrum(TimeSeries, nLags) URL: https://www.andreassteiner.net/help/apassa.spectrum/ ## Result Returns the spectrum of a singular spectrum analysis (SSA) of time series data, i.e. the sorted eigenvalues of all components. ## Syntax *TimeSeries*: nRows x nCols matrix of data, each column containing a time series *nLags*: embedding dimension, i.e. integer number of lags ## Remarks - The spectrum consists of a vector of sorted eigenvalues of all components. - If the input data has several time series, multivariate SSA will be performed automatically. - See the literature on singular spectral analysis for details, for example Hassani H.: “Singular Spectrum Analysis: Methodology and Comparison”, Journal of Data Science 5(2007), p239-257 or Zhigljavsky A.: “Singular Spectrum Analysis: present, past and future”, conference presentation. # apaSSA.Spectrum.Percent(TimeSeries, nLags) URL: https://www.andreassteiner.net/help/apassa.spectrum.percent/ ## Result Returns the spectrum of a singular spectrum analysis (SSA) of time series data, with eigenvalues expressed as percentage figures. ## Syntax *TimeSeries*: nRows x nCols matrix of data, each column containing a time series *nLags*: embedding dimension, i.e. integer number of lags ## Remarks - The spectrum consists of a vector of sorted eigenvalues of all components. - If the input data has several time series, multivariate SSA will be performed automatically. - See the literature on singular spectrum analysis for details, for example Hassani H.: “Singular Spectrum Analysis: Methodology and Comparison”, Journal of Data Science 5(2007), p239-257 or Zhigljavsky A.: “Singular Spectrum Analysis: present, past and future”, conference presentation. # apaSSA.Spectrum.Percent.Cum(TimeSeries, nLags) URL: https://www.andreassteiner.net/help/apassa.spectrum.percent.cum/ ## Result Returns the spectrum of a singular spectrum analysis (SSA) of time series data, with eigenvalues expressed as cumulative percentage figures. ## Syntax *TimeSeries*: nRows x nCols matrix of data, each column containing a time series *nLags*: embedding dimension, i.e. integer number of lags ## Remarks - The spectrum consists of a vector of sorted eigenvalues of all components. - If the input data has several time series, multivariate SSA will be performed automatically. - See the literature on singular spectrum analysis for details, for example Hassani H.: “Singular Spectrum Analysis: Methodology and Comparison”, Journal of Data Science 5(2007), p239-257 or Zhigljavsky A.: “Singular Spectrum Analysis: present, past and future”, conference presentation. # apaSSA.wCorrels(TimeSeries, nLags) URL: https://www.andreassteiner.net/help/apassa.wcorrels/ ## Result Returns the w-correlation matrix of the components of a singular spectrum analysis (SSA) of time series data. ## Syntax *TimeSeries*: nRows x nCols matrix of data, each column containing a time series *nLags*: embedding dimension, i.e. integer number of lags ## Remarks - The w-correlations measure the separability of the components. Components with high absolute w-correlations should be grouped together. - If the input data has several time series, multivariate SSA will be performed automatically. - See the literature on singular spectrum analysis for details, for example Hassani H.: “Singular Spectrum Analysis: Methodology and Comparison”, Journal of Data Science 5(2007), p239-257 or Zhigljavsky A.: “Singular Spectrum Analysis: present, past and future”, conference presentation. # apaSharpeRatio(PortfolioReturns, RiskfreeReturns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apasharperatio/ ## Result Returns the Sharpe ratio of a portfolio, a risk-adjusted performance measure. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *RiskfreeReturns*: r x 1 vector of riskfree returns *IsSampleOtherwisePopulation*: optional; TRUE for sample volatility (division by n-1), FALSE for population volatility (division by n); default: TRUE ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image118.svg) ## Remarks - The input time series are assumed to be continuous returns. If you are processing discrete returns, first transform them with apaReturns.DiscreteToContinuous. The volatility is the sample (denominator n − 1) or population (denominator n) standard deviation, set by IsSampleOtherwisePopulation; default: sample. - Both portfolio returns and riskfree returns must have the same frequency (e.g. daily, monthly, annually). The result will have the same frequency as the input data (i.e. daily Sharpe ratios from daily data, monthly Sharpe ratios from monthly data). # apaSharpeRatio.FromConst(AssetWeights, AssetExcessReturns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apasharperatio.fromconst/ ## Result Calculates the Sharpe ratio of a constant-weight portfolio from constituent excess returns. ## Syntax *AssetWeights*: 1 x n vector of constituent weights *AssetExcessReturns*: r x n matrix of constituent excess returns, each column containing a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample volatility (division by n-1), FALSE for population volatility (division by n); default: FALSE ## Algorithm The Sharpe ratio is calculated as the average portfolio excess return divided by the portfolio volatility, assuming constant weights, i.e. a portfolio which is always rebalanced to its weights. ## Remarks The volatility is the sample (denominator n − 1) or population (denominator n) standard deviation, set by IsSampleOtherwisePopulation; default: population. # apaSharpeRatio.Annualized.Lo(Returns, PeriodsPerYear, RiskfreeReturns, nLags) URL: https://www.andreassteiner.net/help/apasharperatio.annualized.lo/ ## Result Returns the annualized Sharpe ratio of excess returns, adjusted for serial correlation. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *PeriodsPerYear*: number of return periods per year (whole number), e.g. 12 for monthly data *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 *nLags*: optional; number of autocorrelation lags used, between 0 and PeriodsPerYear − 1; 0 gives SR·sqrt(PeriodsPerYear); default: PeriodsPerYear − 1 ## Algorithm SR(q) = SR·q / sqrt(q + 2·Σ\_{k=1..L} (q − k)·ρ_k) (Lo 2002), with q = PeriodsPerYear and L = nLags. SR uses the sample standard deviation (denominator n − 1); ρ_k are the sample autocorrelations of the excess returns (sum of lagged cross-products divided by the sum of squared deviations). ## Remarks The result is a 1 x c row vector with one value per column of Returns. Positive autocorrelation (e.g. smoothed or illiquid returns) lowers the annualized Sharpe ratio compared with SR·sqrt(q). \#N/A is returned if the adjusted variance is not positive. # apaSharpeRatio.Deflated(Returns, RiskfreeReturns, nTrials, TrialSharpeVariance) URL: https://www.andreassteiner.net/help/apasharperatio.deflated/ ## Result Returns the deflated Sharpe ratio (DSR): the probabilistic Sharpe ratio measured against the Sharpe ratio expected from the best of several unskilled strategies, correcting for selection bias under multiple testing. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 *nTrials*: optional; number of strategies tried, a whole number of at least 1; default: the number of columns of Returns *TrialSharpeVariance*: optional; variance of the per-period Sharpe ratios across the trials; default: sample variance (denominator n − 1) of the Sharpe ratios of the columns of Returns, which requires at least two columns ## Algorithm SR0 = sqrt(V)·((1 − γ)·Φ⁻¹(1 − 1/N) + γ·Φ⁻¹(1 − 1/(N·e))), with N = nTrials, V = TrialSharpeVariance and the Euler-Mascheroni constant γ ≈ 0.5772 (Bailey and López de Prado 2014). SR0 = 0 if N = 1. DSR = PSR with benchmark Sharpe ratio SR0, see apaSharpeRatio.Probabilistic. ## Remarks The result is a 1 x c row vector with one value per column of Returns. If Returns contains all tested strategies, both optional arguments can be left empty. # apaSharpeRatio.MinTrackRecordLength(Returns, RiskfreeReturns, BenchmarkSharpeRatio, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apasharperatio.mintrackrecordlength/ ## Result Returns the minimum track record length (MinTRL): the number of observations needed to conclude, at the given confidence level, that the true Sharpe ratio exceeds the benchmark Sharpe ratio. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 *BenchmarkSharpeRatio*: optional; per-period Sharpe ratio to test against (same frequency as the returns, not annualized); default: 0 *ConfidenceLevel*: optional; confidence level, e.g. 95%; default: 0.95 ## Algorithm MinTRL = 1 + (1 − γ3·SR + (γ4 − 1)/4·SR²)·(Φ⁻¹(ConfidenceLevel) / (SR − SR\*))² (Bailey and López de Prado 2012). The Sharpe ratio is the per-period ratio SR = mean(r − rf) / s(r − rf), with the sample standard deviation s (denominator n − 1). Skewness γ3 = m3 / m2^1.5 and non-excess kurtosis γ4 = m4 / m2² use population central moments (denominator n). ## Remarks The result is a 1 x c row vector with one value per column of Returns. The result is a number of observations at the frequency of the data. \#N/A is returned if SR is not greater than the benchmark Sharpe ratio. # apaSharpeRatio.Probabilistic(Returns, RiskfreeReturns, BenchmarkSharpeRatio) URL: https://www.andreassteiner.net/help/apasharperatio.probabilistic/ ## Result Returns the probabilistic Sharpe ratio (PSR): the probability that the true per-period Sharpe ratio exceeds a benchmark Sharpe ratio, allowing for skewness and fat tails. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 *BenchmarkSharpeRatio*: optional; per-period Sharpe ratio to test against (same frequency as the returns, not annualized); default: 0 ## Algorithm PSR = Φ((SR − SR\*)·sqrt(n − 1) / sqrt(1 − γ3·SR + (γ4 − 1)/4·SR²)) (Bailey and López de Prado 2012), where Φ is the standard normal distribution function and SR\* the benchmark Sharpe ratio. The Sharpe ratio is the per-period ratio SR = mean(r − rf) / s(r − rf), with the sample standard deviation s (denominator n − 1). Skewness γ3 = m3 / m2^1.5 and non-excess kurtosis γ4 = m4 / m2² use population central moments (denominator n). ## Remarks The result is a 1 x c row vector with one value per column of Returns. An annual benchmark Sharpe ratio must be converted to the data frequency first, e.g. divided by sqrt(12) for monthly data. # apaSharpeRatio.StandardError(Returns, RiskfreeReturns) URL: https://www.andreassteiner.net/help/apasharperatio.standarderror/ ## Result Returns the standard error of the per-period Sharpe ratio of excess returns for non-normal, serially independent returns. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *RiskfreeReturns*: optional; single value, r x 1 vector (shared by all columns) or r x c matrix of riskfree returns per period; default: 0 ## Algorithm σ(SR) = sqrt((1 − γ3·SR + (γ4 − 1)/4·SR²) / (n − 1)) (Mertens 2002, Opdyke 2007). The Sharpe ratio is the per-period ratio SR = mean(r − rf) / s(r − rf), with the sample standard deviation s (denominator n − 1). Skewness γ3 = m3 / m2^1.5 and non-excess kurtosis γ4 = m4 / m2² use population central moments (denominator n). ## Remarks The result is a 1 x c row vector with one value per column of Returns. \#N/A is returned if the excess returns are constant or the variance factor is not positive. # apaShortfallProb.Empirical(Returns, Threshold) URL: https://www.andreassteiner.net/help/apashortfallprob.empirical/ ## Result Returns the empirical probability of falling short of a given threshold, i.e. the share of observations below the threshold. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *Threshold*: return threshold # apaShortfallProb.ConfidenceIntervals(TimeSeries, Threshold, ConfidenceLevel, nSamples) URL: https://www.andreassteiner.net/help/apashortfallprob.confidenceintervals/ ## Result Calculates non-parametric confidence intervals for the shortfall probability based on resampling. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *Threshold*: return threshold *ConfidenceLevel*: confidence level, e.g. 0.95. *nSamples*: number of samples to generate # apaShrinkageEstimator.Covars.Jorion(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apashrinkageestimator.covars.jorion/ ## Result Jorion Bayesian shrinkage estimator for covariances. The historical covariance matrix is adjusted for the estimation risk of the mean returns, which are shifted towards the return of the minimum variance portfolio. ## Syntax *TimeSeriesMatrix*: n x m time series matrix, each column containing a variable, each row a set of observations ## Algorithm > ![Formula](https://www.andreassteiner.net/help/assets/eq/image119.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image120.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image121.svg)… vector of ones ![Formula](https://www.andreassteiner.net/help/assets/eq/image122.svg)… vector of historical mean returns ![Formula](https://www.andreassteiner.net/help/assets/eq/image123.svg)… return of the minimum variance portfolio ![Formula](https://www.andreassteiner.net/help/assets/eq/image124.svg)… helper variable ![Formula](https://www.andreassteiner.net/help/assets/eq/image125.svg)… historical covariance matrix ![Formula](https://www.andreassteiner.net/help/assets/eq/image126.svg)… shrunk covariance matrix ![Formula](https://www.andreassteiner.net/help/assets/eq/image127.svg)… number of observations ![Formula](https://www.andreassteiner.net/help/assets/eq/image128.svg)… number of assets ## Remarks The formulas were taken (and corrected) from Gorman/Jorgensen(2002): “Domestic versus International Portfolio Selection: A Statistical Examination of the Home Bias”, Journal of Multinational Finance. Uses the sample covariance matrix (denominator n − 1). # apaShrinkageEstimator.Covars.LedoitWolf.ConstantCorrelations(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apashrinkageestimator.covars.ledoitwolf.constantcorrelations/ ## Result Ledoit/Wolf constant correlation Bayesian shrinkage estimator for covariances. The historical covariance matrix is shrunk towards a target matrix with constant correlations. ## Syntax *TimeSeriesMatrix*: n x m time series matrix, each column containing a variable, each row a set of observations ## Algorithm > ![Formula](https://www.andreassteiner.net/help/assets/eq/image129.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image130.svg) > ![Formula](https://www.andreassteiner.net/help/assets/eq/image131.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image121.svg)… vector of ones ![Formula](https://www.andreassteiner.net/help/assets/eq/image122.svg)… vector of historical mean returns ![Formula](https://www.andreassteiner.net/help/assets/eq/image125.svg)… historical covariance matrix ![Formula](https://www.andreassteiner.net/help/assets/eq/image132.svg)… shrunk covariance matrix ![Formula](https://www.andreassteiner.net/help/assets/eq/image133.svg)…target covariance matrix, calculated from the historical average correlation matrix and historical volatilities ![Formula](https://www.andreassteiner.net/help/assets/eq/image134.svg)… helper variables, as defined in Appendix B in Ledoit/Wolf(2002) ![Formula](https://www.andreassteiner.net/help/assets/eq/image127.svg)… number of observations ## Remarks For details, see Ledoit/Wolf(2002): “Honey, I Shrunk the Sample Covariance Matrix”, Financial Analysts Journal. Shrinks the population covariance matrix (denominator n). # apaShrinkageEstimator.Covars.LedoitWolf.GeometricInverse(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apashrinkageestimator.covars.ledoitwolf.geometricinverse/ ## Result Ledoit/Wolf geometric inverse shrinkage (GIS) estimator for covariances, a non-linear shrinkage estimator. ## Syntax *TimeSeriesMatrix*: n x m time series matrix, each column containing a variable, each row a set of observations ## Remarks For details, see the publications of Ledoit/Wolf on non-linear shrinkage estimators. Shrinks the population covariance matrix (denominator n). # apaShrinkageEstimator.Covars.LedoitWolf.LinearInverse(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apashrinkageestimator.covars.ledoitwolf.linearinverse/ ## Result Ledoit/Wolf linear inverse shrinkage (LIS) estimator for covariances, a non-linear shrinkage estimator. ## Syntax *TimeSeriesMatrix*: n x m time series matrix, each column containing a variable, each row a set of observations ## Remarks For details, see the publications of Ledoit/Wolf on non-linear shrinkage estimators. Shrinks the population covariance matrix (denominator n). # apaShrinkageEstimator.Covars.LedoitWolf.QuadraticInverse(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apashrinkageestimator.covars.ledoitwolf.quadraticinverse/ ## Result Ledoit/Wolf quadratic inverse shrinkage (QIS) estimator for covariances, a non-linear shrinkage estimator. ## Syntax *TimeSeriesMatrix*: n x m time series matrix, each column containing a variable, each row a set of observations ## Remarks For details, see the publications of Ledoit/Wolf on non-linear shrinkage estimators. Shrinks the population covariance matrix (denominator n). # apaShrinkageEstimator.ExpectedReturns.JamesStein(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apashrinkageestimator.expectedreturns.jamesstein/ ## Result James/Stein Bayesian shrinkage estimator for expected returns. The historical mean returns are shrunk towards the historical mean return across all assets. ## Syntax *TimeSeriesMatrix*: n x m time series matrix, each column containing a variable, each row a set of observations ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image135.svg) > ![Formula](https://www.andreassteiner.net/help/assets/eq/image136.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image121.svg)… vector of ones ![Formula](https://www.andreassteiner.net/help/assets/eq/image137.svg)… shrinkage factor ![Formula](https://www.andreassteiner.net/help/assets/eq/image122.svg)… vector of historical mean asset returns ![Formula](https://www.andreassteiner.net/help/assets/eq/image138.svg)… average mean asset return ![Formula](https://www.andreassteiner.net/help/assets/eq/image125.svg)… historical covariance matrix ![Formula](https://www.andreassteiner.net/help/assets/eq/image127.svg)… number of observations ![Formula](https://www.andreassteiner.net/help/assets/eq/image128.svg)… number of assets ## Remarks Uses the sample covariance matrix (denominator n − 1). # apaShrinkageEstimator.ExpectedReturns.Jorion(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apashrinkageestimator.expectedreturns.jorion/ ## Result Jorion Bayesian shrinkage estimator for expected returns. The historical mean returns are shrunk towards the return of the minimum variance portfolio. ## Syntax *TimeSeriesMatrix*: n x m time series matrix, each column containing a variable, each row a set of observations ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image139.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image120.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image140.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image141.svg)… vector of shrunk returns ![Formula](https://www.andreassteiner.net/help/assets/eq/image137.svg)… shrinkage factor ![Formula](https://www.andreassteiner.net/help/assets/eq/image122.svg)… vector of historical mean returns ![Formula](https://www.andreassteiner.net/help/assets/eq/image123.svg)… return of the minimum variance portfolio ![Formula](https://www.andreassteiner.net/help/assets/eq/image121.svg)… vector of ones ![Formula](https://www.andreassteiner.net/help/assets/eq/image124.svg)… helper variable ![Formula](https://www.andreassteiner.net/help/assets/eq/image125.svg)… historical covariance matrix ![Formula](https://www.andreassteiner.net/help/assets/eq/image127.svg)… number of observations ![Formula](https://www.andreassteiner.net/help/assets/eq/image128.svg)… number of assets ## Remarks The formulas were taken (and corrected) from Gorman/Jorgensen(2002): “Domestic versus International Portfolio Selection: A Statistical Examination of the Home Bias”, Journal of Multinational Finance. Uses the sample covariance matrix (denominator n − 1). # apaSimilarities.Correl(Correls) URL: https://www.andreassteiner.net/help/apasimilarities.correl/ ## Result Derives a similarity matrix from a correlation matrix. The similarity equals 1 minus the distance derived from the correlations. ## Syntax *Correls*: n x n correlation matrix # apaSimilarities.Cosine(DataMatrix) URL: https://www.andreassteiner.net/help/apasimilarities.cosine/ ## Result Derives the cosine similarity matrix from a data matrix. Similarities range between -1 and 1. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series # apaSimilarities.FromDistances(Distances, IsWeighted) URL: https://www.andreassteiner.net/help/apasimilarities.fromdistances/ ## Result Derives a similarity matrix from a distance matrix. ## Syntax *Distances*: n x n distance matrix *IsWeighted*: TRUE to use the weight information in the off-diagonals, FALSE to use unit values # apaSingleIndexModel.X(PortfolioReturns, BenchmarkReturns, IsDualAlpha, IsDualBeta, IsNonLinear, Threshold, ForceZeroAlpha) URL: https://www.andreassteiner.net/help/apasingleindexmodel.x/ ## Result Returns the matrix of independent variables of a particular single index model specification. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *IsDualAlpha*: TRUE for separate alphas for benchmark returns below and above the threshold *IsDualBeta*: TRUE for separate betas for benchmark returns below and above the threshold *IsNonLinear*: TRUE to include a squared benchmark return term *Threshold*: benchmark return threshold separating down and up markets *ForceZeroAlpha*: optional; TRUE to force alpha to zero (no intercept); default: FALSE ## Algorithm The specification of the index model with all flags except ForceZeroAlpha set to TRUE looks like this… ![Formula](https://www.andreassteiner.net/help/assets/eq/image142.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image143.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image144.svg) # apaSingleIndexModel.B(PortfolioReturns, BenchmarkReturns, IsDualAlpha, IsDualBeta, IsNonLinear, Threshold, ForceZeroAlpha) URL: https://www.andreassteiner.net/help/apasingleindexmodel.b/ ## Result Returns the vector of estimated parameters of a particular single index model specification. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *IsDualAlpha*: TRUE for separate alphas for benchmark returns below and above the threshold *IsDualBeta*: TRUE for separate betas for benchmark returns below and above the threshold *IsNonLinear*: TRUE to include a squared benchmark return term *Threshold*: benchmark return threshold separating down and up markets *ForceZeroAlpha*: optional; TRUE to force alpha to zero (no intercept); default: FALSE ## Algorithm The specification of the index model with all flags except ForceZeroAlpha set to TRUE looks like this… ![Formula](https://www.andreassteiner.net/help/assets/eq/image145.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image143.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image144.svg) # apaSingleIndexModel.Yhat(PortfolioReturns, BenchmarkReturns, IsDualAlpha, IsDualBeta, IsNonLinear, Threshold, ForceZeroAlpha) URL: https://www.andreassteiner.net/help/apasingleindexmodel.yhat/ ## Result Returns the vector of fitted portfolio returns of a particular single index model specification. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *IsDualAlpha*: TRUE for separate alphas for benchmark returns below and above the threshold *IsDualBeta*: TRUE for separate betas for benchmark returns below and above the threshold *IsNonLinear*: TRUE to include a squared benchmark return term *Threshold*: benchmark return threshold separating down and up markets *ForceZeroAlpha*: optional; TRUE to force alpha to zero (no intercept); default: FALSE ## Algorithm The specification of the index model with all flags except ForceZeroAlpha set to TRUE looks like this… ![Formula](https://www.andreassteiner.net/help/assets/eq/image145.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image143.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image144.svg) # apaSingleIndexModel.Res(PortfolioReturns, BenchmarkReturns, IsDualAlpha, IsDualBeta, IsNonLinear, Threshold, ForceZeroAlpha) URL: https://www.andreassteiner.net/help/apasingleindexmodel.res/ ## Result Returns the vector of residuals of a particular single index model specification. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *IsDualAlpha*: TRUE for separate alphas for benchmark returns below and above the threshold *IsDualBeta*: TRUE for separate betas for benchmark returns below and above the threshold *IsNonLinear*: TRUE to include a squared benchmark return term *Threshold*: benchmark return threshold separating down and up markets *ForceZeroAlpha*: optional; TRUE to force alpha to zero (no intercept); default: FALSE ## Algorithm Residuals are calculated as the difference between the actual portfolio returns and fitted portfolio returns. The specification of the index model with all flags except ForceZeroAlpha set to TRUE looks like this… ![Formula](https://www.andreassteiner.net/help/assets/eq/image145.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image143.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image144.svg) # apaSingleIndexModel.R2(PortfolioReturns, BenchmarkReturns, IsDualAlpha, IsDualBeta, IsNonLinear, Threshold, ForceZeroAlpha) URL: https://www.andreassteiner.net/help/apasingleindexmodel.r2/ ## Result Returns the R-squared of a particular single index model specification. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *IsDualAlpha*: TRUE for separate alphas for benchmark returns below and above the threshold *IsDualBeta*: TRUE for separate betas for benchmark returns below and above the threshold *IsNonLinear*: TRUE to include a squared benchmark return term *Threshold*: benchmark return threshold separating down and up markets *ForceZeroAlpha*: optional; TRUE to force alpha to zero (no intercept); default: FALSE ## Algorithm R-squared is calculated as the squared correlation between the fitted and actual portfolio returns. # apaSkewness.ConfidenceIntervals(TimeSeries, ConfidenceLevel, nSamples) URL: https://www.andreassteiner.net/help/apaskewness.confidenceintervals/ ## Result Calculates confidence intervals for skewness, the third standardized central moment, using a resampling methodology. ## Syntax *TimeSeries*: r x 1 data vector containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. *nSamples*: number of samples to generate ## Remarks Uses the sample skewness (as Excel SKEW). # apaSkewness.ExpWeighted(TimeSeries, HalfLife) URL: https://www.andreassteiner.net/help/apaskewness.expweighted/ ## Result Returns the exponentially weighted skewnesses of a time series matrix, one skewness estimate per input series. ## Syntax *TimeSeries*: matrix containing time series data, each column a series *HalfLife*: half-life of the exponential weighting scheme ## Remarks Exponentially weighted moments; the weights sum to one (population-type, no small-sample correction). # apaSkewness.FromReturns(w, R) URL: https://www.andreassteiner.net/help/apaskewness.fromreturns/ ## Result Calculates portfolio skewness from a constituent weight vector and a constituent return matrix. ## Syntax *w*: 1 x n vector of constituent weights *R*: nObs x n matrix of constituent returns, each column containing a time series ## Remarks Uses population covariances and coskewness (denominator n). # apaSkewness.FromCoskews(w, Covars, Coskews) URL: https://www.andreassteiner.net/help/apaskewness.fromcoskews/ ## Result Calculates portfolio skewness from a constituent weight vector, a covariance matrix and a coskewness matrix. ## Syntax *w*: 1 x n vector of constituent weights *Covars*: n x n covariance matrix *Coskews*: coskewness matrix, e.g. from apaCoskews. # apaSkewness.Population(TimeSeries) URL: https://www.andreassteiner.net/help/apaskewness.population/ ## Result Returns the population skewness, i.e. a population version of the Excel function SKEW. ## Syntax *TimeSeries*: r x c matrix of data, each column containing a data series # apaSortinoRatio(PortfolioReturns, Threshold) URL: https://www.andreassteiner.net/help/apasortinoratio/ ## Result Returns the Sortino ratio, a risk-adjusted performance measure. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *Threshold*: return threshold ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image146.svg) ## Remarks Partial moments divide by the total number of observations n (population-type). # apaSpeed.Get() URL: https://www.andreassteiner.net/help/apaspeed.get/ ## Result Returns the current calculation speed level: 1 (accurate), 2 (balanced) or 3 (fast). ## Syntax This function has no arguments This function has no arguments. ## Remarks There exist three speed levels… 1 – Accurate: optimized for accuracy, not calculation performance 2 – Balanced: balancing accuracy and calculation speed 3 – Fast: optimized for calculation speed, not accuracy of results Currently, the speed settings only affect selected functions, for example apaWeights.Style.Rolling. The scope will be expanded gradually in future releases. # apaSpeed.Set(Level) URL: https://www.andreassteiner.net/help/apaspeed.set/ ## Result Sets the calculation speed level and returns the level set. ## Syntax *Level*: desired speed level. Must be 1 (=accurate), 2 (=balanced) or 3 (=fast). ## Algorithm The speed level applies to all subsequent calculations of the affected functions until it is changed again. ## Remarks There exist three speed levels… 1 – Accurate: optimized for accuracy, not calculation performance 2 – Balanced: balancing accuracy and calculation speed 3 – Fast: optimized for calculation speed, not accuracy of results Currently, the speed settings only affect selected functions, for example apaWeights.Style.Rolling. The scope will be expanded gradually in future releases. # apaSplitFactors(Dates, SplitList, nStocks) URL: https://www.andreassteiner.net/help/apasplitfactors/ ## Result Creates an r x nStocks table of stock split conversion factors, one row per date and one column per stock ID. Multiply a matrix of historical prices with the table to obtain split-adjusted prices. ## Syntax *Dates*: r x 1 date vector *SplitList*: r x 3 table with stock splits. First column contains ex-split date, second column the stock ID, third column the split factor. *nStocks*: maximum stock ID. Equals the maximum number of stocks in the universe. ## Algorithm All factors are initialized with 1, i.e. no adjustment. ## Remarks Stock IDs in SplitList must be integers between 1 and nStocks. Column j of the result corresponds to stock ID j. # apaSterlingRatio(PortfolioReturns, RiskfreeReturns, nDrawdowns) URL: https://www.andreassteiner.net/help/apasterlingratio/ ## Result Returns the Sterling ratio, a risk-adjusted performance measure, i.e. the average excess return divided by the absolute average depth of the *nDrawdowns* largest drawdown episodes. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *RiskfreeReturns*: r x 1 vector of riskfree returns *nDrawdowns*: number of largest drawdown episodes to use (at least 1) ## Algorithm STR = (r̄P − r̄f) / \|(D1 + … + DK) / K\| where D1, …, DK are the depths of the K deepest drawdown episodes, K = min(*nDrawdowns*, number of episodes). ## Remarks A drawdown episode is a run of observations below the running high-water mark of the cumulative return; its depth is the lowest value of the underwater curve within the run. If fewer than *nDrawdowns* episodes exist, all episodes are used. \#N/A is returned if the series has no drawdown. # apaStochasticDominance(Returns1, Returns2, Order, ShowDensitiesOtherwisePreference) URL: https://www.andreassteiner.net/help/apastochasticdominance/ ## Result Returns TRUE if Returns1 stochastically dominates Returns2 of the given order, FALSE otherwise. Alternatively, the integrated density vectors are returned. ## Syntax *Returns1*: r x 1 vector of returns *Returns2*: r x 1 vector of returns *Order*: order of stochastic dominance, e.g. 1 or 2. *ShowDensitiesOtherwisePreference*: optional; TRUE to show the integrated densities, FALSE to show the TRUE/FALSE dominance result; default: FALSE # apaStatFactors.PortfolioRisks(AssetReturns, nFactors, AssetWeights, IsCorrelElseCovar, DoForceUnitComponentVariances) URL: https://www.andreassteiner.net/help/apastatfactors.portfoliorisks/ ## Result Returns the total portfolio variance, the systematic variance based on a statistical factor model and the residual variance of a portfolio with given constituent weights. ## Syntax *AssetReturns*: r x c matrix containing the asset returns. Each column contains an asset return time series. *nFactors*: number of statistical factors *AssetWeights*: 1 x c vector of constituent weights *IsCorrelElseCovar*: TRUE to use the correlation matrix, FALSE to use the covariance matrix *DoForceUnitComponentVariances*: TRUE to scale the factors (principal components) to unit variance ## Remarks Uses population covariances (denominator n). # apaStatFactors.FactorWeights(AssetReturns, nFactors, AssetWeights, IsCorrelElseCovar, DoForceUnitComponentVariances) URL: https://www.andreassteiner.net/help/apastatfactors.factorweights/ ## Result Returns the factor exposures of a portfolio based on a statistical factor model derived from the constituent returns. ## Syntax *AssetReturns*: r x c matrix containing the asset returns. Each column contains an asset return time series. *nFactors*: number of statistical factors *AssetWeights*: 1 x c vector of constituent weights *IsCorrelElseCovar*: TRUE to use the correlation matrix, FALSE to use the covariance matrix *DoForceUnitComponentVariances*: TRUE to scale the factors (principal components) to unit variance ## Remarks Uses population covariances (denominator n). # apaStatFactors.Residuals(AssetReturns, nFactors, IsCorrelElseCovar, DoForceUnitComponentVariances) URL: https://www.andreassteiner.net/help/apastatfactors.residuals/ ## Result Returns the residual returns of a statistical factor model derived from the constituent returns. ## Syntax *AssetReturns*: r x c matrix containing the asset returns. Each column contains an asset return time series. *nFactors*: number of statistical factors *IsCorrelElseCovar*: TRUE to use the correlation matrix, FALSE to use the covariance matrix *DoForceUnitComponentVariances*: TRUE to scale the factors (principal components) to unit variance ## Remarks Uses population covariances (denominator n). # apaStatFactors.Factors(TimeSeries, nFactors, IsCorrelElseCovar, DoForceUnitComponentVariances) URL: https://www.andreassteiner.net/help/apastatfactors.factors/ ## Result Returns the factor return time series of a statistical factor model derived from the constituent returns. ## Syntax *TimeSeries*: r x c matrix containing the asset returns. Each column contains an asset return time series. *nFactors*: number of statistical factors *IsCorrelElseCovar*: TRUE to use the correlation matrix, FALSE to use the covariance matrix *DoForceUnitComponentVariances*: TRUE to scale the factors (principal components) to unit variance ## Remarks Uses population covariances (denominator n). # apaStatFactors.Betas(AssetReturns, nFactors, IsCorrelElseCovar, DoForceUnitComponentVariances) URL: https://www.andreassteiner.net/help/apastatfactors.betas/ ## Result Returns the factor betas of a statistical factor model derived from the constituent returns. ## Syntax *AssetReturns*: r x c matrix containing the asset returns. Each column contains an asset return time series. *nFactors*: number of statistical factors *IsCorrelElseCovar*: TRUE to use the correlation matrix, FALSE to use the covariance matrix *DoForceUnitComponentVariances*: TRUE to scale the factors (principal components) to unit variance ## Remarks Uses population covariances (denominator n). # apaStatFactors.Alphas(AssetReturns, nFactors, IsCorrelElseCovar, DoForceUnitComponentVariances) URL: https://www.andreassteiner.net/help/apastatfactors.alphas/ ## Result Returns the factor alphas in a statistical factor model derived from the portfolio constituent returns. ## Syntax *AssetReturns*: r x c matrix containing the asset returns. Each column contains an asset return time series. *nFactors*: number of statistical factors *IsCorrelElseCovar*: TRUE to use the correlation matrix, FALSE to use the covariance matrix *DoForceUnitComponentVariances*: TRUE to scale the factors (principal components) to unit variance ## Remarks Uses population covariances (denominator n). # apaStatFactors.VarianceExplained(AssetReturns, IsCorrelElseCovar) URL: https://www.andreassteiner.net/help/apastatfactors.varianceexplained/ ## Result Returns the sorted % of variance explained by each statistical factor, the cumulative % explained, the Eigenvalue of the factor and the factor index. ## Syntax *AssetReturns*: r x c matrix containing the asset returns. Each column contains an asset return time series. *IsCorrelElseCovar*: TRUE to use the correlation matrix, FALSE to use the covariance matrix ## Remarks Uses population covariances (denominator n). # apaStrategy.CPPI(RiskyReturns, RiskfreeRate, Multiplier, ProtectionLevel, MinRiskyExposure, MaxRiskyExposure) URL: https://www.andreassteiner.net/help/apastrategy.cppi/ ## Result Returns the value path of a CPPI (constant proportion portfolio insurance) strategy applied to a series of risky asset returns. ## Syntax *RiskyReturns*: r x 1 vector of returns of the risky asset *RiskfreeRate*: riskfree rate per period *Multiplier*: CPPI multiplier applied to the cushion *ProtectionLevel*: protected value (floor) at the end of the horizon, e.g. 0.9 for 90%. *MinRiskyExposure*: minimum exposure to the risky asset *MaxRiskyExposure*: maximum exposure to the risky asset ## Algorithm The strategy is calculated by the following standard CPPI program… Floor(t) = ProtectionLevel/(1+RiskfreeRate)^(T-t) Cushion(t) = MAX(PortfolioLevel(t)-Floor(t),0) RiskyExposure(t) = MAX(MIN(Multiplier\*Cushion(t), MaxRiskyExposure), MinRiskyExposure) CPPIReturn(t) = RiskyExposure(t)\*RiskyReturn(t) + (1-RiskyExposure(t))\*RiskfreeRate PortfolioLevel(t) = (1+CPPIReturn(t))\*PortfolioLevel(t-1) ## Remarks - The riskfree rate is a single rate, i.e. assumed to be constant. The riskfree rate is assumed to be a period figure, not an annualized rate. - MinRiskyExposure can be used to rule out short positions or a “lock-in” at 0%. - MaxRiskyExposure can be used to rule out leverage. # apaStresstest.Covars(DataMatrix, SampleSize, nSamples) URL: https://www.andreassteiner.net/help/apastresstest.covars/ ## Result Returns a bootstrap stress-tested covariance matrix from a return data matrix: the elementwise maximum, average and minimum covariances across the bootstrap samples. The result consists of the vertically stacked vech covariances. ## Syntax *DataMatrix*: numeric returns data matrix with observations in rows and assets/series in columns *SampleSize*: size of the resampled data sets *nSamples*: number of data sets to resample ## Remarks Bootstrapped covariances are sample covariances (denominator n − 1). # apaStresstest.ExpectedReturns(DataMatrix, SampleSize, nSamples) URL: https://www.andreassteiner.net/help/apastresstest.expectedreturns/ ## Result Returns bootstrap stressed expected returns: the worst, base and best expected return vectors, stacked vertically. ## Syntax *DataMatrix*: numeric returns data matrix with observations in rows and assets/series in columns *SampleSize*: size of the resampled data sets *nSamples*: number of data sets to resample # apaSummary.FiveNumber.Crosssectional(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apasummary.fivenumber.crosssectional/ ## Result Returns the cross-sectional five-number summary of a time series matrix. ## Syntax *TimeSeriesMatrix*: time series matrix, each column a time series ## Algorithm The following five statistics are calculated across the series (cross-sectionally)… 1. Minimum 2. 25% percentile (1st quartile) 3. Median 4. 75% percentile (3rd quartile) 5. Maximum # apaSummary.FiveNumber.Timeseries(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apasummary.fivenumber.timeseries/ ## Result Returns the time-series five-number summary of a time series matrix. ## Syntax *TimeSeriesMatrix*: time series matrix, each column a time series ## Algorithm The following five statistics are calculated for each series (time-series)… 1. Minimum 2. 25% percentile (1st quartile) 3. Median 4. 75% percentile (3rd quartile) 5. Maximum # apaSummary.SevenNumber.Crosssectional(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apasummary.sevennumber.crosssectional/ ## Result Returns the cross-sectional seven-number summary of a time series matrix. ## Syntax *TimeSeriesMatrix*: time series matrix, each column a time series ## Algorithm The following seven statistics are calculated across the series (cross-sectionally)… 1. Minimum 2. 25% percentile (1st quartile) 3. Median 4. 75% percentile (3rd quartile) 5. Maximum 6. Lower fence 7. Upper fence ## Remarks The lower fence is calculated as max(median - 1.5 \* (quartile3 – quartile1), minimum), the upper fence as min(median + 1.5 \* (quartile3 – quartile1), maximum). # apaSummary.SevenNumber.Timeseries(TimeSeriesMatrix) URL: https://www.andreassteiner.net/help/apasummary.sevennumber.timeseries/ ## Result Returns the time-series seven-number summary of a time series matrix. ## Syntax *TimeSeriesMatrix*: time series matrix, each column a time series ## Algorithm The following seven statistics are calculated for each series (time-series)… 1. Minimum 2. 25% percentile (1st quartile) 3. Median 4. 75% percentile (3rd quartile) 5. Maximum 6. Lower fence 7. Upper fence ## Remarks The lower fence is calculated as max(median - 1.5 \* (quartile3 – quartile1), minimum), the upper fence as min(median + 1.5 \* (quartile3 – quartile1), maximum). # apaSystem.Performance() URL: https://www.andreassteiner.net/help/apasystem.performance/ ## Result A test function returning an indicator of the computer system performance. The smaller the figure returned, the faster the system. ## Syntax \ This function has no arguments. ## Algorithm The function returns the time required to calculate 10’000’000 (ten million) standard normally distributed random numbers. The random numbers are calculated as follows (pseudocode)… Start Stopwatch For i = 1 to 10’000’000 aRandomNumber = GenerateStandardNormalRandomNumber() Next i End stopwatch # apaSystem.Custom.Install(VersionName) URL: https://www.andreassteiner.net/help/apasystem.custom.install/ ## Result Installs a custom version of the add-in. Requires the code of a custom version. ## Syntax *VersionName*: name of the custom version to install # apaSystem.Update() URL: https://www.andreassteiner.net/help/apasystem.update/ ## Result Initiates the update procedure manually, updating the add-in to the latest release available. ## Syntax \ This function has no arguments. ## Remarks Useful for updating unofficial versions to the latest public release. # apaTailDependence.L(Quantiles, X, Y) URL: https://www.andreassteiner.net/help/apataildependence.l/ ## Result Returns the left tail dependence, i.e. the conditional probability of joint occurrences up to a given quantile. ## Syntax *Quantiles*: nQtls x 1 quantile vector *X*: nObs x 1 X data vector *Y*: nObs x nSeries Y data matrix # apaTailDependence.R(Quantiles, X, Y) URL: https://www.andreassteiner.net/help/apataildependence.r/ ## Result Returns the right tail dependence, i.e. the conditional probability of joint occurrences above a given quantile. ## Syntax *Quantiles*: nQtls x 1 quantile vector *X*: nObs x 1 X data vector *Y*: nObs x nSeries Y data matrix # apaTailDependence.LR(Quantiles, X, Y) URL: https://www.andreassteiner.net/help/apataildependence.lr/ ## Result Returns the combined left and right tail dependence, i.e. the conditional probability of joint occurrences. For quantiles below 50%, the left tail dependence is reported, for quantiles above 50% the right tail dependence. ## Syntax *Quantiles*: nQtls x 1 quantile vector *X*: nObs x 1 X data vector *Y*: nObs x nSeries Y data matrix # apaTailRatio(Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apatailratio/ ## Result Returns the tail ratio, the size of the right tail of the return distribution relative to the left tail. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *ConfidenceLevel*: optional; confidence level between 0.5 and 1, e.g. 95% compares the 95th with the 5th percentile; default: 0.95 ## Algorithm Tail ratio = Q(ConfidenceLevel) / \|Q(1 − ConfidenceLevel)\|, with empirical percentiles Q interpolated as in Excel PERCENTILE.INC. ## Remarks The result is a 1 x c row vector with one value per column of Returns. Values above 1 indicate a larger right tail. \#N/A is returned if the lower percentile is not negative. # apaTemporal.Aggregation(Yhifreq, nHiFreqPeriodsPerLoFreqPeriod, StartIndex) URL: https://www.andreassteiner.net/help/apatemporal.aggregation/ ## Result Aggregates high frequency data into low frequency data by summing the high frequency observations of each low frequency period (additive aggregation). ## Syntax *Yhifreq*: r x 1 vector of high frequency data *nHiFreqPeriodsPerLoFreqPeriod*: number of high frequency periods in one low frequency period, e.g. 3 to aggregate monthly into quarterly data *StartIndex*: optional; index of the starting point on the high frequency scale; default: 1 ## Algorithm The result is calculated as C \* Yhifreq, where C is the additive temporal aggregation matrix (see apaTemporal.Aggregation.Matrix). ## Remarks StartIndex must not be larger than nHiFreqPeriodsPerLoFreqPeriod. # apaTemporal.Aggregation.Matrix(nLoFreqPeriods, nHiFreqPeriods, nHiFreqPeriodsPerLoFreqPeriod, StartIndex) URL: https://www.andreassteiner.net/help/apatemporal.aggregation.matrix/ ## Result Generates a temporal aggregation matrix of size nLoFreqPeriods x nHiFreqPeriods. Multiplying this matrix with a high frequency data vector results in the additively aggregated low frequency data. ## Syntax *nLoFreqPeriods*: number of low frequency periods *nHiFreqPeriods*: number of high frequency periods *nHiFreqPeriodsPerLoFreqPeriod*: number of high frequency periods in one low frequency period, e.g. 3 for monthly data within quarterly periods *StartIndex*: optional; index of the starting point on the high frequency scale; default: 1 ## Algorithm The aggregation matrix is the Kronecker product of an nLoFreqPeriods x nLoFreqPeriods identity matrix and a 1 x nHiFreqPeriodsPerLoFreqPeriod vector of ones. ## Remarks StartIndex must not be larger than nHiFreqPeriodsPerLoFreqPeriod. # apaTemporal.Aggregation.Matrix.First(nLoFreqPeriods, nHiFreqPeriods, nHiFreqPeriodsPerLoFreqPeriod, StartIndex) URL: https://www.andreassteiner.net/help/apatemporal.aggregation.matrix.first/ ## Result Generates a temporal aggregation matrix which selects the first high frequency observation of each low frequency period, i.e. “spaces out” observations. ## Syntax *nLoFreqPeriods*: number of low frequency periods *nHiFreqPeriods*: number of high frequency periods *nHiFreqPeriodsPerLoFreqPeriod*: number of high frequency periods in one low frequency period, e.g. 3 for monthly data within quarterly periods *StartIndex*: optional; index of the starting point on the high frequency scale; default: 1 ## Algorithm The matrix is constructed like the additive aggregation matrix (see apaTemporal.Aggregation.Matrix), except that only the first element of each 1 x nHiFreqPeriodsPerLoFreqPeriod block equals one, all other elements zero. ## Remarks StartIndex must not be larger than nHiFreqPeriodsPerLoFreqPeriod. # apaTemporal.Aggregation.Returns.Continuous(Returns, Frequency, IsStartAtLastOtherwiseFirst, IsExtrapolOtherwiseTrunc) URL: https://www.andreassteiner.net/help/apatemporal.aggregation.returns.continuous/ ## Result Legacy function to time-aggregate continuous returns. ## Syntax *Returns*: r x c matrix of continuous returns, each column containing a return time series *Frequency*: number of high frequency periods in one low frequency period *IsStartAtLastOtherwiseFirst*: TRUE to start aggregating at the end of the data, FALSE to start at the beginning *IsExtrapolOtherwiseTrunc*: TRUE to extrapolate incomplete periods, FALSE to truncate them # apaTemporal.Aggregation.Returns.Discrete(Returns, Frequency, IsStartAtLastOtherwiseFirst, IsExtrapolOtherwiseTrunc) URL: https://www.andreassteiner.net/help/apatemporal.aggregation.returns.discrete/ ## Result Legacy function to time-aggregate discrete returns. ## Syntax *Returns*: r x c matrix of discrete returns, each column containing a return time series *Frequency*: number of high frequency periods in one low frequency period *IsStartAtLastOtherwiseFirst*: TRUE to start aggregating at the end of the data, FALSE to start at the beginning *IsExtrapolOtherwiseTrunc*: TRUE to extrapolate incomplete periods, FALSE to truncate them # apaTemporal.Disaggregation.BrownianBridge(DataMatrix, nInserts, MuFactor, SigmaFactor) URL: https://www.andreassteiner.net/help/apatemporal.disaggregation.brownianbridge/ ## Result Temporally disaggregates data by Brownian bridge interpolation. ## Syntax *DataMatrix*: r x c data matrix *nInserts*: number of rows to insert between observations *MuFactor*: factor by which the drift rate is multiplied *SigmaFactor*: factor by which the volatility is multiplied ## Remarks The bridge volatility is the sample volatility (denominator n − 1). # apaTemporal.Disaggregation.ChowLin(Ylofreq, Xhifreq, nHiFreqPeriodsPerLoFreqPeriod, StartIndex) URL: https://www.andreassteiner.net/help/apatemporal.disaggregation.chowlin/ ## Result Temporally disaggregates low frequency data into high frequency data by modeling the dynamics with high frequency indicator variables and assuming an AR(1) process in the residuals (Chow/Lin method). ## Syntax *Ylofreq*: r x 1 vector of low frequency data *Xhifreq*: r x c matrix of high frequency indicator data *nHiFreqPeriodsPerLoFreqPeriod*: number of high frequency periods in one low frequency period, e.g. 3 to disaggregate quarterly into monthly data *StartIndex*: optional; index of the starting point on the high frequency scale; default: 1 ## Algorithm The indicator data is aggregated to the low frequency with the additive aggregation matrix C and the low frequency data is regressed on the aggregated indicators (OLS). The residual variance and first-order autocorrelation ρ are estimated from the regression residuals. ## Remarks StartIndex must not be larger than nHiFreqPeriodsPerLoFreqPeriod. # apaTemporal.Disaggregation.Diagonal(Ylofreq, Xhifreq, nHiFreqPeriodsPerLoFreqPeriod, StartIndex) URL: https://www.andreassteiner.net/help/apatemporal.disaggregation.diagonal/ ## Result Temporally disaggregates low frequency data into high frequency data by modeling the dynamics with high frequency indicator variables and assuming uncorrelated (diagonal) residuals. ## Syntax *Ylofreq*: r x 1 vector of low frequency data *Xhifreq*: r x c matrix of high frequency indicator data *nHiFreqPeriodsPerLoFreqPeriod*: number of high frequency periods in one low frequency period, e.g. 3 to disaggregate quarterly into monthly data *StartIndex*: optional; index of the starting point on the high frequency scale; default: 1 ## Algorithm The indicator data is aggregated to the low frequency with the additive aggregation matrix C and the low frequency data is regressed on the aggregated indicators (OLS). The residual variance σ² is estimated from the regression residuals. ## Remarks StartIndex must not be larger than nHiFreqPeriodsPerLoFreqPeriod. # apaTemporal.Disaggregation.Fernandez(Ylofreq, Xhifreq, nHiFreqPeriodsPerLoFreqPeriod, StartIndex) URL: https://www.andreassteiner.net/help/apatemporal.disaggregation.fernandez/ ## Result Temporally disaggregates low frequency data into high frequency data by modeling the dynamics with high frequency indicator variables and assuming a random walk in the residuals (Fernandez method). ## Syntax *Ylofreq*: r x 1 vector of low frequency data *Xhifreq*: r x c matrix of high frequency indicator data *nHiFreqPeriodsPerLoFreqPeriod*: number of high frequency periods in one low frequency period, e.g. 3 to disaggregate quarterly into monthly data *StartIndex*: optional; index of the starting point on the high frequency scale; default: 1 ## Algorithm The indicator data is aggregated to the low frequency with the additive aggregation matrix C and the low frequency data is regressed on the aggregated indicators (OLS). The residual variance σ² is estimated from the regression residuals. ## Remarks StartIndex must not be larger than nHiFreqPeriodsPerLoFreqPeriod. # apaTemporal.Disaggregation.Litterman(Ylofreq, Xhifreq, nHiFreqPeriodsPerLoFreqPeriod, StartIndex) URL: https://www.andreassteiner.net/help/apatemporal.disaggregation.litterman/ ## Result Temporally disaggregates low frequency data into high frequency data by modeling the dynamics with high frequency indicator variables and assuming ARIMA(1,1,0) residuals (Litterman method). ## Syntax *Ylofreq*: r x 1 vector of low frequency data *Xhifreq*: r x c matrix of high frequency indicator data *nHiFreqPeriodsPerLoFreqPeriod*: number of high frequency periods in one low frequency period, e.g. 3 to disaggregate quarterly into monthly data *StartIndex*: optional; index of the starting point on the high frequency scale; default: 1 ## Algorithm The indicator data is aggregated to the low frequency with the additive aggregation matrix C and the low frequency data is regressed on the aggregated indicators (OLS). The residual variance σ² and first-order autocorrelation ρ are estimated from the regression residuals. ## Remarks StartIndex must not be larger than nHiFreqPeriodsPerLoFreqPeriod. # apaTemporal.kFold.Data(Data, k, FoldIndex, FoldingType, IsInSampleOtherwiseOutOfSample) URL: https://www.andreassteiner.net/help/apatemporal.kfold.data/ ## Result Returns a particular data set when k-folding data. ## Syntax *Data*: rows x cols matrix of data *k*: number of folds performed on the data *FoldIndex*: index of the folded data. Ranges from 1 to the maximum number of folds possible. *FoldingType*: way the data is folded: 1 = standard k-fold, 2 = time series rolling k-fold, 3 = time series cumulative k-fold *IsInSampleOtherwiseOutOfSample*: optional; TRUE to return the in-sample data set, FALSE to return the out-of-sample data set; default: TRUE # apaTemporal.kFold.nRemainders(nObs, nRemainders) URL: https://www.andreassteiner.net/help/apatemporal.kfold.nremainders/ ## Result Returns the k values resulting in a given number of remainder observations. Useful for finding k values with a small number of remainders. ## Syntax *nObs*: number of observations *nRemainders*: number of remainders targeted ## Remarks The result is independent of the folding type. # apaTemporal.kFold.Sizes(nObs, k, FoldingType) URL: https://www.andreassteiner.net/help/apatemporal.kfold.sizes/ ## Result Returns the sizes of the various data sets when k-folding data. ## Syntax *nObs*: number of observations *k*: number of folds performed on the data *FoldingType*: optional; way the data is folded: 1 = standard k-fold, 2 = time series rolling k-fold, 3 = time series cumulative k-fold; default: 1 ## Algorithm Format of the output… 1\) Number of folds 2\) n per fold 3\) n in training 4\) n in validation 5\) remainder observations # apaTemporal.Window.Data(Data, nInSample, nOutOfSample, nSteps, nShifts, IsCumulativeInSample, IsCumulativeOutOfSample, WindowIndex, IsInSampleOtherwiseOutOfSample) URL: https://www.andreassteiner.net/help/apatemporal.window.data/ ## Result Returns a particular data set when rolling windows through data. ## Syntax *Data*: rows x cols matrix of data *nInSample*: number of obs in the in-sample window *nOutOfSample*: number of obs in the out-of-sample window *nSteps*: number of steps to move the windows *nShifts*: number of +/- shifts of the beginning of the out-of-sample window *IsCumulativeInSample*: TRUE to always start the in-sample data set at the first observation, i.e. to accumulate observations *IsCumulativeOutOfSample*: TRUE to always start the out-of-sample data set at the first observation *WindowIndex*: index of the dataset. Ranges from 1 to the maximum number of datasets possible. *IsInSampleOtherwiseOutOfSample*: optional; TRUE to return the in-sample data set, FALSE to return the out-of-sample data set; default: TRUE ## Remarks nShifts can be negative. WindowIndex = 0 returns the last window. nOutOfSample = 0 results in in-sample window data only, ignoring the out-of-sample window. # apaTemporal.Window.Sizes(nObs, nInSamples, nOutOfSamples, nSteps, nShifts) URL: https://www.andreassteiner.net/help/apatemporal.window.sizes/ ## Result Returns various data set sizes when rolling windows: 1) number of data sets, 2) number of remainder observations. ## Syntax *nObs*: number of observations in the original data *nInSamples*: rows x 1 vector with numbers of obs in the in-sample window *nOutOfSamples*: rows x 1 vector with number of obs in the out-of-sample window *nSteps*: number of steps to move the windows *nShifts*: number of +/- shifts of the beginning of the out-of-sample window ## Remarks nShifts can be negative. # apaTemporal.Window.TimeIdx.All(Data, nInSample, nOutOfSample, nSteps, nShifts, IsCumulativeInSample, IsCumulativeOutOfSample, WindowIndex, IsInSampleOtherwiseOutOfSample) URL: https://www.andreassteiner.net/help/apatemporal.window.timeidx.all/ ## Result Returns all time indices (row numbers) of a particular rolling window, either of the in-sample or of the out-of-sample window. ## Syntax *Data*: rows x cols matrix of data *nInSample*: number of obs in the in-sample window *nOutOfSample*: number of obs in the out-of-sample window *nSteps*: number of steps to move the windows *nShifts*: number of +/- shifts of the beginning of the out-of-sample window *IsCumulativeInSample*: TRUE to always start the in-sample data set at the first observation, i.e. to accumulate observations *IsCumulativeOutOfSample*: TRUE to always start the out-of-sample data set at the first observation *WindowIndex*: index of the dataset. Ranges from 1 to the maximum number of datasets possible. *IsInSampleOtherwiseOutOfSample*: optional; TRUE to return the in-sample time indices, FALSE to return the out-of-sample time indices; default: TRUE ## Algorithm The windows are defined as in apaTemporal.Window.Data. The time indices of the window with the given WindowIndex are returned. ## Remarks nShifts can be negative. # apaTemporal.Window.TimeIdx.First(Data, nInSample, nOutOfSample, nSteps, nShifts, IsCumulativeInSample, IsCumulativeOutOfSample, WindowIndex, IsInSampleOtherwiseOutOfSample) URL: https://www.andreassteiner.net/help/apatemporal.window.timeidx.first/ ## Result Returns the first time index (row number) of a particular rolling window, either of the in-sample or of the out-of-sample window. ## Syntax *Data*: rows x cols matrix of data *nInSample*: number of obs in the in-sample window *nOutOfSample*: number of obs in the out-of-sample window *nSteps*: number of steps to move the windows *nShifts*: number of +/- shifts of the beginning of the out-of-sample window *IsCumulativeInSample*: TRUE to always start the in-sample data set at the first observation, i.e. to accumulate observations *IsCumulativeOutOfSample*: TRUE to always start the out-of-sample data set at the first observation *WindowIndex*: index of the dataset. Ranges from 1 to the maximum number of datasets possible. *IsInSampleOtherwiseOutOfSample*: optional; TRUE to return the in-sample time index, FALSE to return the out-of-sample time index; default: TRUE ## Algorithm The windows are defined as in apaTemporal.Window.Data. The first time index of the window with the given WindowIndex is returned. ## Remarks nShifts can be negative. # apaTemporal.Window.TimeIdx.Last(Data, nInSample, nOutOfSample, nSteps, nShifts, IsCumulativeInSample, IsCumulativeOutOfSample, WindowIndex, IsInSampleOtherwiseOutOfSample) URL: https://www.andreassteiner.net/help/apatemporal.window.timeidx.last/ ## Result Returns the last time index (row number) of a particular rolling window, either of the in-sample or of the out-of-sample window. ## Syntax *Data*: rows x cols matrix of data *nInSample*: number of obs in the in-sample window *nOutOfSample*: number of obs in the out-of-sample window *nSteps*: number of steps to move the windows *nShifts*: number of +/- shifts of the beginning of the out-of-sample window *IsCumulativeInSample*: TRUE to always start the in-sample data set at the first observation, i.e. to accumulate observations *IsCumulativeOutOfSample*: TRUE to always start the out-of-sample data set at the first observation *WindowIndex*: index of the dataset. Ranges from 1 to the maximum number of datasets possible. *IsInSampleOtherwiseOutOfSample*: optional; TRUE to return the in-sample time index, FALSE to return the out-of-sample time index; default: TRUE ## Algorithm The windows are defined as in apaTemporal.Window.Data. The last time index of the window with the given WindowIndex is returned. ## Remarks nShifts can be negative. # apaTimePoints.FromDates(Dates, StartDate, EndDate) URL: https://www.andreassteiner.net/help/apatimepoints.fromdates/ ## Result Calculates points in time, i.e. the time that has passed from the beginning of StartDate to each date, as a fraction of the period from the beginning of StartDate to the end of EndDate (Act/Act). ## Syntax *Dates*: r x 1 date vector *StartDate*: start calendar date *EndDate*: end calendar date ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image148.svg) ## Remarks The time period begins at the beginning of StartDate and lasts until the end of the day of EndDate. Uses the actual calendar days, making no day count assumption. # apaTimePoints.Rounded(nPeriods, TimePoints) URL: https://www.andreassteiner.net/help/apatimepoints.rounded/ ## Result Rounds a vector of time points to the nearest multiple of 1/nPeriods, i.e. such that the overall time period is divided into nPeriods subperiods of equal length. ## Syntax *nPeriods*: number of subperiods of equal length per year *TimePoints*: r x 1 vector of time points in years # apaTcdf(t, k) URL: https://www.andreassteiner.net/help/apatcdf/ ## Result Cumulative distribution function of Student’s t distribution. ## Syntax *t*: value at which to evaluate the function *k*: degrees of freedom # apaTinv(p, k) URL: https://www.andreassteiner.net/help/apatinv/ ## Result Inverse of the cumulative distribution function of Student’s t distribution. ## Syntax *p*: probability *k*: degrees of freedom # apaTpdf(t, k) URL: https://www.andreassteiner.net/help/apatpdf/ ## Result Probability density function of Student’s t distribution. ## Syntax *t*: value at which to evaluate the function *k*: degrees of freedom # apaTsim(nSims, Degrees, Mean, StandardDeviation) URL: https://www.andreassteiner.net/help/apatsim/ ## Result Returns a matrix of random numbers drawn from Student’s t distributions with given location and scale parameters. ## Syntax *nSims*: number of observations to simulate *Degrees*: degrees of freedom *Mean*: 1 x c vector of location parameters *StandardDeviation*: 1 x c vector of scale parameters ## Remarks The function is volatile, i.e. it is recalculated whenever a change occurs, even if not related to the function’s output. The function is also recalculated when pressing F9. # apaTsim.Multivariate(nSims, e, covars, df) URL: https://www.andreassteiner.net/help/apatsim.multivariate/ ## Result Returns random drawings from a multivariate Student’s t distribution. ## Syntax *nSims*: number of observations to simulate *e*: 1 x n vector containing the location parameters *covars*: n x n covariance matrix *df*: degrees of freedom. The larger this value, the more the resulting distribution will resemble a normal distribution. Small values will have fat tails. ## Remarks All marginal distributions are assumed to have the same degrees of freedom. # apaTree.Layout(Edges, IsWeighted, midpointType, IsAlignedLeaves) URL: https://www.andreassteiner.net/help/apatree.layout/ ## Result Calculates a tree layout from an edge list. Returns one row per node with the x and y coordinates, the nodes sorted by node index. ## Syntax *Edges*: edge list; the first column contains the parent node index, the second column the child node index, the third column the edge weight *IsWeighted*: TRUE to use the edge weights as vertical distances, FALSE to use unit distances *midpointType*: horizontal positioning of parent nodes: 0 = midpoint between leftmost and rightmost child, 1 = arithmetic mean of the immediate children, 2 = above the leftmost child, 3 = above the rightmost child, 4 = 75% of the distance from the leftmost to the rightmost child *IsAlignedLeaves*: TRUE to align all leaves at the maximum root-to-leaf depth, FALSE to place leaves at their own depth ## Algorithm The root node (the node without parent) is identified. ## Remarks The edge list must define a tree, i.e. a connected graph with a single root and without cycles. # apaTradeProfile.CDaR(Weights, Returns, ConfidenceLevel, StepSize, nSteps, IsTraditional, IsSmooth) URL: https://www.andreassteiner.net/help/apatradeprofile.cdar/ ## Result Calculates the so-called “trade profile” of portfolio conditional drawdown at risk (CDaR), i.e. how +/- changes in the constituent exposures affect the portfolio CDaR. ## Syntax *Weights*: 1 x n vector of constituent exposures *Returns*: m x n matrix of constituent returns (m = nObs, n = nAssets) *ConfidenceLevel*: confidence level for CDaR, e.g. 95% *StepSize*: size of exposure changes *nSteps*: number of exposure changes *IsTraditional*: TRUE to set the results of trades resulting in short (\< 0) or leveraged (\> 1) constituent exposures to \#N/A *IsSmooth*: TRUE to calculate smooth CDaR (tail \<= DaR), FALSE for the usual calculation (tail \< DaR) ## Remarks For more information on the IsSmooth parameter, see apaCDaR.Empirical. # apaTradeProfile.CVaR(Weights, Returns, ConfidenceLevel, StepSize, nSteps, IsTraditional, IsSmooth) URL: https://www.andreassteiner.net/help/apatradeprofile.cvar/ ## Result Calculates the so-called “trade profile” of portfolio conditional value at risk (CVaR), i.e. how +/- changes in the constituent exposures affect the portfolio CVaR. ## Syntax *Weights*: 1 x n vector of constituent exposures *Returns*: m x n matrix of constituent returns (m = nObs, n = nAssets) *ConfidenceLevel*: confidence level for CVaR, e.g. 95% *StepSize*: size of exposure changes *nSteps*: number of exposure changes *IsTraditional*: TRUE to set the results of trades resulting in short (\< 0) or leveraged (\> 1) constituent exposures to \#N/A *IsSmooth*: TRUE to calculate smooth CVaR (tail \<= VaR), FALSE for the usual calculation (tail \< VaR) ## Remarks For more information on the IsSmooth parameter, see apaCVaR.Empirical. # apaTradeProfile.DaR(Weights, Returns, ConfidenceLevel, StepSize, nSteps, IsTraditional) URL: https://www.andreassteiner.net/help/apatradeprofile.dar/ ## Result Calculates the so-called “trade profile” of portfolio drawdown at risk (DaR), i.e. how +/- changes in the constituent exposures affect the portfolio DaR. ## Syntax *Weights*: 1 x n vector of constituent exposures *Returns*: m x n matrix of constituent returns (m = nObs, n = nAssets) *ConfidenceLevel*: confidence level for DaR, e.g. 95% *StepSize*: size of exposure changes *nSteps*: number of exposure changes *IsTraditional*: TRUE to set the results of trades resulting in short (\< 0) or leveraged (\> 1) constituent exposures to \#N/A # apaTradeProfile.Kurtosis(Weights, Returns, StepSize, nSteps, IsTraditional) URL: https://www.andreassteiner.net/help/apatradeprofile.kurtosis/ ## Result Calculates the so-called “trade profile” of portfolio kurtosis, i.e. how +/- changes in the constituent exposures affect the portfolio kurtosis. ## Syntax *Weights*: 1 x n vector of constituent exposures *Returns*: m x n matrix of constituent returns (m = nObs, n = nAssets) *StepSize*: size of exposure changes *nSteps*: number of exposure changes *IsTraditional*: TRUE to set the results of trades resulting in short (\< 0) or leveraged (\> 1) constituent exposures to \#N/A ## Remarks Population kurtosis (not excess) from population covariances and cokurtosis (denominator n). # apaTradeProfile.SharpeRatio(Weights, ExpectedReturns, Covariances, StepSize, nSteps, IsTraditional) URL: https://www.andreassteiner.net/help/apatradeprofile.sharperatio/ ## Result Calculates the so-called “trade profile” of the portfolio Sharpe ratio, i.e. how +/- changes in the constituent exposures affect the portfolio Sharpe ratio. ## Syntax *Weights*: 1 x n vector of constituent exposures *ExpectedReturns*: 1 x n vector of constituent expected returns *Covariances*: n x n matrix of constituent covariances *StepSize*: size of exposure changes *nSteps*: number of exposure changes *IsTraditional*: TRUE to set the results of trades resulting in short (\< 0) or leveraged (\> 1) constituent exposures to \#N/A # apaTradeProfile.Skewness(Weights, Returns, StepSize, nSteps, IsTraditional) URL: https://www.andreassteiner.net/help/apatradeprofile.skewness/ ## Result Calculates the so-called “trade profile” of portfolio skewness, i.e. how +/- changes in the constituent exposures affect the portfolio skewness. ## Syntax *Weights*: 1 x n vector of constituent exposures *Returns*: m x n matrix of constituent returns (m = nObs, n = nAssets) *StepSize*: size of exposure changes *nSteps*: number of exposure changes *IsTraditional*: TRUE to set the results of trades resulting in short (\< 0) or leveraged (\> 1) constituent exposures to \#N/A ## Remarks Population skewness from population covariances and coskewness (denominator n). # apaTradeProfile.VaR(Weights, Returns, ConfidenceLevel, StepSize, nSteps, IsTraditional) URL: https://www.andreassteiner.net/help/apatradeprofile.var/ ## Result Calculates the so-called “trade profile” of portfolio value at risk (VaR), i.e. how +/- changes in the constituent exposures affect the portfolio VaR. ## Syntax *Weights*: 1 x n vector of constituent exposures *Returns*: m x n matrix of constituent returns (m = nObs, n = nAssets) *ConfidenceLevel*: confidence level for VaR, e.g. 95% *StepSize*: size of exposure changes *nSteps*: number of exposure changes *IsTraditional*: TRUE to set the results of trades resulting in short (\< 0) or leveraged (\> 1) constituent exposures to \#N/A # apaTradeProfile.Volatility(Weights, Covariances, StepSize, nSteps, IsTraditional) URL: https://www.andreassteiner.net/help/apatradeprofile.volatility/ ## Result Calculates the so-called “trade profile” of portfolio volatility, i.e. how +/- changes in the constituent exposures affect the portfolio volatility. ## Syntax *Weights*: 1 x n vector of constituent exposures *Covariances*: n x n matrix of constituent covariances *StepSize*: size of exposure changes *nSteps*: number of exposure changes *IsTraditional*: TRUE to set the results of trades resulting in short (\< 0) or leveraged (\> 1) constituent exposures to \#N/A # apaTriangPdf(X, LowerValue, UpperValue, MiddleValue) URL: https://www.andreassteiner.net/help/apatriangpdf/ ## Result Probability density function of the triangular distribution. ## Syntax *X*: value at which to evaluate the function *LowerValue*: number marking the lower value *UpperValue*: number marking the upper value *MiddleValue*: number marking the middle value (mode) # apaTriangCdf(X, LowerValue, UpperValue, MiddleValue) URL: https://www.andreassteiner.net/help/apatriangcdf/ ## Result Cumulative distribution function of the triangular distribution. ## Syntax *X*: value at which to evaluate the function *LowerValue*: number marking the lower value *UpperValue*: number marking the upper value *MiddleValue*: number marking the middle value (mode) # apaTriangInv(prob, LowerValue, UpperValue, MiddleValue) URL: https://www.andreassteiner.net/help/apatrianginv/ ## Result Inverse cumulative distribution function of the triangular distribution. ## Syntax *prob*: probability *LowerValue*: number marking the lower value *UpperValue*: number marking the upper value *MiddleValue*: number marking the middle value (mode) # apaTriangMom(LowerValue, UpperValue, MiddleValue) URL: https://www.andreassteiner.net/help/apatriangmom/ ## Result Returns the first four moments of a triangular distribution: mean, variance, skewness and kurtosis (not excess kurtosis). ## Syntax *LowerValue*: number marking the lower value *UpperValue*: number marking the upper value *MiddleValue*: number marking the middle value (mode) # apaTriangRnd(LowerValue, UpperValue, MiddleValue) URL: https://www.andreassteiner.net/help/apatriangrnd/ ## Result Returns a random number drawn from a triangular distribution. ## Syntax *LowerValue*: number marking the lower value *UpperValue*: number marking the upper value *MiddleValue*: number marking the middle value (mode) # apaTriangSim(LowerValue, UpperValue, MiddleValue, n) URL: https://www.andreassteiner.net/help/apatriangsim/ ## Result Returns a vector of random numbers drawn from a triangular distribution. ## Syntax *LowerValue*: number marking the lower value *UpperValue*: number marking the upper value *MiddleValue*: number marking the middle value (mode) *n*: number of observations to simulate # apaTrackingError(PortfolioReturns, BenchmarkReturns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apatrackingerror/ ## Result Returns the tracking error of a portfolio, calculated from active returns. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *IsSampleOtherwisePopulation*: optional; TRUE for sample tracking error (division by n-1), FALSE for population tracking error (division by n); default: TRUE ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image149.svg) ## Remarks The tracking error is the sample (denominator n − 1) or population (denominator n) standard deviation of active returns, set by IsSampleOtherwisePopulation; default: sample. # apaTrendModels.Fourier(series, harmonicCount, includeLinearTrend, nAhead) URL: https://www.andreassteiner.net/help/apatrendmodels.fourier/ ## Result Fits a Fourier harmonic trend regression with intercept to a single series and returns the fitted values and coefficients. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *harmonicCount*: number of sine/cosine harmonic pairs to include *includeLinearTrend*: TRUE to include a linear time trend in addition to the Fourier terms, FALSE otherwise. Default value: FALSE *nAhead*: optional number of forecast steps appended after the last observation. Default value: 0 ## Algorithm The series is regressed by ordinary least squares on a constant, optionally a linear time trend t, and the terms cos(2πkt/P) and sin(2πkt/P) for k = 1, …, harmonicCount. ## Remarks The result contains a header row and one row per observation with the columns Position (1-based), FittedValue, Period, HarmonicCount, IncludeLinearTrend, R2, RSS and the coefficients Beta0, Beta1, … . If nAhead is greater than 0, nAhead further rows with the Positions r + 1, …, r + nAhead follow, where r is the number of observations. Their FittedValue is the forecast obtained by evaluating the fitted regression at the times t = r, …, r + nAhead − 1; the other columns repeat the fit statistics and coefficients. Since the period P equals the number of observations, the harmonic terms of the forecast repeat the pattern from the start of the series, and only the linear trend, if included, continues the level. # apaTrendModels.NeuralNetwork(series, nLags, nAhead, hidden1, hidden2, learningRate, epochs, batchSize, l2Alpha, validationFraction, patience, oneBased) URL: https://www.andreassteiner.net/help/apatrendmodels.neuralnetwork/ ## Result Fits a neural network forecast model with lagged inputs, trained with the Adam optimizer and early stopping, and calculates a recursive multi-step forecast. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *nLags*: number of lagged observations used as inputs *nAhead*: number of recursive forecast steps *hidden1*: size of the first hidden layer. Default value: 16 *hidden2*: size of the second hidden layer, 0 to omit the layer. Default value: 8 *learningRate*: learning rate of the Adam optimizer. Default value: 0.001 *epochs*: maximum number of training epochs. Default value: 1000 *batchSize*: mini-batch size. Default value: 32 *l2Alpha*: L2 regularization strength. Default value: 0.0001 *validationFraction*: fraction of the observations reserved for validation, between 0 and 0.5. Default value: 0.1 *patience*: number of epochs without improvement of the validation loss before training is stopped. Default value: 30 *oneBased*: 1 for 1-based row numbering, 0 for 0-based row numbering ## Algorithm The input matrix is set up from the nLags lagged observations, the target is the current observation. The last validationFraction of the rows is held out for validation. Inputs and target are standardized with the means and standard deviations of the training rows. The network has ReLU hidden layers and a linear output and is trained on the mean squared error plus the L2 penalty with the Adam optimizer in mini-batches of size batchSize (fixed random seed 42). After each epoch the mean squared error on the validation rows is computed; training stops after patience epochs without improvement or after epochs epochs, and the weights with the lowest validation loss are kept. The forecast is calculated recursively: each forecast is appended to the series and used as a lagged input for the next step. ## Remarks The result contains a header row followed by the columns Position, FittedValue, ForecastValue, BestValidationLoss, EpochsCompleted, LagCount and HiddenLayers. The first nLags fitted values are not available and are shown as \#N/A, as are the ForecastValue cells beyond row nAhead. The ForecastValue in row j is the j-step-ahead forecast. The loss is the mean squared error of the standardized target. If validationFraction is 0, no rows are held out, the weights with the lowest training loss are kept, and the fourth column is labelled TrainingLoss. Leading and trailing non-numeric or empty cells of series (for example a header) are ignored. A non-numeric or empty cell within the series returns an error message, since removing it would shift the lags. # apaTrendModels.Piecewise(series, maxBreakpoints, minSegmentLength, maxIterations, nOutOfSample, useLinearModel, nAhead) URL: https://www.andreassteiner.net/help/apatrendmodels.piecewise/ ## Result Fits a piecewise linear or quadratic trend model to a single series, selects the number of breakpoints by a knee rule and returns the fitted values and breakpoint information. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *maxBreakpoints*: maximum number of breakpoints to consider. Default value: 10 *minSegmentLength*: minimum number of observations between the series start, the breakpoints and the series end. Default value: 6 *maxIterations*: maximum number of iterations of the breakpoint search. Default value: 200 *nOutOfSample*: number of final observations held out from the fit. Default value: 4 *useLinearModel*: TRUE for a piecewise linear model, FALSE for a piecewise quadratic model. Default value: FALSE *nAhead*: optional number of forecast steps appended after the last observation. Default value: 0 ## Algorithm The trend is regressed on time t = 0, 1, …, using the in-sample observations only, i.e. all observations except the last nOutOfSample. ## Remarks The result contains a header row and one row per observation with the columns Position (1-based), ObservedInSampleFlag (1 for in-sample, 0 for out-of-sample), FittedValue, SelectedBreakCount, BreakPoints (1 at a breakpoint, 0 otherwise), R2 and ModelType. If nAhead is greater than 0, nAhead further rows with the Positions r + 1, …, r + nAhead follow, where r is the number of observations. Their FittedValue is the forecast obtained by continuing the last segment of the selected model at the times t = r, …, r + nAhead − 1, their ObservedInSampleFlag and BreakPoints are 0, and the other columns repeat those of the fit. # apaTrendModels.Polynomial(series, degree, nAhead) URL: https://www.andreassteiner.net/help/apatrendmodels.polynomial/ ## Result Fits a polynomial time trend regression with intercept to a single series and returns the fitted values and coefficients. ## Syntax *series*: r x 1 or 1 x r data vector containing a time series *degree*: degree of the polynomial, e.g. 1 = linear, 2 = quadratic, 3 = cubic *nAhead*: optional number of forecast steps appended after the last observation. Default value: 0 ## Algorithm The series is regressed by ordinary least squares on a constant and the powers t, t², …, t^degree of time t. ## Remarks The result contains a header row and one row per observation with the columns Position (1-based), FittedValue, Degree, R2, RSS and the coefficients Beta0 (intercept), Beta1, … . If nAhead is greater than 0, nAhead further rows with the Positions r + 1, …, r + nAhead follow, where r is the number of observations. Their FittedValue is the forecast obtained by evaluating the fitted polynomial at the times t = r, …, r + nAhead − 1; the other columns repeat the fit statistics and coefficients. Polynomial forecasts can move away from the data quickly, especially for higher degrees. # apaTreynorMazui.Alpha(PortfolioReturns, BenchmarkReturns, RiskfreeReturns) URL: https://www.andreassteiner.net/help/apatreynormazui.alpha/ ## Result Returns the alpha of a portfolio based on the Treynor/Mazuy quadratic one-factor (market-timing) model. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *RiskfreeReturns*: r x 1 vector of riskfree returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image150.svg) # apaTreynorMazui.Gamma(PortfolioReturns, BenchmarkReturns, RiskfreeReturns) URL: https://www.andreassteiner.net/help/apatreynormazui.gamma/ ## Result Returns the gamma of a portfolio, a market timing indicator, based on the Treynor/Mazuy quadratic one-factor model. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *RiskfreeReturns*: r x 1 vector of riskfree returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image151.svg) # apaTreynorRatio(PortfolioReturns, BenchmarkReturns, RiskfreeReturns) URL: https://www.andreassteiner.net/help/apatreynorratio/ ## Result Returns the Treynor ratio, a risk-adjusted performance measure. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *BenchmarkReturns*: r x 1 vector of benchmark returns *RiskfreeReturns*: r x 1 vector of riskfree returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image152.svg) ## Remarks Ratio of sample covariance to sample variance (denominator n − 1); population moments give the same beta. # apaTurbulence(Returns, DoShowContributions, DoShowAbsContrOtherwisePercent) URL: https://www.andreassteiner.net/help/apaturbulence/ ## Result Calculates the financial turbulence indicator (Kritzman/Li), i.e. the Mahalanobis distance of the returns from their mean, for each observation. Optionally returns the contributions of the constituents to the indicator instead, either absolute or relative to the indicator. ## Syntax *Returns*: nObs x nAssets matrix of returns, each column containing a time series *DoShowContributions*: optional; TRUE: nObs x nAssets matrix with the contribution of each constituent to the turbulence indicator of each observation; FALSE (default): nObs x 1 vector with the turbulence indicator *DoShowAbsContrOtherwisePercent*: optional, used if DoShowContributions is TRUE; TRUE (default): absolute contributions, each row sums to the turbulence indicator of the observation; FALSE: relative contributions, i.e. the absolute contributions divided by the turbulence indicator of the same observation, each row sums to 1 ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image153.svg) With r as asset returns, μ as average asset returns, Σ as covariance matrix and n as number of assets. Contributions (DoShowContributions = TRUE): with u(t) = (r(t) - μ)' Σ^-1, the contribution of asset k is c(t,k) = u(t,k) x (r(t,k) - μ(k)) / n. The contributions of each observation sum to its turbulence indicator. Relative contributions (DoShowAbsContrOtherwisePercent = FALSE): c(t,k) / Turbulence(t), which sum to 1; observations with a turbulence indicator of 0 return 0. ## Remarks Kinlaw/Turkington(2013): “Correlation Surprise”, Journal of Asset Management: “This statistic, which can be thought of as a multivariate z-score, measures the statistical unusualness of a contemporaneous cross-section of asset returns relative to its historical distribution. It captures the extent to which the risk-adjusted magnitudes of the returns differ from their historical means as well as the extent to which their interaction is inconsistent with the historical correlation matrix.” Contributions can be negative: a constituent whose deviation from its mean is consistent with its correlations to the other constituents reduces the indicator, and relative contributions can be negative or exceed 1. Plotting the last row of the contributions as a bar chart shows which constituents drive the most recent turbulence reading. Relative contributions are comparable across observations; averaging them over turbulent observations shows which constituents drive turbulence (compare with 1/n). Uses population covariances (denominator n). # apaTurnover(OldWeights, NewWeights) URL: https://www.andreassteiner.net/help/apaturnover/ ## Result Calculates the turnover between two allocations. ## Syntax *OldWeights*: 1 x n vector of constituent weights before rebalancing *NewWeights*: 1 x n vector of constituent weights after rebalancing ## Algorithm Formula for turnover based on percentage exposures (- represents sales, + represents purchases)… ![Formula](https://www.andreassteiner.net/help/assets/eq/image154.svg) # apaUlcerIndex(Returns) URL: https://www.andreassteiner.net/help/apaulcerindex/ ## Result Calculates the Ulcer Index, a risk measure, i.e. the root mean square of the underwater returns. ## Syntax *Returns*: r x 1 vector of returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image155.svg) # apaUlcerPerformanceIndex(PortfolioReturns, RiskfreeReturns) URL: https://www.andreassteiner.net/help/apaulcerperformanceindex/ ## Result Calculates the Ulcer Performance Index (Martin ratio), a risk-adjusted performance measure. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *RiskfreeReturns*: r x 1 vector of riskfree returns ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image156.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image155.svg) # apaUpsidePotentialRatio(PortfolioReturns, Threshold) URL: https://www.andreassteiner.net/help/apaupsidepotentialratio/ ## Result Returns the upside potential ratio, a risk-adjusted performance measure. ## Syntax *PortfolioReturns*: r x 1 vector of portfolio returns *Threshold*: return threshold ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image157.svg) ## Remarks Partial moments divide by the total number of observations n (population-type). # apaUPM(Returns, Threshold, Degree) URL: https://www.andreassteiner.net/help/apaupm/ ## Result Returns the upper partial moment (UPM) of a return time series. ## Syntax *Returns*: r x 1 vector of returns *Threshold*: return threshold *Degree*: degree of the partial moment ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image158.svg) ## Remarks Partial moments divide by the total number of observations n (population-type). # apaUsim(n) URL: https://www.andreassteiner.net/help/apausim/ ## Result Returns a vector of random drawings from a uniform distribution between 0 and 1. ## Syntax *n*: number of observations to simulate ## Algorithm A 32-bit version of the Multiply-With-Carry random number generator by George Marsaglia is used. ## Remarks More efficient than Excel’s RAND(). # apaUsim.Correlated(nSims, Correlations) URL: https://www.andreassteiner.net/help/apausim.correlated/ ## Result Simulates correlated uniformly distributed random variables (Gaussian copula). ## Syntax *nSims*: number of observations to simulate *Correlations*: c x c rank correlation matrix # apaVaR.EVT.Hill(Returns, m, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apavar.evt.hill/ ## Result Calculates value at risk (VaR) based on extreme value theory, using the Hill tail index estimate. ## Syntax *Returns*: r x 1 vector of returns *m*: number of tail observations (largest losses) to use *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm The tail parameter of the generalized Pareto distribution is estimated with the least squares Hill estimator. # apaVaR.EVT.GP(Returns, Threshold, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apavar.evt.gp/ ## Result Calculates value at risk (VaR) based on extreme value theory, from a generalized Pareto distribution fitted to the losses beyond the threshold. ## Syntax *Returns*: r x 1 vector of returns *Threshold*: return threshold defining the tail *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image159.svg) S and K are the scale and shape parameters of the fitted generalized Pareto distribution. # apaVaR.Empirical(Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apavar.empirical/ ## Result Returns the empirical value at risk (VaR) of each return series. ## Syntax *Returns*: r x c matrix of returns. Each column represents a different time series. *ConfidenceLevel*: confidence level, e.g. 95%. # apaVaR.Modified(Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apavar.modified/ ## Result Returns the modified value at risk (VaR), an approximate parametric VaR figure based on the Cornish-Fisher expansion. ## Syntax *Returns*: r x 1 vector of return data *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm ``` math \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ ModVaR_{\alpha} = \bar{r} + \sigma \cdot \left( q_{\alpha} + \frac{1}{6}\left( q_{\alpha}^{2} - 1 \right) \cdot S + \frac{1}{24}\left( q_{\alpha}^{3} - 3 \cdot q_{\alpha} \right) \cdot K - \frac{1}{36}\left( 2 \cdot q_{\alpha}^{3} - 5 \cdot q_{\alpha} \right) \cdot S^{2} \right) ``` qα is the α-quantile of the standard normal distribution, α = 1 − *ConfidenceLevel*, S the skewness and K the excess kurtosis (population moments). Losses are reported as negative numbers. # apaVaR.Modified.FromConstituents(Weights, Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apavar.modified.fromconstituents/ ## Result Returns the parametric modified value at risk (VaR) of a portfolio, calculated from constituent weights and returns. ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks Population moments of the portfolio returns are used. Losses are reported as negative numbers. # apaVaR.Modified.Moments(Mu, Sigma, Skewness, Kurtosis, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apavar.modified.moments/ ## Result Returns the modified value at risk (VaR), an approximate parametric VaR figure based on the Cornish-Fisher expansion, calculated from moments. ## Syntax *Mu*: location parameter (first moment) *Sigma*: volatility (second moment) *Skewness*: skewness (third moment) *Kurtosis*: excess kurtosis, i.e. kurtosis minus three (zero for a normal distribution) *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks Losses are reported as negative numbers. # apaVaR.Modified.Attribution(AssetWeights, AssetReturns, ConfidenceLevel, DoShowTotals) URL: https://www.andreassteiner.net/help/apavar.modified.attribution/ ## Result Performs a tail risk attribution of modified value at risk (VaR) to the portfolio constituents. ## Syntax *AssetWeights*: 1 x n vector of constituent weights *AssetReturns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. *DoShowTotals*: TRUE to show subtotals (contribution from normal VaR, contribution from non-normal effects, grand total), FALSE to show the effects only ## Algorithm See our research note “Tail Risk Attribution”, Aug 2011, for details. ## Remarks Uses population covariances, coskewness and cokurtosis (denominator n). # apaVaR.NIG(Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apavar.nig/ ## Result Returns the parametric normal inverse Gaussian (NIG) value at risk (VaR). ## Syntax *Returns*: r x 1 vector of returns *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks The NIG parameters are estimated by moment matching. Note that the NIG distribution is only defined when the kurtosis (not excess kurtosis) exceeds 3 + (5/3)·S², where S is the skewness. The NIG parameters match the sample mean, sample variance (n − 1), sample skewness and sample excess kurtosis. # apaVaR.Normal(Returns, ConfidenceLevel, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apavar.normal/ ## Result Returns the parametric normal value at risk (VaR) of a return time series. ## Syntax *Returns*: vector containing a return time series *ConfidenceLevel*: confidence level, e.g. 0.95. *IsSampleOtherwisePopulation*: optional; TRUE for sample volatility (division by n-1), FALSE for population volatility (division by n); default: FALSE ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image160.svg) qα is the α-quantile of the standard normal distribution, α = 1 − *ConfidenceLevel*. Losses are reported as negative numbers. ## Remarks The volatility is the sample (denominator n − 1) or population (denominator n) standard deviation, set by IsSampleOtherwisePopulation; default: population. # apaVaR.Normal.FromConstituents(Weights, Returns, ConfidenceLevel, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apavar.normal.fromconstituents/ ## Result Returns the ex ante parametric normal value at risk (VaR) of a portfolio, calculated from constituent weights and returns. ## Syntax *Weights*: 1 x n vector of constituent weights *Returns*: r x n matrix of constituent returns, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. *IsSampleOtherwisePopulation*: optional; TRUE for sample volatility (division by n-1), FALSE for population volatility (division by n); default: FALSE ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image160.svg) qα is the α-quantile of the standard normal distribution, α = 1 − *ConfidenceLevel*. Losses are reported as negative numbers. ## Remarks The volatility is the sample (denominator n − 1) or population (denominator n) standard deviation, set by IsSampleOtherwisePopulation; default: population. # apaVaR.Normal.Moments(Mu, Sigma, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apavar.normal.moments/ ## Result Returns the parametric normal value at risk (VaR), calculated from moments. ## Syntax *Mu*: the location parameter (mean) *Sigma*: the dispersion parameter (volatility) *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image160.svg) qα is the α-quantile of the standard normal distribution, α = 1 − *ConfidenceLevel*. Losses are reported as negative numbers. # apaVaR.GARCH11.Conditional(Returns, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apavar.garch11.conditional/ ## Result Returns the value at risk (VaR) calculated from the conditional volatility of a fitted GARCH(1,1) model. ## Syntax *Returns*: r x 1 vector of returns *ConfidenceLevel*: confidence level, e.g. 0.95. ## Remarks GARCH by maximum likelihood with the unconditional variance targeted at the sample variance (denominator n − 1). # apaVectorAutoregress.Betas(DataMatrix, Order, WithInterceptOtherwiseNot) URL: https://www.andreassteiner.net/help/apavectorautoregress.betas/ ## Result Calculates the OLS betas of a vector autoregressive (VAR) model of order p. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order p, i.e. the number of lags to consider *WithInterceptOtherwiseNot*: TRUE to add an intercept term to the model, FALSE for no intercept # apaVectorAutoregress.Betas.tValue(DataMatrix, Order, WithInterceptOtherwiseNot) URL: https://www.andreassteiner.net/help/apavectorautoregress.betas.tvalue/ ## Result Returns the t-values of the estimated OLS betas of a vector autoregressive (VAR) model of order p. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order p, i.e. the number of lags to consider *WithInterceptOtherwiseNot*: TRUE to add an intercept term to the model, FALSE for no intercept ## Remarks Residual variance is SSE/(n − k), i.e. degrees-of-freedom corrected. # apaVectorAutoregress.CompanionMatrix(Betas, WithInterceptOtherwiseNot) URL: https://www.andreassteiner.net/help/apavectorautoregress.companionmatrix/ ## Result Returns the companion matrix of a vector autoregressive (VAR) model, derived from the VAR betas. ## Syntax *Betas*: r x c matrix of VAR betas, each column containing the betas of a variable *WithInterceptOtherwiseNot*: TRUE if the betas include an intercept term, FALSE if not # apaVectorAutoregress.Fitted(DataMatrix, Order, WithInterceptOtherwiseNot) URL: https://www.andreassteiner.net/help/apavectorautoregress.fitted/ ## Result Returns the fitted values of a vector autoregressive (VAR) model of order p. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order p, i.e. the number of lags to consider *WithInterceptOtherwiseNot*: TRUE to add an intercept term to the model, FALSE for no intercept # apaVectorAutoregress.Forecast(DataMatrix, Order, WithInterceptOtherwiseNot, nAhead) URL: https://www.andreassteiner.net/help/apavectorautoregress.forecast/ ## Result Returns forecasts from a vector autoregressive (VAR) model of order p. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order p, i.e. the number of lags to consider *WithInterceptOtherwiseNot*: TRUE to add an intercept term to the model, FALSE for no intercept *nAhead*: number of periods ahead to forecast # apaVectorAutoregress.Forecast.WithData(DataMatrix, Order, WithInterceptOtherwiseNot, nAhead) URL: https://www.andreassteiner.net/help/apavectorautoregress.forecast.withdata/ ## Result Returns forecasts from a vector autoregressive (VAR) model of order p, appended to the existing data. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order p, i.e. the number of lags to consider *WithInterceptOtherwiseNot*: TRUE to add an intercept term to the model, FALSE for no intercept *nAhead*: number of periods ahead to forecast # apaVectorAutoregress.ImpulseResponse(DataMatrix, Order, WithInterceptOtherwiseNot, Shock, nAhead) URL: https://www.andreassteiner.net/help/apavectorautoregress.impulseresponse/ ## Result Returns the impulse responses of a vector autoregressive (VAR) model of order p, i.e. the projected response of all variables to a unit shock in one variable. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order p, i.e. the number of lags to consider *WithInterceptOtherwiseNot*: TRUE to add an intercept term to the model, FALSE for no intercept *Shock*: index of the variable which is shocked. The sign of the index determines whether the shock is positive or negative *nAhead*: number of periods ahead to project the shock # apaVectorAutoregress.R2(DataMatrix, Order, WithInterceptOtherwiseNot) URL: https://www.andreassteiner.net/help/apavectorautoregress.r2/ ## Result Returns the overall R-squared of a vector autoregressive (VAR) model of order p. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order p, i.e. the number of lags to consider *WithInterceptOtherwiseNot*: TRUE to add an intercept term to the model, FALSE for no intercept # apaVectorAutoregress.R2s(DataMatrix, Order, WithInterceptOtherwiseNot) URL: https://www.andreassteiner.net/help/apavectorautoregress.r2s/ ## Result Returns the R-squared of each equation of a vector autoregressive (VAR) model of order p. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order p, i.e. the number of lags to consider *WithInterceptOtherwiseNot*: TRUE to add an intercept term to the model, FALSE for no intercept # apaVectorAutoregress.Residuals(DataMatrix, Order, WithInterceptOtherwiseNot) URL: https://www.andreassteiner.net/help/apavectorautoregress.residuals/ ## Result Returns the residuals of a vector autoregressive (VAR) model of order p. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order p, i.e. the number of lags to consider *WithInterceptOtherwiseNot*: TRUE to add an intercept term to the model, FALSE for no intercept # apaVectorAutoregress.X(DataMatrix, Order, WithInterceptOtherwiseNot) URL: https://www.andreassteiner.net/help/apavectorautoregress.x/ ## Result Returns the X data matrix of a vector autoregressive (VAR) model of order p. ## Syntax *DataMatrix*: r x c matrix of data, each column containing a series *Order*: order p, i.e. the number of lags to consider *WithInterceptOtherwiseNot*: TRUE to add an intercept term to the model, FALSE for no intercept # apaVersion.Installed() URL: https://www.andreassteiner.net/help/apaversion.installed/ ## Result Returns the version of the installed add-in. ## Syntax No arguments This function has no arguments. # apaVersion.Current() URL: https://www.andreassteiner.net/help/apaversion.current/ ## Result Returns the latest version of the add-in available. ## Syntax No arguments This function has no arguments. ## Remarks This function only works if the computer is connected to the Internet. # apaVolatilities(ReturnsMatrix, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apavolatilities/ ## Result Returns the ex post volatilities of several time series. ## Syntax *ReturnsMatrix*: data matrix in which each column contains a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample volatility (division by n-1), FALSE for population volatility (division by n); default: FALSE # apaVolatilities.ExpWeighted(TimeSeries, HalfLife) URL: https://www.andreassteiner.net/help/apavolatilities.expweighted/ ## Result Returns the ex post exponentially weighted volatilities of a time series matrix. ## Syntax *TimeSeries*: matrix containing time series data, each column a series *HalfLife*: half-life of the exponential weighting scheme ## Remarks Exponentially weighted moments; the weights sum to one (population-type, no small-sample correction). # apaVolatility.ExpWeighted.HalfLife.Calibrate(Returns, MinHalfLife, MaxHalfLife, InitialHalfLife, WarmupLength, RealizedVolWindow, WindowMode, RollingWindowLength) URL: https://www.andreassteiner.net/help/apavolatility.expweighted.halflife.calibrate/ ## Result Calibrate the half‑life of an exponentially weighted volatility model by minimizing out‑of‑sample forecast loss, optionally across multiple return series in one call. The function returns, for each series, the optimal half‑life, the corresponding EWMA decay factor $`\lambda`$, the objective value, and optimization diagnostics. In EWMA volatility models, the decay factor $`\lambda`$controls the exponential down‑weighting of older returns, and half‑life is related to $`\lambda`$via $`\text{half‑life} = \ln(0.5)/ln(\lambda)`$. ## Syntax *Returns*: n x 1, 1 x n, or n x k matrix of arithmetic returns. If a matrix is passed, each column is treated as a separate series. *MinHalfLife*: optional; lower bound for half-life, \> 0. Default: 2. *MaxHalfLife*: optional; upper bound for half-life, \> MinHalfLife. Default: 250. *InitialHalfLife*: optional; initial half-life guess. Default: 21. *WarmupLength*: optional; minimum number of observations before the first forecast origin. Default: 60. *RealizedVolWindow*: optional; forward realized-volatility window. Default: 5. *WindowMode*: optional; 0 = Expanding, 1 = Rolling; default: 0 *RollingWindowLength*: optional; rolling estimation window length; used only if WindowMode = 1. Default: 60. ## Algorithm Accept returns as a vector, matrix of doubles, or Excel object matrix; validate there are no empty or missing cells and convert to a numeric $`n \times k`$array where each column is one return series. For each series, call EWMACalibration.CalibrateHalfLife over the search interval \[MinHalfLife, MaxHalfLife\], starting from InitialHalfLife. The EWMA volatility model uses a decay factor $`\lambda`$ with recursive form ``` math \sigma_{t}^{2} = \lambda\sigma_{t - 1}^{2} + (1 - \lambda)r_{t - 1}^{2}, ``` and the calibration routine searches over half‑life (equivalently $`\lambda`$) to minimize an out‑of‑sample forecast loss, such as realized volatility or next‑day squared return, given the chosen target. An expanding or rolling estimation window is used (controlled by WindowMode and RollingWindowLength), with WarmupLength observations before the first forecast origin and RealizedVolWindow observations for the realized volatility computation. The optimization uses internal settings for the perturbation scale, convergence tolerance, maximum number of evaluations, restarts and probe scale. For each series, the following is returned: - HalfLife: calibrated half-life. - Lambda: decay factor corresponding to the calibrated half-life. - ObjectiveValue: minimized forecast-loss value. - EvaluationCount: number of function evaluations. - RestartCount: number of optimization restarts. - TerminationReason: reason the optimization stopped (e.g. converged, max evaluations). This function allows you to empirically tune EWMA volatility decay to your data and chosen forecasting target, rather than relying on a fixed rule‑of‑thumb $`\lambda`$or half‑life. ## Remarks Exponentially weighted moments; the weights sum to one (population-type, no small-sample correction). # apaVolatilities.FromCovars(Covariances) URL: https://www.andreassteiner.net/help/apavolatilities.fromcovars/ ## Result Returns the volatilities contained in a covariance matrix, i.e. the square roots of the diagonal elements. ## Syntax *Covariances*: covariance matrix # apaVolatilities.Jagged(DataMatrix, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apavolatilities.jagged/ ## Result Returns the ex post volatilities of all columns of a jagged data matrix. ## Syntax *DataMatrix*: data matrix in which each column contains a time series *IsSampleOtherwisePopulation*: optional; TRUE for sample volatilities (division by n-1), FALSE for population volatilities (division by n); default: FALSE ## Remarks *Each column is evaluated on its own numeric observations; empty cells, text, logical values and error values are skipped, so series of different lengths and with gaps can be combined in one matrix. The output is a 1 x m row vector. A column without numeric observations, or with fewer than two numeric observations when sample volatilities are requested, returns \#N/A. Volatilities are not annualised; they refer to the periodicity of the input data.* # apaVolatilities.Random(nAssets) URL: https://www.andreassteiner.net/help/apavolatilities.random/ ## Result Generates a 1 x nAssets vector of uniformly distributed random volatilities between 0% and 100%. Multiply with a constant \< 1 to generate volatilities from a narrower range. ## Syntax *nAssets*: number of assets ## Remarks The volatilities are uniformly distributed between 0% and 100%. Multiply with a scalar \< 1 to draw from a narrower range. # apaVolatilities.MatchObservedCVaRs(CVaR, Mu, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apavolatilities.matchobservedcvars/ ## Result Finds the normal volatilities which reproduce given conditional values at risk (CVaR), given the means and a confidence level. ## Syntax *CVaR*: 1 x c vector of CVaR figures to match *Mu*: 1 x c vector of location parameters *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm For each constituent, the volatility is calculated as σ = (1 - ConfidenceLevel) \* (Mu - CVaR) / φ(z), with z the (1 - ConfidenceLevel) quantile and φ the density of the standard normal distribution. ## Remarks CVaR figures are expressed as returns, i.e. losses are negative figures. # apaVolatilities.MatchObservedVaRs(VaR, Mu, ConfidenceLevel) URL: https://www.andreassteiner.net/help/apavolatilities.matchobservedvars/ ## Result Finds the normal volatilities which reproduce given values at risk (VaR), given the means and a confidence level. ## Syntax *VaR*: 1 x c vector of VaR figures to match *Mu*: 1 x c vector of location parameters *ConfidenceLevel*: confidence level, e.g. 0.95. ## Algorithm For each constituent, the volatility is calculated as σ = (VaR - Mu) / z, with z the (1 - ConfidenceLevel) quantile of the standard normal distribution. ## Remarks VaR figures are expressed as returns, i.e. losses are negative figures. # apaVolatilities.Shrink.Hi(Volatilities, Shrinkage) URL: https://www.andreassteiner.net/help/apavolatilities.shrink.hi/ ## Result Shrinks a vector of cross-sectional volatilities towards the highest volatility. ## Syntax *Volatilities*: 1 x c volatility vector *Shrinkage*: shrinkage factor between 0% and 100% ## Algorithm Each element is calculated as (1 − Shrinkage) \* σ(i) + Shrinkage \* max(σ). ## Remarks The function is volatile. # apaVolatilities.Shrink.Lo(Volatilities, Shrinkage) URL: https://www.andreassteiner.net/help/apavolatilities.shrink.lo/ ## Result Shrinks a vector of cross-sectional volatilities towards the lowest volatility. ## Syntax *Volatilities*: 1 x c volatility vector *Shrinkage*: shrinkage factor between 0% and 100% ## Algorithm Each element is calculated as (1 − Shrinkage) \* σ(i) + Shrinkage \* min(σ). ## Remarks The function is volatile. # apaVolatilities.Shrink.Mean(Volatilities, Shrinkage) URL: https://www.andreassteiner.net/help/apavolatilities.shrink.mean/ ## Result Shrinks a vector of cross-sectional volatilities towards the mean volatility. ## Syntax *Volatilities*: 1 x c volatility vector *Shrinkage*: shrinkage factor between 0% and 100% ## Algorithm Each element is calculated as (1 − Shrinkage) \* σ(i) + Shrinkage \* mean(σ). ## Remarks The function is volatile. # apaVolatilities.Specific(AssetReturns, IndexReturns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apavolatilities.specific/ ## Result Calculates the specific (idiosyncratic) volatilities relative to an index, i.e. the volatilities of the single index model residuals. ## Syntax *AssetReturns*: r x c matrix containing the asset returns. Each column contains an asset return time series. *IndexReturns*: r x 1 vector of index returns *IsSampleOtherwisePopulation*: optional; TRUE for sample variances and covariances (division by n-1), FALSE for population variances and covariances (division by n); default: FALSE ## Algorithm For each asset, the beta relative to the index is calculated as β = cov(r, r_I) / var(r_I). ## Remarks The function is volatile. # apaVolatilities.Specific.Percentage(AssetReturns, IndexReturns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apavolatilities.specific.percentage/ ## Result Calculates the specific (idiosyncratic) volatilities relative to an index as a percentage of total volatility. ## Syntax *AssetReturns*: r x c matrix containing the asset returns. Each column contains an asset return time series. *IndexReturns*: r x 1 vector of index returns *IsSampleOtherwisePopulation*: optional; TRUE for sample variances and covariances (division by n-1), FALSE for population variances and covariances (division by n); default: FALSE ## Algorithm For each asset, the beta relative to the index is calculated as β = cov(r, r_I) / var(r_I). ## Remarks The square of the result equals 1 − R², with R² the coefficient of determination of the single index model. # apaVolatility.ConfidenceIntervals(TimeSeries, ConfidenceLevel, nSamples) URL: https://www.andreassteiner.net/help/apavolatility.confidenceintervals/ ## Result Calculates confidence intervals for volatility, the square root of the second central moment, using a resampling methodology. Returns the lower and upper bounds for each time series. ## Syntax *TimeSeries*: data matrix, each column containing a time series *ConfidenceLevel*: confidence level, e.g. 0.95. *nSamples*: number of samples to generate ## Remarks Uses the sample volatility (denominator n − 1). # apaVolatility.FromCovars(Weights, Covariances) URL: https://www.andreassteiner.net/help/apavolatility.fromcovars/ ## Result Calculates portfolio volatilities from weights and a covariance matrix. ## Syntax *Weights*: matrix of portfolio constituent weights; constituents in columns, portfolios in rows *Covariances*: covariance matrix ## Remarks If Weights is a matrix, in which each row contains a portfolio, the volatilities of all portfolios are returned in a column vector. # apaVolatility.FromReturns(Weights, Returns, IsSampleOtherwisePopulation) URL: https://www.andreassteiner.net/help/apavolatility.fromreturns/ ## Result Calculates portfolio volatilities from weights and constituent returns. ## Syntax *Weights*: matrix of portfolio constituent weights; constituents in columns, portfolios in rows *Returns*: data matrix in which each column contains an asset time series *IsSampleOtherwisePopulation*: optional; TRUE for sample volatility (division by n-1), FALSE for population volatility (division by n); default: FALSE ## Remarks If Weights is a matrix, in which each row contains a portfolio, the volatilities of all portfolios are returned in a column vector. # apaVolatility.Downside(Returns, Threshold) URL: https://www.andreassteiner.net/help/apavolatility.downside/ ## Result Calculates the downside volatility of each column of a return matrix, i.e. the square root of the second lower partial moment with respect to the threshold. ## Syntax *Returns*: r x c matrix of returns, each column containing a series *Threshold*: return threshold ## Algorithm For each series, the downside volatility is calculated as the square root of LPM(Threshold, 2), the second-degree lower partial moment (see apaLPM). ## Remarks Downside is defined as below the threshold. Partial moments divide by the total number of observations n (population-type). # apaVolatility.Lower(Returns) URL: https://www.andreassteiner.net/help/apavolatility.lower/ ## Result Calculates the lower semi-volatility of a return series, i.e. the square root of the second lower partial moment with respect to the mean. ## Syntax *Returns*: r x 1 vector of returns ## Algorithm The lower semi-volatility is calculated as the square root of LPM(μ, 2), the second-degree lower partial moment with the mean μ as threshold (see apaLPM). ## Remarks Downside is defined as below the mean. Partial moments divide by the total number of observations n (population-type). # apaVolatility.Upper(Returns) URL: https://www.andreassteiner.net/help/apavolatility.upper/ ## Result Calculates the upper semi-volatility of a return series, i.e. the square root of the second upper partial moment with respect to the mean. ## Syntax *Returns*: r x 1 vector of returns ## Algorithm The upper semi-volatility is calculated as the square root of UPM(μ, 2), the second-degree upper partial moment with the mean μ as threshold (see apaUPM). ## Remarks Upside is defined as above the mean. Partial moments divide by the total number of observations n (population-type). # apaVolatility.Upside(Returns, Threshold) URL: https://www.andreassteiner.net/help/apavolatility.upside/ ## Result Calculates the upside volatility of each column of a return matrix, i.e. the square root of the second upper partial moment with respect to the threshold. ## Syntax *Returns*: r x c matrix of returns, each column containing a series *Threshold*: return threshold ## Algorithm For each series, the upside volatility is calculated as the square root of UPM(Threshold, 2), the second-degree upper partial moment (see apaUPM). ## Remarks Upside is defined as above the threshold. Partial moments divide by the total number of observations n (population-type). # apaWeights.BuyAndHold(InitialWeights, Returns) URL: https://www.andreassteiner.net/help/apaweights.buyandhold/ ## Result Returns a matrix containing the evolution of buy and hold weights, i.e. initial weights drifting with the constituent returns. ## Syntax *InitialWeights*: 1 x n vector of initial weights, each column containing an asset *Returns*: time series matrix, each column representing a time series # apaWeights.Combinatorial.EqualWeighted(nAssetsInUniverse, nAssetsInPortfolio) URL: https://www.andreassteiner.net/help/apaweights.combinatorial.equalweighted/ ## Result Returns the allocations of all possible portfolios containing nAssetsInPortfolio equally weighted assets selected from a universe of nAssetsInUniverse assets. ## Syntax *nAssetsInUniverse*: number of assets in the universe *nAssetsInPortfolio*: number of positions in the equal-weighted portfolios # apaWeights.Combinatorial.TwoAssets(nAssetsInUniverse, nAllocations) URL: https://www.andreassteiner.net/help/apaweights.combinatorial.twoassets/ ## Result Returns nAllocations allocations of all possible two-asset portfolios selected from a universe of nAssetsInUniverse assets. ## Syntax *nAssetsInUniverse*: number of assets in the universe *nAllocations*: number of weight combinations per asset pair # apaWeights.FromAllocations(Allocations, Returns) URL: https://www.andreassteiner.net/help/apaweights.fromallocations/ ## Result Calculates the weights over time from target allocations, letting the weights drift with the constituent returns between allocation dates. ## Syntax *Allocations*: matrix of target weights (beginning of period), each column containing an asset. The first column contains the 1-based time period index *Returns*: r x n matrix of constituent returns, each column containing a time series ## Algorithm At each time index listed in Allocations, the weights are set to the target weights. ## Remarks The result has the same number of rows as Returns. Allocation rows with a time index \< 1 are ignored. # apaWeights.Rebalanced(InitialWeights, Returns, RebalFreq) URL: https://www.andreassteiner.net/help/apaweights.rebalanced/ ## Result Returns a matrix containing the evolution of weights which are regularly rebalanced to the initial weights. ## Syntax *InitialWeights*: 1 x n vector of initial weights, each column containing an asset *Returns*: time series matrix, each column representing a time series *RebalFreq*: rebalancing frequency in number of observations # apaWeights.Style(StyleReturns, PortfolioReturns) URL: https://www.andreassteiner.net/help/apaweights.style/ ## Result Returns the style weights best replicating a portfolio return time series. ## Syntax *StyleReturns*: r x k matrix of style index returns, each column containing a time series *PortfolioReturns*: r x 1 vector of portfolio returns # apaWeights.Style.Rolling(StyleReturns, PortfolioReturns, WindowSize) URL: https://www.andreassteiner.net/help/apaweights.style.rolling/ ## Result Returns the rolling style weights best replicating a portfolio return time series. ## Syntax *StyleReturns*: r x k matrix of style index returns, each column containing a time series *PortfolioReturns*: r x 1 vector of portfolio returns *WindowSize*: number of observations over which the style weights are assumed to be constant # apaWeights.Tilt.Category(Weights, CategoryIndices, Tilt) URL: https://www.andreassteiner.net/help/apaweights.tilt.category/ ## Result Tilts a portfolio either towards the first category (positive tilt) or towards the rest of the portfolio (negative tilt). ## Syntax *Weights*: 1 x nCols vector with constituent weights *CategoryIndices*: 1 x nCols vector with category indices (text or numerical) *Tilt*: tilt between -1 (negative values tilt towards zero) and +1 (positive values tilt towards one) # apaWealthSimulation(InitialWealth, CashFlowSchedule, RiskReturnSchedule, nSimulations, nTimeSteps, InvestmentHorizon, CashRateSchedule, ConfidenceLevel, nHistogramBins, Threshold, IsRecoveryAllowed, IsThresholdLowerBound, IsStochasticInvestments) URL: https://www.andreassteiner.net/help/apawealthsimulation/ ## Result Monte Carlo wealth simulation with cash flows and time-varying risk and return. Returns time, cash flows, shortfall probability, expected, median and confidence wealth, and a terminal wealth histogram. ## Syntax *InitialWealth*: initial wealth *CashFlowSchedule*: m x 2 matrix of cash flows: time (in years) and amount. Positive amounts are inflows, negative amounts outflows. *RiskReturnSchedule*: m x 3 matrix: time (in years), expected return and volatility of the investment strategy from that time on *nSimulations*: number of simulations to perform *nTimeSteps*: number of time steps of the simulation *InvestmentHorizon*: investment horizon in years *CashRateSchedule*: m x 2 matrix: time (in years) and cash rate from that time on *ConfidenceLevel*: confidence level, e.g. 0.95. *nHistogramBins*: number of bins of the terminal wealth histogram *Threshold*: wealth shortfall threshold *IsRecoveryAllowed*: TRUE if wealth can recover after falling below the threshold, FALSE if paths stop at the shortfall *IsThresholdLowerBound*: TRUE if the threshold acts as a lower bound for wealth, FALSE otherwise *IsStochasticInvestments*: TRUE for stochastic (risky) investment returns, FALSE for deterministic returns equal to the expected returns ## Remarks The simulation is performed using the following assumptions… - Cash flows are mapped to the time scale defined by nTimeSteps and InvestmentHorizon. Where necessary, a rounding is performed such that all cash flows are represented on the timeline. - Cash flows are assumed to occur at the beginning of the period and are compounded immediately. - Wealth is assumed to follow a normally distributed process for continuous returns with the drift rates and volatilities defined in RiskReturnSchedule. - All compounding is assumed to be *continuous*. - The parameters IsRecoveryAllowed and IsThresholdLowerBound have important implications for wealth at the end of the investment horizon and the calculation of shortfall probability. # apaWLS(DataMat, WeightVec) URL: https://www.andreassteiner.net/help/apawls/ ## Result Applies a weight vector to a data matrix in order to perform weighted least squares (WLS) regression, i.e. multiplies each row by 1/sqrt of its weight. The weights are therefore interpreted as relative error variances. ## Syntax *DataMat*: r x c data matrix *WeightVec*: r x 1 vector of observation weights ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image161.svg) ## Remarks - Weighted least squares can be expressed as ordinary least squares with transformed variables… ![Formula](https://www.andreassteiner.net/help/assets/eq/image162.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image163.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image164.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image165.svg) # apaZScore(TimeSeries) URL: https://www.andreassteiner.net/help/apazscore/ ## Result Returns the z-scores of a time series, i.e. the deviations from the mean in units of standard deviation. ## Syntax *TimeSeries*: r x 1 data vector containing a time series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image166.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image167.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image168.svg) ## Remarks Uses the sample standard deviation (denominator n − 1). # apaZScore.Outlier(TimeSeries) URL: https://www.andreassteiner.net/help/apazscore.outlier/ ## Result Returns outlier flags based on z-scores: \* for \|z\| \>= 1, \*\* for \|z\| \>= 2 and \*\*\* for \|z\| \>= 3. ## Syntax *TimeSeries*: r x 1 data vector containing a time series ## Algorithm ![Formula](https://www.andreassteiner.net/help/assets/eq/image169.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image167.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image168.svg) ![Formula](https://www.andreassteiner.net/help/assets/eq/image170.svg) ## Remarks Uses the sample standard deviation (denominator n − 1).