Correlation ZonesThis indicator highlights zones with strong, weak and negative correlation. Unlike standard coefficient indicator it will help to filter out noise when analyzing dependencies between two assets.
With default input setting Correlation_Threshold=0.5:
- Zones with correlation above 0.5, will be colored in green (strong correlation)
- Zones with correlation from -0.5 to 0.5 will be colored grey (weak correlation)
- Zones with correlation below -0.5 will be colore red (strong negative correlation)
Input parameter "Correlation_Threshold" can be modified in settings.
Provided example demonstrates BTCUSD correlation with NASDAQ Composite . I advice to use weekly timeframe and set length to 26 week for this study
Statistics
Kendall Rank Correlation Coefficient (alt)This is a non-parametric correlation statistical test, which is less sensitive to magnitude and more to direction, hence why some people call this a "concordance test".
This indicator was originally created by Alex Orekhov (everget), if you like this one, please show the original author some love:
This version is extended by tartigradia (2022) to make it more readily useable:
* Update to pinescript v5
* Default compare to current symbol (instead of only fixed symbols)
* Add 1.0, 0.0 and -1.0 correlation levels lines.
This indicator plots both the Kendall correlation in orange, and the more classical parametric Pearson correlation in purple for comparison. Either can be disabled in the Style tab.
Three Linear Regression ChannelsPlot three linear regression channels using alexgrover 's Computing The Linear Regression Using The WMA And SMA indicator for the linear regression calculations.
Settings
Length : Number of inputs to be used
Source : Source input of the indicator
Midline Colour : The colour of the midline
Channel One, Two, and Three Multiplicative Factor : Multiplication factor for the RMSE, determine the distance between the upper and lower level
Channel One, Two, and Three Colour : The channel's lines colour
Usage
For usage details, please refer to alexgrover 's Computing The Linear Regression Using The WMA And SMA indicator.
Multi-Optimized Linear Regression ChannelA take on alexgrover 's Optimized Linear Regression Channel script which allows users to apply multiple linear regression channel with unique multiplicative factors.
Multiplicative Factors
Adjust the amount of channels and multiplicative factors of existing or additional channels using the "Mults" input.
An input of "1" creates a single linear regression channel with the multiplicative factor of one.
An input of "4" creates a single linear regression channel with the multiplicative factor of four.
An input of "1,4" creates two linear regression channels with multiplicative factors of one and four.
An input of "1,2,3" creates three linear regression channels with multiplicative factors of one, two, and three.
KernelFunctionsLibrary "KernelFunctions"
This library provides non-repainting kernel functions for Nadaraya-Watson estimator implementations. This allows for easy substitution/comparison of different kernel functions for one another in indicators. Furthermore, kernels can easily be combined with other kernels to create newer, more customized kernels. Compared to Moving Averages (which are really just simple kernels themselves), these kernel functions are more adaptive and afford the user an unprecedented degree of customization and flexibility.
rationalQuadratic(_src, _lookback, _relativeWeight, _startAtBar)
Rational Quadratic Kernel - An infinite sum of Gaussian Kernels of different length scales.
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_relativeWeight : Relative weighting of time frames. Smaller values result in a more stretched-out curve, and larger values will result in a more wiggly curve. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Rational Quadratic Kernel.
gaussian(_src, _lookback, _startAtBar)
Gaussian Kernel - A weighted average of the source series. The weights are determined by the Radial Basis Function (RBF).
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Gaussian Kernel.
periodic(_src, _lookback, _period, _startAtBar)
Periodic Kernel - The periodic kernel (derived by David Mackay) allows one to model functions that repeat themselves exactly.
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_period : The distance between repititions of the function.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Periodic Kernel.
locallyPeriodic(_src, _lookback, _period, _startAtBar)
Locally Periodic Kernel - The locally periodic kernel is a periodic function that slowly varies with time. It is the product of the Periodic Kernel and the Gaussian Kernel.
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_period : The distance between repititions of the function.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Locally Periodic Kernel.
AmitN STDEV V5Often, a trader would like to predict the range for the next certain amount of period. This is useful for doing short strangles, Iron Fy, Iron Condor strategies.
This script calculates the price range for the next 'X' number of candles on the given timeframe based on Standard Deviation formulae.
It gives this range on 1 standard deviation and 2 standard deviations.
-----------------------------------------------------------
1SD Range : Probability of expiry in that range is 68 %
2SD Range : Probability of expiry in that range is 95 %
-----------------------------------------------------------
From the settings, you can choose the "lookback" period which is used to calculate the next price prediction based on those many candles.
The range is plotted in the form of lines. It marks the range and also the difference between spot and the range-value.
ahpuhelperLibrary "ahpuhelper"
Helper Library for Auto Harmonic Patterns UltimateX. It is not meaningful for others. This is supposed to be private library. But, publishing it to make sure that I don't delete accidentally. Some functions may be useful for coders.
insert_open_trades_table_column(showOpenTrades, table_id, column, colors, values, intStatus, harmonicTrailingStartState, lblSizeOpenTrades)
add data to open trades table column
Parameters:
showOpenTrades : flag to show open trades table
table_id : Table Id
column : refers to pattern data
colors : backgroud and text color array
values : cell values
intStatus : status as integer
harmonicTrailingStartState : trailing Start state as per configs
lblSizeOpenTrades : text size
Returns: nextColumn
populate_closed_stats(ClosedStatsPosition, bullishCounts, bearishCounts, bullishRetouchCounts, bearishRetouchCounts, bullishSizeMatrix, bearishSizeMatrix, bullishRR, bearishRR, allPatternLabels, flags, rowMain, rowHeaders)
populate closed stats for harmonic patterns
Parameters:
ClosedStatsPosition : Table position for closed stats
bullishCounts : Matrix containing bullish trade stats
bearishCounts : Matrix containing bearish trade stats
bullishRetouchCounts : Matrix containing bullish trade stats for those which retouched entry
bearishRetouchCounts : Matrix containing bearish trade stats for those which retouched entry
bullishSizeMatrix : Matrix containing data about size of bullish patterns
bearishSizeMatrix : Matrix containing data about size of bearish patterns
bullishRR : Matrix containing Risk Reward data of bullish patterns
bearishRR : Matrix containing Risk Reward data of bearish patterns
allPatternLabels : array containing pattern labels
flags : display flags
rowMain : Pattern header data
rowHeaders : header grouping data
Returns: void
get_rr_details(patternTradeDetails, harmonicTrailingStartState, disableTrail, breakEvenTrail)
calculate and return risk reward based on targets and stops
Parameters:
patternTradeDetails : array containing stop, entry and targets
harmonicTrailingStartState : trailing point
disableTrail : If set, ignores trailing point
breakEvenTrail : If set, trailing does not go beyond breakeven.
Returns: nextColumn
Market Beta/Beta Coefficient for CAPM [Loxx]Market Beta/Beta Coefficient for CAPM is not so much an indicator as it is a value to be used in future indicators to forecast stock prices using the Capital Asset Pricing Model, CAPM. CAPM is used by the likes of value investors such as Warren Buffet and valuation/accounting/investment banking firms. More specifically, CAPM is typically used in Discounted Cashflow Analysis to value revenue generating assets.
What is Beta?
In finance, the beta (β or market beta or beta coefficient) is a measure of how an individual asset moves (on average) when the overall stock market increases or decreases. Thus, beta is a useful measure of the contribution of an individual asset to the risk of the market portfolio when it is added in small quantity. Thus, beta is referred to as an asset's non-diversifiable risk, its systematic risk, market risk, or hedge ratio. Beta is not a measure of idiosyncratic risk.
By definition, the value-weighted average of all market-betas of all investable assets with respect to the value-weighted market index is 1. If an asset has a beta above (below) 1, it indicates that its return moves more (less) than 1-to-1 with the return of the market-portfolio, on average. In practice, few stocks have negative betas (tending to go up when the market goes down). Most stocks have betas between 0 and 3.
How to calculate Beta
To calculate beta you typically choose 5 years of monthly data; typically SPY is used here
Calculate log returns of both the asset for which you are calculating Beta and the benchmark market data
Calculation the covariance between the asset and benchmark
Calculate the variance of the benchmark returns
Divide the covariance by the variance
Read more here:
en.wikipedia.org(finance)
en.wikipedia.org
einvestingforbeginners.com
[MT] Strategy Backtest Template| Initial Release | | EN |
An update of my old script, this script is designed so that it can be used as a template for all those traders who want to save time when programming their strategy and backtesting it, having functions already programmed that in normal development would take you more time to program, with this template you can simply add your favorite indicator and thus be able to take advantage of all the functions that this template has.
🔴Stop Loss and 🟢Take Profit:
No need to mention that it is a Stop Loss and a Take Profit, within these functions we find the options of: fixed percentage (%), fixed price ($), ATR, especially for Stop Loss we find the Pivot Points, in addition to this, the price range between the entry and the Stop Loss can be converted into a trailing stop loss, instead, especially for the Take Profit we have an option to choose a 1:X ratio that complements very well with the Pivot Points.
📈Heikin Ashi Based Entries:
Heikin Ashi entries are trades that are calculated based on Heikin Ashi candles but their price is executed to Japanese candles, thus avoiding false results that occur in Heikin candlestick charts, this making in certain cases better results in strategies that are executed with this option compared to Japanese candlesticks.
📊Dashboard:
A more visual and organized way to see the results and necessary data produced by our strategy, among them we can see the dates between which our operations are made regardless if you have activated some time filter, usual data such as Profit, Win Rate, Profit factor are also displayed in this panel, additionally data such as the total number of operations, how many were gains and how many losses, the average profit and loss for each operation and finally the maximum profits and losses followed, which are data that will be very useful to us when we elaborate our strategies.
Feel free to use this template to program your own strategies, if you find errors or want to request a new feature let me know in the comments or through my social networks found in my tradingview profile.
| Update 1.1 | | EN |
➕Additions: '
Time sessions filter and days of the week filter added to the time filter section.
Option to add leverage to the strategy.
5 Moving Averages, RSI, Stochastic RSI, ADX, and Parabolic Sar have been added as indicators for the strategy.
You can choose from the 6 available indicators the way to trade, entry alert or entry filter.
Added the option of ATR for Take Profit.
Ticker information and timeframe are now displayed on the dashboard.
Added display customization and color customization of indicator plots.
Added customization of display and color plots of trades displayed on chart.
📝Changes:
Now when activating the time filter it is optional to add a start or end date and time, being able to only add a start date or only an end date.
Operation plots have been changed from plot() to line creation with line.new().
Indicator plots can now be controlled from the "plots" section.
Acceptable and deniable range of profit, winrate and profit factor can now be chosen from the "plots" section to be displayed on the dashboard.
Aesthetic changes in the section separations within the settings section and within the code itself.
The function that made the indicators give inputs based on heikin ashi candles has been changed, see the code for more information.
⚙️Fixes:
Dashboard label now projects correctly on all timeframes including custom timeframes.
Removed unnecessary lines and variables to take up less code space.
All code in general has been optimized to avoid the use of variables, unnecessary lines and avoid unnecessary calculations, freeing up space to declare more variables and be able to use fewer lines of code.
| Lanzamiento Inicial | | ES |
Una actualización de mi antiguo script, este script está diseñado para que pueda ser usado como una plantilla para todos aquellos traders que quieran ahorrar tiempo al programar su estrategia y hacer un backtesting de ella, teniendo funciones ya programadas que en el desarrollo normal te tomaría más tiempo programar, con esta plantilla puedes simplemente agregar tu indicador favorito y así poder aprovechar todas las funciones que tiene esta plantilla.
🔴Stop Loss y 🟢Take Profit:
No hace falta mencionar que es un Stop Loss y un Take Profit, dentro de estas funciones encontramos las opciones de: porcentaje fijo (%), precio fijo ($), ATR, en especial para Stop Loss encontramos los Pivot Points, adicionalmente a esto, el rango de precio entre la entrada y el Stop Loss se puede convertir en un trailing stop loss, en cambio, especialmente para el Take Profit tenemos una opción para elegir un ratio 1:X que se complementa muy bien con los Pivot Points.
📈Entradas Basadas en Heikin Ashi:
Las entradas Heikin Ashi son operaciones que son calculados en base a las velas Heikin Ashi pero su precio esta ejecutado a velas japonesas, evitando así́ los falsos resultados que se producen en graficas de velas Heikin, esto haciendo que en ciertos casos se obtengan mejores resultados en las estrategias que son ejecutadas con esta opción en comparación con las velas japonesas.
📊Panel de Control:
Una manera más visual y organizada de ver los resultados y datos necesarios producidos por nuestra estrategia, entre ellos podemos ver las fechas entre las que se hacen nuestras operaciones independientemente si se tiene activado algún filtro de tiempo, datos usuales como el Profit, Win Rate, Profit factor también son mostrados en este panel, adicionalmente se agregaron datos como el número total de operaciones, cuantos fueron ganancias y cuantos perdidas, el promedio de ganancias y pérdidas por cada operación y por ultimo las máximas ganancias y pérdidas seguidas, que son datos que nos serán muy útiles al elaborar nuestras estrategias.
Siéntete libre de usar esta plantilla para programar tus propias estrategias, si encuentras errores o quieres solicitar una nueva función házmelo saber en los comentarios o a través de mis redes sociales que se encuentran en mi perfil de tradingview.
| Actualización 1.1 | | ES |
➕Añadidos:
Filtro de sesiones de tiempo y filtro de días de la semana agregados al apartado de filtro de tiempo.
Opción para agregar apalancamiento a la estrategia.
5 Moving Averages, RSI, Stochastic RSI, ADX, y Parabolic Sar se han agregado como indicadores para la estrategia.
Puedes escoger entre los 6 indicadores disponibles la forma de operar, alerta de entrada o filtro de entrada.
Añadido la opción de ATR para Take Profit.
La información del ticker y la temporalidad ahora se muestran en el dashboard.
Añadido personalización de visualización y color de los plots de indicadores.
Añadido personalización de visualización y color de los plots de operaciones mostradas en grafica.
📝Cambios:
Ahora al activar el filtro de tiempo es opcional añadir una fecha y hora de inicio o fin, pudiendo únicamente agregar una fecha de inicio o solamente una fecha de fin.
Los plots de operaciones han cambiados de plot() a creación de líneas con line.new().
Los plots de indicadores ahora se pueden controlar desde el apartado "plots".
Ahora se puede elegir el rango aceptable y negable de profit, winrate y profit factor desde el apartado "plots" para mostrarse en el dashboard.
Cambios estéticos en las separaciones de secciones dentro del apartado de configuraciones y dentro del propio código.
Se ha cambiado la función que hacía que los indicadores dieran entradas en base a velas heikin ashi, mire el código para más información.
⚙️Arreglos:
El dashboard label ahora se proyecta correctamente en todas las temporalidades incluyendo las temporalidades personalizadas.
Se han eliminado líneas y variables innecesarias para ocupar menos espacio en el código.
Se ha optimizado todo el código en general para evitar el uso de variables, líneas innecesarias y evitar los cálculos innecesarios, liberando espacio para declarar más variables y poder utilizar menos líneas de código.
Candle wick averageThis tool shows all 4 values: (Candle chart can describe the size)
- Average wick length below It is calculated as the length of the candle wick under the rising candlestick. calculated average (AVG) and Standard Deviation (STDEV). plot on the chart at the current bar using (open price ) - (average + STDEV ).
- Average wick + average body above(high - open) is calculated from the upper wick and upper body wick length of the rising candle. take Average (AVG) and standard deviation (STDEV). plot on the chart at the current bar using (open price) + (average + 2*STDEV)
- The other 2 values are calculated in the same way. But using the data of the candlestick that the price has moved down.
Usage example
- Use the average of the lower wick length to determine the SL for buy order.
- Use the average wick length and the candle above to set the TP for buy order.
- The other 2 values use in the same way for sell order
Correlation with P-Value & Confidence Interval (alt)Shows the Pearson correlation between two symbols, including statistical significance test.
This is a fork of the original script by Balipour, with the addition of EMA that can be used instead of SMA in the Pearson correlation as an attempt to capture correlation trend changes more quickly, and conversion to pinescript v5. In the end, the EMA does not help much, for a faster capture of correlation trend changes, another kind of correlation is necessary, such as sign test correlation (another one of my indicators implement this idea).
Please show the original indicator's author some love if you appreciate this work:
BTC's #4 Whale Sells [TheSecretGuy]Hello there !
I have been tracking BTC richests wallets for some time - and one of them seems to be aligning its sells pretty well with what the market is about to do.
BTC's Whale #3 (now Whale #4) has been selling his BTC in very crutial moments - therefore I felt that converting this into an indicator will give us a pretty visual feedback of what that Whale expects to happen at a given point.
In order to do that, I have listed manually all of his sells (dates) until today and placed a vertical line on the chart on each of these dates.
This sadly can't be automated as Pinescript language doesn't allow to reach outter data - I'd need to update this manually.
Hope this helps you a bit, Cheers!
Dealar VIX Implied Range + Retracement LevelsThis Implied range Is derived by the VIX(1 sd annual +/- Implied move.)
This Indicator plots the daily Implied range, A lot of quantitative trading firms/ MM firms hedge their delta & gamma exposure around the Implied range(prop calc). I have added retracement levels as well, so you have more pivot levels.
Enjoy!
normsinvLibrary "normsinv"
Description:
Returns the inverse of the standard normal cumulative distribution.
The distribution has a mean of zero and a standard deviation of one; i.e.,
normsinv seeks that value z such that a normal distribtuion of mean of zero
and standard deviation one is equal to the input probability.
Reference:
github.com
normsinv(y0)
Returns the inverse of the standard normal cumulative distribution. The distribution has a mean of zero and a standard deviation of one.
Parameters:
y0 : float, probability corresponding to the normal distribution.
Returns: float, z-score
[MAD] TrendmonitorFollowing indicator is a multi-asset monitor
Possibilitys:
16 Custom tickers
7 Colorschemes
Smoothing and scaling of the assets
invert the colors
shift the labels left/right
cndevLibrary "cndev"
This function returns the inverse of cumulative normal distribution function
Reference:
The Full Monte, by Boris Moro, Union Bank of Switzerland . RISK 1995(2)
CNDEV(U)
Returns the inverse of cumulative normal distribution function
Parameters:
U : float,
Returns: float.
Hussarya compare DJI SPX BTCScript shows relations between DJI downJones SPX and BTC:USD.
DJI chart must be set from candlestick to line
Red line is price (close). x 8
Green line ist te price BTCUSD from Binance price (close) x 1.5
Strategy PnL LibraryLibrary "Strategy_PnL_Library"
TODO: This is a library that helps you learn current pnl of open position and use it to create your own dynamic take profit or stop loss rules based on current level of your profit. It should only be used with strategies.
inTrade()
inTrade: Checks if a position is currently open.
Returns: bool: true for yes, false for no.
notInTrade()
inTrade: Checks if a position is currently open. Interchangeable with inTrade but just here for simple semantics.
Returns: bool: true for yes, false for no.
pnl()
pnl: Calculates current profit or loss of position after the commission. If the strategy is not in trade it will always return na.
Returns: float: Current Profit or Loss of position, positive values for profit, negative values for loss.
entryBars()
entryBars: Checks how many bars it's been since the entry of the position.
Returns: int: Returns a int of strategy entry bars back. Minimum value is always corrected to 1 to avoid lookback errors.
pnlvelocity()
pnlvelocity: Calculates the velocity of pnl by following the change in open profit compared to previous bar. If the strategy is not in trade it will always return na.
Returns: float: Returns a float value of pnl velocity.
pnlacc()
pnlacc: Calculates the acceleration of pnl by following the change in profit velocity compared to previous bar. If the strategy is not in trade it will always return na.
Returns: float: Returns a float value of pnl acceleration.
pnljerk()
pnljerk: Calculates the jerk of pnl by following the change in profit acceleration compared to previous bar. If the strategy is not in trade it will always return na.
Returns: float: Returns a float value of pnl jerk.
pnlhigh()
pnlhigh: Calculates the highest value the pnl has reached since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float highest value the pnl has reached.
pnllow()
pnllow: Calculates the lowest value the pnl has reached since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float lowest value the pnl has reached.
pnldev()
pnldev: Calculates the deviance of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float deviance value of the pnl.
pnlvar()
pnlvar: Calculates the variance value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float variance value of the pnl.
pnlstdev()
pnlstdev: Calculates the stdev value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float stdev value of the pnl.
pnlmedian()
pnlmedian: Calculates the median value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float median value of the pnl.
ctndLibrary "ctnd"
Description:
Double precision algorithm to compute the cumulative trivariate normal distribution
found in A.Genz, Numerical computation of rectangular bivariate and trivariate normal
and t probabilities”, Statistics and Computing, 14, (3), 2004. The cumulative trivariate
normal is needed to price window barrier options, see G.F. Armstrong, Valuation formulae
or window barrier options”, Applied Mathematical Finance, 8, 2001.
References:
link.springer.com
www.tandfonline.com
citeseerx.ist.psu.edu
The Complete Guide to Option Pricing Formulas, 2nd ed. (Espen Gaarder Haug)
CTND(LIMIT1, LIMIT2, LIMIT3, SIGMA1, SIGMA2, SIGMA3)
Returns the Cumulative Trivariate Normal Distribution
Parameters:
LIMIT1 : float,
LIMIT2 : float,
LIMIT3 : float,
SIGMA1 : float,
SIGMA2 : float,
SIGMA3 : float,
Returns: float.
combinLibrary "combin"
Description:
The combin function is a the combination function
as it calculates the number of possible combinations for two given numbers.
This function takes two arguments: the number and the number_chosen.
For example, if the number is 5 and the number chosen is 1,
there are 5 combinations, giving 5 as a result.
Reference:
ideone.com
support.microsoft.com
combin(n, kin)
Returns the number of combinations for a given number of items. Use to determine the total possible number of groups for a given number of items.
Parameters:
n : int, The number of items.
kin : int, The number of items in each combination.
Returns: int.
Z Bollinger BandsThis version of Bollinger Bands measures the average volatility. By taking the 75th percentile of the average absolute value of the difference between the Source and the Mean divided by the Standard Deviation and using that as our multiplier for our Bollinger bands we can have a statistically safe trading zone.
You notice that its dynamic, this is because it take into account the real volatility levels of a window and uses that to determine an appropriate multiplier. As always I hope you enjoy this release.
norminvLibrary "norminv"
Description:
An inverse normal distribution is a way to work backwards
from a known probability to find an x-value. It is an informal term and
doesn't refer to a particular probability distribution. Returns the
value of the inverse normal distribution function for a specified value,
mean, and standard deviation.
Reference:
github.com
support.microsoft.com
norminv(x, mean, stdev)
Returns the value of the inverse normal distribution function for a specified value, mean, and standard deviation.
Parameters:
x : float, The input to the normal distribution function.
mean : float, The mean (mu) of the normal distribution function
stdev : float, The standard deviation (sigma) of the normal distribution function.
Returns: float.
cbndLibrary "cbnd"
Description:
A standalone Cumulative Bivariate Normal Distribution (CBND) functions that do not require any external libraries.
This includes 3 different CBND calculations: Drezner(1978), Drezner and Wesolowsky (1990), and Genz (2004)
Comments:
The standardized cumulative normal distribution function returns the probability that one random
variable is less than a and that a second random variable is less than b when the correlation
between the two variables is p. Since no closed-form solution exists for the bivariate cumulative
normal distribution, we present three approximations. The first one is the well-known
Drezner (1978) algorithm. The second one is the more efficient Drezner and Wesolowsky (1990)
algorithm. The third is the Genz (2004) algorithm, which is the most accurate one and therefore
our recommended algorithm. West (2005b) and Agca and Chance (2003) discuss the speed and
accuracy of bivariate normal distribution approximations for use in option pricing in
ore detail.
Reference:
The Complete Guide to Option Pricing Formulas, 2nd ed. (Espen Gaarder Haug)
CBND1(A, b, rho)
Returns the Cumulative Bivariate Normal Distribution (CBND) using Drezner 1978 Algorithm
Parameters:
A : float,
b : float,
rho : float,
Returns: float.
CBND2(A, b, rho)
Returns the Cumulative Bivariate Normal Distribution (CBND) using Drezner and Wesolowsky (1990) function
Parameters:
A : float,
b : float,
rho : float,
Returns: float.
CBND3(x, y, rho)
Returns the Cumulative Bivariate Normal Distribution (CBND) using Genz (2004) algorithm (this is the preferred method)
Parameters:
x : float,
y : float,
rho : float,
Returns: float.