# Function Covariance

1302 views
Covariance Function as described here:
http://www.investopedia.com/articles/fin...

can be used for example to calculate Beta:
Open-source Skript

Ganz im Sinne von TradingView hat der Autor dieses Skripts es als Open-Source veröffentlicht, damit Trader es verstehen und überprüfen können. Ein Hoch auf den Autor! Sie können es kostenlos verwenden, aber die Wiederverwendung dieses Codes in einer Publikation unterliegt den Hausregeln. Sie können das Skript den Favoriten hinzufügen, um es auf dem Chart zu verwenden.

Möchten Sie dieses Skript auf einem Chart verwenden?

## Kommentare

Feel really stupid covariance is a static function of array
Antworten
Also could you use the array functionality to take processing cycles out of for loop i.e. do the suming at the end using the instance function array.sum..... just do the multiplication/assignment
Antworten
MikeColfs71
@MikeColfs71, yes you could, this was done before the array implementation tho :)
Antworten
RicardoSantos
@RicardoSantos, Should have kept up with progress!! One question though would you have to create two separate series for returns change(close)/close then check for covariance or with raw close values?
Antworten
MikeColfs71
Antworten
RicardoSantos
@RicardoSantos, I suppose you could also optimize code by pushing and shifting on each candle (global array) rather than reloading the array on every candle?
Antworten
MikeColfs71
@MikeColfs71,
```var float[] A = array.new_float(0)
if array.size(A) > X
a = array.pop(A)
array.unshift(A, newvalue)
```
Antworten
RicardoSantos
@RicardoSantos, between candles your adding the new candle index getting rid of initial index and reusing the rest to recalculate covariance. I presume X would represent the period variable over which your testing.
Antworten
RicardoSantos
@RicardoSantos, So to use above to calculate beta, I could try the following
study("Beta",overlay=false)
src = input(defval=close,title="Source",type=input.source)
period=input(defval=20,title="Period",type=input.integer)
index = input(defval="AMEX:SPY",title="Symbol",type=input.symbol)

var float A = array.new_float(0)
var float B = array.new_float(0)//Declare 2 global arrays to hold returns

//////////Using correlation/stdev
Ix=security(index,timeframe.period,close)

TotA=change(close)/close*100 //Caculate returns for new candle
TotB=change(Ix)/Ix*100

array.push(A,TotA) //add new return data for this candle
array.push(B,TotB)
if array.size(A) >period //are the arrays bigger than lookback period?
array.shift(A)
array.shift(B)

cv2=array.covariance(A,B) //recalculate new covariance

beta=cv2/array.variance(B) //recalculate new beta/variance for index

plot(beta,title="beta",color=color.red)
Antworten
MikeColfs71
Antworten