FunctionMatrixCovarianceLibrary "FunctionMatrixCovariance"
In probability theory and statistics, a covariance matrix (also known as auto-covariance matrix, dispersion matrix, variance matrix, or variance–covariance matrix) is a square matrix giving the covariance between each pair of elements of a given random vector.
Intuitively, the covariance matrix generalizes the notion of variance to multiple dimensions. As an example, the variation in a collection of random points in two-dimensional space cannot be characterized fully by a single number, nor would the variances in the `x` and `y` directions contain all of the necessary information; a `2 × 2` matrix would be necessary to fully characterize the two-dimensional variation.
Any covariance matrix is symmetric and positive semi-definite and its main diagonal contains variances (i.e., the covariance of each element with itself).
The covariance matrix of a random vector `X` is typically denoted by `Kxx`, `Σ` or `S`.
~wikipedia.
method cov(M, bias)
Estimate Covariance matrix with provided data.
Namespace types: matrix
Parameters:
M (matrix) : `matrix` Matrix with vectors in column order.
bias (bool)
Returns: Covariance matrix of provided vectors.
---
en.wikipedia.org
numpy.org
Covariance
Autoregressive Covariance Oscillator by TenozenWell to be honest I don't know what to name this indicator lol. But anyway, here is my another original work! Gonna give some background of why I create this indicator, it's all pretty much a coincidence when I'm learning about time series analysis.
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Well, the formula of Auto-covariance is:
E{(X(t)-(t) * (X(t-s)-(t-s))}= Y_s
But I don't multiply both values but rather subtract them:
E{(X(t)-(t) - (X(t-s)-(t-s))}= Y_s?
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
For arm_vald, the equation is as follows:
arm_vald = val_mu + mu_plus_lsm + et
val_mu --> mean of time series
mu_plus_lsm --> val_mu + LSM
et --> error term
As you can see, val_mu^2. I did this so the oscillator is much smoother.
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
After I get the value, I normalize them:
aco = Y_s? / arm_vald
So by this calculation, I get something like an oscillator!
(more details in the code)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
So how to use this indicator? It's so easy! If the value is above 0, we gonna expect a bullish response, if the value is below 0, we gonna expect a bearish response; that simple. Be aware that you should wait for the price to be closed before executing a trade.
Well, try it out! So far this is the most powerful indicator that I've created, hope it's useful. Ciao.
(more updates for the indicator if needed)
Beta ScreenerThis script allows you to screen up to 38 symbols for their beta. It also allows you to compare the list to not only SPY but also CRYPTO10! Features include custom time frame and custom colors.
Here is a refresher on what beta is:
Beta (β) is a measure of the volatility—or systematic risk—of a security or portfolio compared to the market as a whole (usually the S&P 500 ). Stocks with betas higher than 1.0 can be interpreted as more volatile than the S&P 500 .
Beta is used in the capital asset pricing model (CAPM), which describes the relationship between systematic risk and expected return for assets (usually stocks). CAPM is widely used as a method for pricing risky securities and for generating estimates of the expected returns of assets, considering both the risk of those assets and the cost of capital.
How Beta Works
A beta coefficient can measure the volatility of an individual stock compared to the systematic risk of the entire market. In statistical terms, beta represents the slope of the line through a regression of data points. In finance, each of these data points represents an individual stock's returns against those of the market as a whole.
Beta effectively describes the activity of a security's returns as it responds to swings in the market. A security's beta is calculated by dividing the product of the covariance of the security's returns and the market's returns by the variance of the market's returns over a specified period.
cov (a,b)/var(b)
Modified Covariance Autoregressive Estimator of Price [Loxx]What is the Modified Covariance AR Estimator?
The Modified Covariance AR Estimator uses the modified covariance method to fit an autoregressive (AR) model to the input data. This method minimizes the forward and backward prediction errors in the least squares sense. The input is a frame of consecutive time samples, which is assumed to be the output of an AR system driven by white noise. The block computes the normalized estimate of the AR system parameters, A(z), independently for each successive input.
Characteristics of Modified Covariance AR Estimator
Minimizes the forward prediction error in the least squares sense
Minimizes the forward and backward prediction errors in the least squares sense
High resolution for short data records
Able to extract frequencies from data consisting of p or more pure sinusoids
Does not suffer spectral line-splitting
May produce unstable models
Peak locations slightly dependent on initial phase
Minor frequency bias for estimates of sinusoids in noise
Order must be less than or equal to 2/3 the input frame size
Purpose
This indicator calculates a prediction of price. This will NOT work on all tickers. To see whether this works on a ticker for the settings you have chosen, you must check the label message on the lower right of the chart. The label will show either a pass or fail. If it passes, then it's green, if it fails, it's red. The reason for this is because the Modified Covariance method produce unstable models
H(z)= G / A(z) = G / (1+. a(2)z −1 +…+a(p+1)z)
You specify the order, "ip", of the all-pole model in the Estimation order parameter. To guarantee a valid output, you must set the Estimation order parameter to be less than or equal to two thirds the input vector length.
The output port labeled "a" outputs the normalized estimate of the AR model coefficients in descending powers of z.
The implementation of the Modified Covariance AR Estimator in this indicator is the fast algorithm for the solution of the modified covariance least squares normal equations.
Inputs
x - Array of complex data samples X(1) through X(N)
ip - Order of linear prediction model (integer)
Notable local variables
v - Real linear prediction variance at order IP
Outputs
a - Array of complex linear prediction coefficients
stop - value at time of exit, with error message
false - for normal exit (no numerical ill-conditioning)
true - if v is not a positive value
true - if delta and gamma do not lie in the range 0 to 1
true - if v is not a positive value
true - if delta and gamma do not lie in the range 0 to 1
errormessage - an error message based on "stop" parameter; this message will be displayed in the lower righthand corner of the chart. If you see a green "passed" then the analysis is valid, otherwise the test failed.
Indicator inputs
LastBar = bars backward from current bar to test estimate reliability
PastBars = how many bars are we going to analyze
LPOrder = Order of Linear Prediction, and for Modified Covariance AR method, this must be less than or equal to 2/3 the input frame size, so this number has a max value of 0.67
FutBars = how many bars you'd like to show in the future. This algorithm will either accept or reject your value input here and then project forward
Further reading
Spectrum Analysis-A Modern Perspective 1380 PROCEEDINGS OF THE IEEE, VOL. 69, NO. 11, NOVEMBER 1981
Related indicators
Levinson-Durbin Autocorrelation Extrapolation of Price
Weighted Burg AR Spectral Estimate Extrapolation of Price
Helme-Nikias Weighted Burg AR-SE Extra. of Price
Itakura-Saito Autoregressive Extrapolation of Price
Modified Covariance Autoregressive Estimator of Price
Correlation MeterThis script calculates the covariance and correlation coefficient between two markets using arrays.
Lookback: How many bars to perform the calculation on.
Source: Price source to calculate the correlation on.
Reference Market: The reference market to compare to the current market.
It's a simple indicator, but very useful for determining how correlated your preferred markets to trade are.
A correlation reading of +1.0 means the markets are perfectly positively correlated, a reading of -1.0 means they are perfectly negatively correlated.
If you're not sure what correlation & covariance are then Google the terms with "Investopedia" added to the end - they have some great definitions and examples.
For traders this can be useful for deciding how much risk to spread across two markets that have a high correlation, or how to hedge existing positions by trading a negatively correlated market.
For investors this can be useful for building a truly diversified portfolio.
If a market has a high positive correlation, the black line will stay above zero most of the time. If a market has a high negative correlation, the black line will stay below zero most of the time.
A market with no or little correlation will bounce between the two or hover around zero most of the time.
The example market above is comparing Apple's weekly price action to the S&P500's over the past 20 weeks. It has a high positive correlation as the black line is above zero most of the time.
Good luck with your trading!
Functions Allowing Series As Length - PineCoders FAQ█ WARNING
Improvements to the following Pine built-ins have deprecated the vast majority of this publication's functions, as the built-ins now accept "series int" `length` arguments:
ta.wma()
ta.linreg()
ta.variance()
ta.stdev()
ta.correlation()
NOTE
For an EMA function that allows a "series int" argument for `length`, please see `ema2()` in the ta library by TradingView .
█ ORIGINAL DESCRIPTION
Pinescript requires many of its built-in functions to use a simple int as their period length, which entails the period length cannot vary during the script's execution. These functions allow using a series int or series float for their period length, which means it can vary on each bar.
The functions shared in this script include:
Rolling sum: Sum(src,p)
Simple moving average: Sma(src,p)
Rolling variance: Variance(src,p)
Rolling standard deviation: Stdev(src,p)
Rolling covariance: Covariance(x,y,p)
Rolling correlation: Correlation(x,y,p)
If p is a float then it is rounded to the nearest int .
How to Use the Script
Most of the functions in the script are dependent on the Sma function. The Correlation function uses the Covariance and Stdev functions. Be sure you include all the required functions in your script.
Make sure the series you use as the length argument is greater than 0, else the functions will return na . When using a series as length argument, the following error might appear:
Pine cannot determine the referencing length of a series. Try using max_bars_back in the study or strategy function.
This can be frequent if you use barssince(condition) where condition is a relatively rare event. You can fix it by including max_bars_back=5000 in your study declaration statement as follows:
study("Title",overlay=true,max_bars_back=5000)
Example
The chart shows the Sma , Stdev , Covariance and Correlation functions. The Sma uses the closing price as input and bars as period length where:
bars = barssince(change(security(syminfo.tickerid,"D",close ,lookahead=true)))
The Stdev uses the closing price as input and bars + 9 as period length. The Covariance and Correlation use the closing price as x and bar_index as y , with bars + 9 as period length.
Look first. Then leap.
Function CovarianceCovariance Function as described here:
www.investopedia.com
can be used for example to calculate Beta:
Moving CO-covariance (covariance on covariance)This is Covariance on Covariance. It shows you how much a given covariance period has deviated from it mean over another defined period. Because it is a time series, It can allow you to spot changes in how covariance changes. You can apply trend lines, Fibonacci retracements, etc. This is also volume weighting covariance.
This is not a directional indicator nor is moving covariance. This is used for forecasting volatility. This must be used in conjunction with moving covariance.
Moving CovarianceCo-variance is a representation of the average percent data points deviate from there mean. A standard calculation of Co-variance uses One standard Deviation. Using the empirical rule, we can assume that about 68.26% of Data points lie in this range.
The advantage to plotting co variance as a time series is that it will show you how volatility of a trailing period changes. Therefore trend lines and other methods of analysis such as Fibonacci retracements could be applied in order to generate volatility targets.
For the purpose of this indicator I have the mean using a vwma derived from vwap. This makes this measurement of co-variance more sensitive to changes in volume, likewise are more representative a change in volatility, thus giving this indicator a "leading aspect".