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, I suppose you could also optimize code by pushing and shifting on each candle (global array) rather than reloading the array on every candle?
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
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