benito_h
benito_h

Reputation: 560

Technical Analysis negative index

I'm writting technical indicators with Python via Numpy. Say, for convenience one has an np.array called Price filled with Stock-Prices and wants to calculate some example indicator like:

for i in range (0,len(Price)):
    Indicator[i]=2*Price[i]+3*Price[i-1]+ .... + 34*Price[i-10]

Up to now I would separately calculate the first 10 entries of Indicator since Price[-9]=Price[len(Price)-9] and start the for loop at 10. Is there a way to simplify this, e.g. automatically omit values with negative indices like Price[-5]?

Thank You

Upvotes: 3

Views: 161

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 77991

You can write your transformation in terms numpy.convolve. For example, if

>>> price
array([-1,  4,  5,  0, -5,  2, -4,  4, 20,  1])
>>> coef
array([10, -2,  1])

(where, just for simplicity, I am using only 3 elements instead of 10), then

coef[0] * price[t] + coef[1] * price[t-1] + coef[2] * price[t-2]

is what np.convolve calculates, and it also takes care of initial part of the series where we do not have 3 elements:

>>> np.convolve(coef, price)
array([-10,  42,  41,  -6, -45,  30, -49,  50, 188, -26,  18,   1])

as you see, for the 1st element -10 = 10 * -1, for the 2nd element: 42 = 10 * 4 + -2 * -1, and for, say, the 7th element: -49 = 10 * -4 + -2 * 2 + 1 * -5.

Upvotes: 1

Related Questions