Capital Asset Pricing Model (CAPM) [Loxx]Capital Asset Pricing Model (CAPM) demonstrates how to calculate the Cost of Equity for an underlying asset using Pine Script. This script will only work on the monthly timeframe. While you can change the default inputs, you should study what CAPM is and how this works before doing so. This indicator pulls various types of data from SPY from various timeframes to calculate risk-free rates, market premiums, and log returns. Alpha and Beta are computed using the regression between underlying asset and SPY. This indicator only calculates on the most recent data. If you wish to change this, you'll have to save the script and make adjustments. A few examples where CAPM is used:
Used as the mu factor Geometric Brownian Motion models for options pricing and forecasting price ranges and decay
Calculating the Weighted Average Cost of Capital
Asset pricing
Efficient frontier
Risk and diversification
Security market line
Discounted Cashflow Analysis
Investment bankers use CAPM to value deals
Account firms use CAPM to verify asset prices and assumptions
Real estate firms use variations of CAPM to value properties
... and more
Details of the calculations used here
Rm is calculated using yearly simple returns data from SPY, typically this is just hard coded as 10%.
Rf is pulled from US 10 year bond yields
Beta and Alpha are pulled form monthly returns data of the asset and SPY
In the past, typically this data is purchased from investments banks whose research arms produce values for beta, alpha, risk free rate, and risk premiums. In 2022 ,you can find free estimates for each parameter but these values might not reflect the most current data or research.
History
The CAPM was introduced by Jack Treynor (1961, 1962), William F. Sharpe (1964), John Lintner (1965) and Jan Mossin (1966) independently, building on the earlier work of Harry Markowitz on diversification and modern portfolio theory. Sharpe, Markowitz and Merton Miller jointly received the 1990 Nobel Memorial Prize in Economics for this contribution to the field of financial economics. Fischer Black (1972) developed another version of CAPM, called Black CAPM or zero-beta CAPM, that does not assume the existence of a riskless asset. This version was more robust against empirical testing and was influential in the widespread adoption of the CAPM.
Usage
The CAPM is used to calculate the amount of return that investors need to realize to compensate for a particular level of risk. It subtracts the risk-free rate from the expected rate and weighs it with a factor – beta – to get the risk premium. It then adds the risk premium to the risk-free rate of return to get the rate of return an investor expects as compensation for the risk. The CAPM formula is expressed as follows:
r = Rf + beta (Rm – Rf) + Alpha
Therefore,
Alpha = R – Rf – beta (Rm-Rf)
Where:
R represents the portfolio return
Rf represents the risk-free rate of return
Beta represents the systematic risk of a portfolio
Rm represents the market return, per a benchmark
For example, assuming that the actual return of the fund is 30, the risk-free rate is 8%, beta is 1.1, and the benchmark index return is 20%, alpha is calculated as:
Alpha = (0.30-0.08) – 1.1 (0.20-0.08) = 0.088 or 8.8%
The result shows that the investment in this example outperformed the benchmark index by 8.8%.
The alpha of a portfolio is the excess return it produces compared to a benchmark index. Investors in mutual funds or ETFs often look for a fund with a high alpha in hopes of getting a superior return on investment (ROI).
The alpha ratio is often used along with the beta coefficient, which is a measure of the volatility of an investment. The two ratios are both used in the Capital Assets Pricing Model (CAPM) to analyze a portfolio of investments and assess its theoretical performance.
To see CAPM in action in terms of calculate WACC, see here for an example: finbox.com
Further reading
en.wikipedia.org
Blacksholes
BSM OPM 1973 w/ Continuous Dividend Yield [Loxx]Generalized Black-Scholes-Merton w/ Analytical Greeks is an adaptation of the Black-Scholes-Merton Option Pricing Model including Analytical Greeks and implied volatility calculations. The following information is an excerpt from Espen Gaarder Haug's book "Option Pricing Formulas". The options sensitivities (Greeks) are the partial derivatives of the Black-Scholes-Merton ( BSM ) formula. Analytical Greeks for our purposes here are broken down into various categories:
Delta Greeks: Delta, DDeltaDvol, Elasticity
Gamma Greeks: Gamma, GammaP, DGammaDSpot/speed, DGammaDvol/Zomma
Vega Greeks: Vega , DVegaDvol/Vomma, VegaP
Theta Greeks: Theta
Rate/Carry Greeks: Rho, Rho futures option, Carry Rho, Phi/Rho2
Probability Greeks: StrikeDelta, Risk Neutral Density
(See the code for more details)
Black-Scholes-Merton Option Pricing
The Black-Scholes-Merton model can be "generalized" by incorporating a cost-of-carry rate b. This model can be used to price European options on stocks, stocks paying a continuous dividend yield, options on futures, and currency options:
c = S * e^((b - r) * T) * N(d1) - X * e^(-r * T) * N(d2)
p = X * e^(-r * T) * N(-d2) - S * e^((b - r) * T) * N(-d1)
where
d1 = (log(S / X) + (b + v^2 / 2) * T) / (v * T^0.5)
d2 = d1 - v * T^0.5
b = r ... gives the Black and Scholes (1973) stock option model.
b = r — q ... gives the Merton (1973) stock option model with continuous dividend yield q. <== this is the one used for this indicator!
b = 0 ... gives the Black (1976) futures option model.
b = 0 and r = 0 ... gives the Asay (1982) margined futures option model.
b = r — rf ... gives the Garman and Kohlhagen (1983) currency option model.
Inputs
S = Stock price.
X = Strike price of option.
T = Time to expiration in years.
r = Risk-free rate
d = dividend yield
v = Volatility of the underlying asset price
cnd (x) = The cumulative normal distribution function
nd(x) = The standard normal density function
convertingToCCRate(r, cmp ) = Rate compounder
gImpliedVolatilityNR(string CallPutFlag, float S, float x, float T, float r, float b, float cm , float epsilon) = Implied volatility via Newton Raphson
gBlackScholesImpVolBisection(string CallPutFlag, float S, float x, float T, float r, float b, float cm ) = implied volatility via bisection
Implied Volatility: The Bisection Method
The Newton-Raphson method requires knowledge of the partial derivative of the option pricing formula with respect to volatility ( vega ) when searching for the implied volatility . For some options (exotic and American options in particular), vega is not known analytically. The bisection method is an even simpler method to estimate implied volatility when vega is unknown. The bisection method requires two initial volatility estimates (seed values):
1. A "low" estimate of the implied volatility , al, corresponding to an option value, CL
2. A "high" volatility estimate, aH, corresponding to an option value, CH
The option market price, Cm , lies between CL and cH . The bisection estimate is given as the linear interpolation between the two estimates:
v(i + 1) = v(L) + (c(m) - c(L)) * (v(H) - v(L)) / (c(H) - c(L))
Replace v(L) with v(i + 1) if c(v(i + 1)) < c(m), or else replace v(H) with v(i + 1) if c(v(i + 1)) > c(m) until |c(m) - c(v(i + 1))| <= E, at which point v(i + 1) is the implied volatility and E is the desired degree of accuracy.
Implied Volatility: Newton-Raphson Method
The Newton-Raphson method is an efficient way to find the implied volatility of an option contract. It is nothing more than a simple iteration technique for solving one-dimensional nonlinear equations (any introductory textbook in calculus will offer an intuitive explanation). The method seldom uses more than two to three iterations before it converges to the implied volatility . Let
v(i + 1) = v(i) + (c(v(i)) - c(m)) / (dc / dv (i))
until |c(m) - c(v(i + 1))| <= E at which point v(i + 1) is the implied volatility , E is the desired degree of accuracy, c(m) is the market price of the option, and dc/ dv (i) is the vega of the option evaluaated at v(i) (the sensitivity of the option value for a small change in volatility ).
Things to know
Only works on the daily timeframe and for the current source price.
You can adjust the text size to fit the screen
Black Scholes Option Pricing Model w/ Greeks [Loxx]The Black Scholes Merton model
If you are new to options I strongly advise you to profit from Robert Shiller's lecture on same . It combines practical market insights with a strong authoritative grasp of key models in option theory. He explains many of the areas covered below and in the following pages with a lot intuition and relatable anecdotage. We start here with Black Scholes Merton which is probably the most popular option pricing framework, due largely to its simplicity and ease in terms of implementation. The closed-form solution is efficient in terms of speed and always compares favorably relative to any numerical technique. The Black–Scholes–Merton model is a mathematical go-to model for estimating the value of European calls and puts. In the early 1970’s, Myron Scholes, and Fisher Black made an important breakthrough in the pricing of complex financial instruments. Robert Merton simultaneously was working on the same problem and applied the term Black-Scholes model to describe new generation of pricing. The Black Scholes (1973) contribution developed insights originally proposed by Bachelier 70 years before. In 1997, Myron Scholes and Robert Merton received the Nobel Prize for Economics. Tragically, Fisher Black died in 1995. The Black–Scholes formula presents a theoretical estimate (or model estimate) of the price of European-style options independently of the risk of the underlying security. Future payoffs from options can be discounted using the risk-neutral rate. Earlier academic work on options (e.g., Malkiel and Quandt 1968, 1969) had contemplated using either empirical, econometric analyses or elaborate theoretical models that possessed parameters whose values could not be calibrated directly. In contrast, Black, Scholes, and Merton’s parameters were at their core simple and did not involve references to utility or to the shifting risk appetite of investors. Below, we present a standard type formula, where: c = Call option value, p = Put option value, S=Current stock (or other underlying) price, K or X=Strike price, r=Risk-free interest rate, q = dividend yield, T=Time to maturity and N denotes taking the normal cumulative probability. b = (r - q) = cost of carry. (via VinegarHill-Financelab )
Things to know
This can only be used on the daily timeframe
You must select the option type and the greeks you wish to show
This indicator is a work in process, functions may be updated in the future. I will also be adding additional greeks as I code them or they become available in finance literature. This indictor contains 18 greeks. Many more will be added later.
Inputs
Spot price: select from 33 different types of price inputs
Calculation Steps: how many iterations to be used in the BS model. In practice, this number would be anywhere from 5000 to 15000, for our purposes here, this is limited to 300
Strike Price: the strike price of the option you're wishing to model
% Implied Volatility: here you can manually enter implied volatility
Historical Volatility Period: the input period for historical volatility ; historical volatility isn't used in the BS process, this is to serve as a sort of benchmark for the implied volatility ,
Historical Volatility Type: choose from various types of implied volatility , search my indicators for details on each of these
Option Base Currency: this is to calculate the risk-free rate, this is used if you wish to automatically calculate the risk-free rate instead of using the manual input. this uses the 10 year bold yield of the corresponding country
% Manual Risk-free Rate: here you can manually enter the risk-free rate
Use manual input for Risk-free Rate? : choose manual or automatic for risk-free rate
% Manual Yearly Dividend Yield: here you can manually enter the yearly dividend yield
Adjust for Dividends?: choose if you even want to use use dividends
Automatically Calculate Yearly Dividend Yield? choose if you want to use automatic vs manual dividend yield calculation
Time Now Type: choose how you want to calculate time right now, see the tool tip
Days in Year: choose how many days in the year, 365 for all days, 252 for trading days, etc
Hours Per Day: how many hours per day? 24, 8 working hours, or 6.5 trading hours
Expiry date settings: here you can specify the exact time the option expires
The Black Scholes Greeks
The Option Greek formulae express the change in the option price with respect to a parameter change taking as fixed all the other inputs. ( Haug explores multiple parameter changes at once .) One significant use of Greek measures is to calibrate risk exposure. A market-making financial institution with a portfolio of options, for instance, would want a snap shot of its exposure to asset price, interest rates, dividend fluctuations. It would try to establish impacts of volatility and time decay. In the formulae below, the Greeks merely evaluate change to only one input at a time. In reality, we might expect a conflagration of changes in interest rates and stock prices etc. (via VigengarHill-Financelab )
First-order Greeks
Delta: Delta measures the rate of change of the theoretical option value with respect to changes in the underlying asset's price. Delta is the first derivative of the value
Vega: Vegameasures sensitivity to volatility. Vega is the derivative of the option value with respect to the volatility of the underlying asset.
Theta: Theta measures the sensitivity of the value of the derivative to the passage of time (see Option time value): the "time decay."
Rho: Rho measures sensitivity to the interest rate: it is the derivative of the option value with respect to the risk free interest rate (for the relevant outstanding term).
Lambda: Lambda, Omega, or elasticity is the percentage change in option value per percentage change in the underlying price, a measure of leverage, sometimes called gearing.
Epsilon: Epsilon, also known as psi, is the percentage change in option value per percentage change in the underlying dividend yield, a measure of the dividend risk. The dividend yield impact is in practice determined using a 10% increase in those yields. Obviously, this sensitivity can only be applied to derivative instruments of equity products.
Second-order Greeks
Gamma: Measures the rate of change in the delta with respect to changes in the underlying price. Gamma is the second derivative of the value function with respect to the underlying price.
Vanna: Vanna, also referred to as DvegaDspot and DdeltaDvol, is a second order derivative of the option value, once to the underlying spot price and once to volatility. It is mathematically equivalent to DdeltaDvol, the sensitivity of the option delta with respect to change in volatility; or alternatively, the partial of vega with respect to the underlying instrument's price. Vanna can be a useful sensitivity to monitor when maintaining a delta- or vega-hedged portfolio as vanna will help the trader to anticipate changes to the effectiveness of a delta-hedge as volatility changes or the effectiveness of a vega-hedge against change in the underlying spot price.
Charm: Charm or delta decay measures the instantaneous rate of change of delta over the passage of time.
Vomma: Vomma, volga, vega convexity, or DvegaDvol measures second order sensitivity to volatility. Vomma is the second derivative of the option value with respect to the volatility, or, stated another way, vomma measures the rate of change to vega as volatility changes.
Veta: Veta or DvegaDtime measures the rate of change in the vega with respect to the passage of time. Veta is the second derivative of the value function; once to volatility and once to time.
Vera: Vera (sometimes rhova) measures the rate of change in rho with respect to volatility. Vera is the second derivative of the value function; once to volatility and once to interest rate.
Third-order Greeks
Speed: Speed measures the rate of change in Gamma with respect to changes in the underlying price.
Zomma: Zomma measures the rate of change of gamma with respect to changes in volatility.
Color: Color, gamma decay or DgammaDtime measures the rate of change of gamma over the passage of time.
Ultima: Ultima measures the sensitivity of the option vomma with respect to change in volatility.
Dual Delta: Dual Delta determines how the option price changes in relation to the change in the option strike price; it is the first derivative of the option price relative to the option strike price
Dual Gamma: Dual Gamma determines by how much the coefficient will changedual delta when the option strike price changes; it is the second derivative of the option price relative to the option strike price.
Related Indicators
Cox-Ross-Rubinstein Binomial Tree Options Pricing Model
Implied Volatility Estimator using Black Scholes
Boyle Trinomial Options Pricing Model
Implied Volatility Estimator using Black Scholes [Loxx]Implied Volatility Estimator using Black Scholes derives a estimation of implied volatility using the Black Scholes options pricing model. The Bisection algorithm is used for our purposes here. This includes the ability to adjust for dividends.
Implied Volatility
The implied volatility (IV) of an option contract is that value of the volatility of the underlying instrument which, when input in an option pricing model (such as Black–Scholes), will return a theoretical value equal to the current market price of that option. The VIX , in contrast, is a model-free estimate of Implied Volatility. The latter is viewed as being important because it represents a measure of risk for the underlying asset. Elevated Implied Volatility suggests that risks to underlying are also elevated. Ordinarily, to estimate implied volatility we rely upon Black-Scholes (1973). This implies that we are prepared to accept the assumptions of Black Scholes (1973).
Inputs
Spot price: select from 33 different types of price inputs
Strike Price: the strike price of the option you're wishing to model
Market Price: this is the market price of the option; choose, last, bid, or ask to see different results
Historical Volatility Period: the input period for historical volatility ; historical volatility isn't used in the Bisection algo, this is to serve as a comparison, even though historical volatility is from price movement of the underlying asset where as implied volatility is the volatility of the option
Historical Volatility Type: choose from various types of implied volatility , search my indicators for details on each of these
Option Base Currency: this is to calculate the risk-free rate, this is used if you wish to automatically calculate the risk-free rate instead of using the manual input. this uses the 10 year bold yield of the corresponding country
% Manual Risk-free Rate: here you can manually enter the risk-free rate
Use manual input for Risk-free Rate? : choose manual or automatic for risk-free rate
% Manual Yearly Dividend Yield: here you can manually enter the yearly dividend yield
Adjust for Dividends?: choose if you even want to use use dividends
Automatically Calculate Yearly Dividend Yield? choose if you want to use automatic vs manual dividend yield calculation
Time Now Type: choose how you want to calculate time right now, see the tool tip
Days in Year: choose how many days in the year, 365 for all days, 252 for trading days, etc
Hours Per Day: how many hours per day? 24, 8 working hours, or 6.5 trading hours
Expiry date settings: here you can specify the exact time the option expires
*** the algorithm inputs for low and high aren't to be changed unless you're working through the mathematics of how Bisection works.
Included
Option pricing panel
Loxx's Expanded Source Types
Related Indicators
Cox-Ross-Rubinstein Binomial Tree Options Pricing Model