Statistical and Financial MetricsGood morning traders!
This time I want to share with you a little script that, thanks to the use of arrays, allows you to have interesting statistical and financial insights taken from the symbol on chart and compared to those of another symbol you desire (in this case the metrics taken from the perpetual future ETHUSDT are compared to those taken from the perpetual future BTCUSDT, used as a proxy for the direction of cryptocurrency market)
By enabling "prevent repainting", the data retrieved from the compared symbol won't be on real time but they will static since they will belong to the previous closed candle
Here are the metrics you can have by storing data from a variable period of candles (by default 51):
✓ Variance (of the symbol on chart in GREEN; of the compared symbol in WHITE)
✓ Standard Deviation (of the symbol on chart in OLIVE; of the compared symbol in SILVER)
✓ Yelds (of the symbol on chart in LIME; of the compared symbol in GRAY) → yelds are referred to the previous close, so they would be calculated as the the difference between the current close and the previous one all divided by the previous close
✓ Covariance of the two datasets (in BLUE)
✓ Correlation coefficient of the two datasets (in AQUA)
✓ β (in RED) → this insight is calculated in three alternative ways for educational purpose (don't worry, the output would be the same).
WHAT IS BETA (β)?
The BETA of an asset can be interpretated as the representation (in relative terms) of the systematic risk of an asset: in other terms, it allows you to understand how big is the risk (not eliminable with portfolio diversification) of an asset based on the volatilty of its yelds.
We say that this representation is made in relative terms since it is expressed according to the market portfolio: this portfolio is hypothetically the portfolio which maximizes the diversification effects in order to kill all the specific risk of that portfolio; in this way the standard deviation calculated from the yelds of this portfolio will represent just the not-eliminable risk (the systematic risk), without including the eliminable risk (the specific risk).
The BETA of an asset is calculated as the volatilty of this asset around the volatilty of the market portfolio: being more precise, it is the covariance between the yelds of the current asset and those of the market portfolio all divided by the variance of the yelds of market portfolio.
Covariance is calculated as the product between correlation coefficient, standard deviation of the first dataset and standard deviation of the second asset.
So, as the correlation coefficient and the standard deviation of the yelds of our asset increase (it means that the yelds of our asset are very similiar to those of th market portfolio in terms of sign and intensity and that the volatility of these yelds is quite high), the value of BETA increases as well
According to the Capital Asset Pricing Model (CAPM) promoted by William Sharpe (the guy of the "Sharpe Ratio") and Harry Markowitz, in efficient markets the yeld of an asset can be calculated as the sum between the risk-free interest rate and the risk premium. The risk premium of the specific asset would be the risk premium of the market portfolio multiplied with the value of beta. It is simple: if the volatility of the yelds of an asset around the yelds of market protfolio are particularly high, investors would ask for a higher risk premium that would be translated in a higher yeld.
In this way the expected yeld of an asset would be calculated from the linear expression of the "Security Market Line": r_i = r_f + β*(r_m-r_f)
where:
r_i = expected yeld of the asset
r_f = risk free interest rate
β = beta
r_m = yeld of market portfolio
I know that considering Bitcoin as a proxy of the market portfolio involved in the calculation of Beta would be an inaccuracy since it doesn't have the property of maximum diversification (since it is a single asset), but there's no doubt that it's tying the prices of altcoins (upward and downward) thanks to the relevance of its dominance in the capitalization of cryptocurrency market. So, in the lack of a good index of cryptocurrencies (as the FTSE MIB for the italian stock market), and as long the dominance of Bitcoin will persist with this intensity, we can use Bitcoin as a proxy of the market portfolio
Beta
BETA (against any benchmark index - defaulted to NSE:NIFTY)Beta value of a stock relative to benchmark index. Thanks to Ricardo Santos for the original script. This script is adapted from it.
To understand beta, refer Investopedia link: www.investopedia.com
A beta value of 1 means the stock is directly correlated to benchmark index - volatility would be same as overall market.
Beta value less than 1 and greater than 0 means the stock is less volatile than the market.
Beta value more than 1 would mean the stock is more volatile than the market.
A beta value of 1.2 would roughly translate to the stock being 20% more volatile than the overall market.
A negative beta value indicates the stock is inversely correlated to market.
In the example chart, you can see the Beta value change in NSE:RELIANCE with respect to NSE:NIFTY.
Fama-French 3 Factor ModelFama-French 3 Factor Model
Extension of the Capital Asset Pricing Model (CAPM)
CAPM
Ra = Rfr +
where,
Ra = Return of the Asset
Rfr = Risk-Free Rate
βa = Beta Coefficient of the Asset
Rm - Rfr = Market Risk Premium
Fama-French 3 Factor
r = rf + β1*(rm - rf) + β2(smh) +β3(hml)
r = Expected rate of return
rf = Risk-free rate
ß = Factor’s coefficient (sensitivity)
(rm – rf) = Market risk premium
SMB (Small Minus Big) = Historic excess returns of small-cap companies over large-cap companies
HML (High Minus Low) = Historic excess returns of value stocks (high book-to-price ratio) over growth stocks (low book-to-price ratio)
Small is set to $EWSC
Invesco S&P SmallCap 600® Equal Weight ETF
Big is set to $EQLW
Invesco S&P 100 Equal Weight ETF
High is set to $IUSV
iShares Core S&P US Value ETF
Low is set to $IUSG
iShares Core S&P US Growth ETF
returns selections
'returns'
'logarithmic returns' (use for realized (historical) returns)
'geometric returns' (compounded returns)
risk-free rate selections:
$DTB3
$DGS2
$DGS5
$DGS10
$DGS30
tf = primary time-frame
rtf = reference time-frame
Realized Variables for Options ComparisonThese variables can be used in comparison with the implied volatility of options.
Variables:
Realized Volatility
mathematical notation lowercase 'sigma'
Realized Variance
mathematical notation lowercase 'sigma' squared
Realized Beta
mathematical notation lowercase 'beta'
Timeframes:
Yearly = 250 or 365
Quarterly = 50 or 90
Monthly = 20 or 30
Important Note:
Options Contract Expiry = barmerge.lookahead_on
"Merge strategy for the requested data position. Requested barset is merged with current barset in the order of sorting bars by their opening time. This merge strategy can lead to undesirable effect of getting data from "future" on calculation on history. This is unacceptable in backtesting strategies, but can be useful in indicators."
[ All other timeframes barmerge.lookahead is disabled.
Risk Metrics: Crypto VersionRisk Metrics for Crypto.
Market can be set to BTCUSD, BTCEUR, BTCCHF, BTCGBP, BTC1!, BTC2!, SPX, and DTB3
Beta
Correlation
Standard Deviation
Variance
R-squared
Risk Metrics: beta 'β', correl 'ρxy', stdev 'σ', variance 'σ²'Portfolio Risk Metrics (Part I):
beta 'β'
The beta coefficient can be interpreted as follows:
β =1 exactly as volatile as the market
β >1 more volatile than the market
β <1>0 less volatile than the market
β =0 uncorrelated to the market
β <0 negatively correlated to the market
excerpt from the Corporate Finance Institute
correlation coefficient 'ρxy'
The correlation coefficient is a value that indicates the strength of the relationship between variables.
The coefficient can take any values from -1 to 1. The interpretations of the values are:
-1: Perfect negative correlation. The variables tend to move in opposite directions
(i.e., when one variable increases, the other variable decreases).
0: No correlation. The variables do not have a relationship with each other.
1: Perfect positive correlation. The variables tend to move in the same direction
(i.e., when one variable increases, the other variable also increases).
excerpt from the Corporate Finance Institute
standard deviation 'σ'
68% of returns will fall within 1 standard deviation of the arithmetic mean
95% of returns will fall within 2 standard deviations of the arithmetic mean
99% of returns will fall within 3 standard deviations of the arithmetic mean
excerpt from Corporate Finance Institute
variance 'σ²'
In investing, variance is used to compare the relative performance of each asset in a portfolio.
Because the results can be difficult to analyze, standard deviation is often used instead of variance.
In either case, the goal for the investor is to improve asset allocation.
excerpt from Investopedia
Portfolio Metrics = α(Jensen's), β, CAPM(Ra), Sharpe, TreynorPortfolio Metrics...
Standard Deviation
Jensen's Alpha
Beta
Expected Return (CAPM, Ra)
Sharpe Ratio
Treynor Ratio
Alpha & BetaAlpha & Beta Indicators for Portfolio Performance
β = Σ Correlation (RP, RM) * (σP/σM)
α P = E(RP) –
Where,
RP = Portfolio Return (or Investment Return)
RM = Market Return (or Benchmark Index)
RF = Risk-Free Rate
How to use the Indicator
RM = SPX (Default)
The Market Return for the indicator has the options of $SPX, $NDX, or $DJI (S&P 500, Nasdaq 100, Dow 30)
RF = FRED: DTB3
The Risk-Free Rate in the Indicator is set to the 3-Month Treasury Bill: Secondary Market Rate
The Default Timeframe is 1260 or 5-Years (252 Trading Days in One Year)
RP = The symbol you enter
HOWEVER , you can determine your portfolio value by following the following directions below.
Note: I am currently working on an indicator that will allow you to insert the weights of your positions.
Complete Portfolio Analysis Directions
You will first need...
a) spreadsheet application - Google Sheets is Free, but Microsoft Excel will convert ticker symbols to Stocks and Retrieve Data.
b) your current stock tickers, quantity of shares, and last price information
In the spreadsheet,
In the first column list the stock tickers...
AMZN
AAPL
TSLA
In the second column list the quantity of shares you own...
5
10
0.20
In the third column insert the last price
Excel: Three tickers will automatically give you the option to "Convert to Stocks",
after conversion, click once on cell and click the small tab in the upper right-hand of the highlighted cell.
Click the tab and a menu pops up
Find "Price", "Price Extended-Hours", or "Previous Close"...
$3,284.72
$497.48
$2,049.98
Next, multiply the number of shares by the price (Stock Market Value)
Excel: in fourth column type "=(B1*C1)", "=(B2*C2)", "=(B3*C3)"...
= $16,423.60
= $4,974.80
= $410.00
add the three calculated numbers together or click "ΣAutoSum" (Portfolio Market Value)
= $21,808.40
Last, divide the market value of AMZN ($16,423.60) by the Portfolio Market Value ($21,808.40) for each of the stocks.
= 0.7531
= 0.2281
= 0.0188
These values are the weight of the stock in your portfolio.
Go back to TradingView
Enter into the "search box" the following...
AMZN*0.7531 + AAPL*0.2281 + TSLA*0.0188
and click Enter
Now you can use the "Alpha & Beta" Indicator to analyze your entire portfolio!
Beta 252 Days (NIFTY 50) by AkshayThe script derives the Beta Value of 252 days of a stock with Benchmark Index NIFTY 50. Note:- I have edited the script using an existing Beta script by Ricardo Santos. Thank you to him! :)
Hello VWAP "Beta"This is my 1st indicator, and my attention is to plot the VWAP "Volume-weighted average price" using the SMA "Simple Moving Average" over time... IE over the last 50,100,200 bars and just the VWAP... All of them in just one line... I have made it when I have been using the BTC/US chart, but it should work for stocks/forex or any other chart that you want to use...
I am not completely sure about this indicator and I do want to add more to this, that is how come I am posting to the community to show what I have done and people can use it and if they are open to it give me feedback or tips to make it better...
Happy trading...
SPY RelativeShows an instrument's sentiment in a day (or week) compared to the market (SPY default). The Red line shows bearish sentiment compared to the market and the green is bullish. Technically this works like a proxy for Alpha/Beta factor.
Correlation & BetaDisplay the correlation coefficient and/or Beta of an asset to a specified market.
Options to:
- Specify market (S&P500 futures by default)
- Display one or other metrics
- Modify assessment period (200 bars by default)
- Calculate on price, returns or log-returns
Formula for Day Trading NSEINDAtesting script. please try at your own risk. don't claim if any damage
Multi-Asset Correlation CoeffThis is just a modified correlation coefficient indicator that shows the correlation coefficient between five different assets and the one on the chart.
Cryptocurrency α / β (Alpha and Beta)Alpha and Beta for cryptocurrency. Custom input for other symbols.
Bitfinex USD Pairs: Betas and Correlations [checkm8]Hello and welcome to my beta and correlation indicator!
This indicator is meant to be used to assess trading alternatives to BTCUSD on Bitfinex, examining alt-USD pairs that can be traded on margin. This list is as follows:
ETHUSD
LTCUSD
EOSUSD
NEOUSD
OMGUSD
XRPUSD
IOTUSD
BCHUSD
SANUSD
ETPUSD
ETCUSD
XMRUSD
ZECUSD
DSHUSD
Before dwelling further on the script, let's revisit the definitions of beta and correlation:
Beta is a statistical measure of a %-change in an asset relative to a 1% change in a benchmark. In our case - this is BTCUSD. For example, if the beta is 1.5, it means that the particular asset moves 1.5% in the same direction as the 1% change of the benchmark. If the beta is negative, the asset is moving in opposite direction of the benchmark. Note: beta is not confined to any range.
Correlation is a statistical measure of the relationship between two assets, from a range of +1 to -1, where a score of +1 implies perfect positive correlation (prices move in the same direction), -1 implies perfect negative correlation (inverse relationship), and 0 implies no relationship in price changes.
For the calculations, BITFINEX:BTCUSD is used as the benchmark.
Through the script's settings:
You can select whether to plot betas or the correlations
You can select the desired length to be used in the measure of beta and correlations
You can enable smoothing for less choppy results. This is accompanied by options to modify the smoothing length and the smoothing method, where SMA, EMA, RMA, and WMA are available.
You can enable and disable individual alt pairs from being displayed (ie. if you do not want LTCUSD plotted, you can turn it off)
Below is an example of the correlation setting.
I would recommend using a smoothing input of 3-6, on SMA, and the 4-hour timeframe for good results. I use this indicator for help in deciding what alt pairs to trade on a particular day, where you will want to trade alts with the highest correlations. Note: be weary of less liquid markets, such as ETP and SAN.
Also note: the labels shown in the snapshot are for presentation purposes only. You can enable Indicator Labels by right clicking the oscillator -> "Price Scale" -> "Indicator Labels".
Please let me know if you have any questions, suggestions, or concerns.
Happy trading!
For additional information as to why you should be using this indicator and trading alts instead of BTCUSD, please refer to my study:
Anomaly Indicator V1.1 The Anomaly Indicator is an idea I recently come up with. Its very simple, yet it can be extremely useful. The Anomaly indicator detects the current and general trend channels. When the yellow line which is the current channel, exits the general channel this will usually mean an anomaly. Anomalies can vary within meaning, from a trend reversal, a market change (trending or rangebound) and lastly it can also give you an entering point. You can even use it to know the volatility of the market.
This is a very early version of the indicator and has pre-set values. I personally use it among a 5 minute chart for daytrading.
NOTE : Have in mind my indicator as ny other is not perfect, it might give fake signals. I suggest using Williams Alligator, and RSI with it. Best of luck. Follow my predictions under your own risk.
Beta coefficientClassic Beta coefficient by the method of Yahoo. Use only on monthly TF with Beta window = 36
You can use any benchmark, for example DIA / SPY / QQQ / DAX / BTCUSD / GC1! / etc
420_betaA newer, more customizable version of the holy grail script I published for silver before.
This script is a work in progress (as was the last version) and although I have been trying to refine this script I would still only classify it in the early stages of development; unlike my previous Euro Dollar strength holy grail script which was designed to work with only the EU pair or the XAGUSD spread script that was designed to work only with silver traded in USD, this script is designed to work with ANY commodity traded in USD, EUR, GBP, or JPY.
In this version I have tried to make smaller time frames work (60 - 240 supported now?) and added a lot of options for average type to be considered in the basket. Not every average created equally though, so I need feedback still etc...
I have also added the ability to specify what the 'basis currency' is. For example XAUUSD --> USD is basis currency. XAGGBP --> GBP is basis currency.
The only supported currencies at the moment are USD, EUR, GBP, and JPY (case sensitive)
If someone requests another (CHF, CAD, etc) I can add that as well.
I have an alert centric version (study, not a strategy) that I am trying out as well on my Euro dollar strength script and this 420_beta script
If you want access, feel free to ask, but as this is still in beta and I'm looking for feedback I'll probably only provide this script to those who have a record of trading commodities here on TV (aka published an idea on XAUUSD, XAGUSD, USOIL, Copper, etc...)
- Snoop
Cyclical vs. Defensive Sector Alphashows mean excess returns of defensive and cyclical sectors vs. S&P500