TradingView
RicardoSantos
22 дек 2016 г., 12:13

Function Covariance 

GOLD / U.S. DOLLARICE

Описание

Covariance Function as described here:
investopedia.com/articles/financial-theory/11/calculating-covariance.asp

can be used for example to calculate Beta:
tradingview.com/script/aqsB5OHC-BETA/
Комментарии
MikeColfs71
Feel really stupid covariance is a static function of array
MikeColfs71
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
RicardoSantos
@MikeColfs71, yes you could, this was done before the array implementation tho :)
MikeColfs71
@RicardoSantos, Should have kept up with progress!! One question though would you have to create two separate series for returns change(close)/close[1] then check for covariance or with raw close values?
RicardoSantos
@MikeColfs71, tradingview.com/pine-script-reference/v4/
you only need to add the values to 2 different series.
MikeColfs71
@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?
RicardoSantos
@MikeColfs71,
var float[] A = array.new_float(0) if array.size(A) > X a = array.pop(A) array.unshift(A, newvalue)
MikeColfs71
@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.
MikeColfs71
@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[1]*100 //Caculate returns for new candle
TotB=change(Ix)/Ix[1]*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)
RicardoSantos
Ещё