0

I am having an issue and seem to not understand the concept on looping thru an array. My goal is divide each value in my array by the preceding value. Sort of like an i / i-1

I am dividing closing price stock data. My goal is to then store that value into a new array.

An example of stock data could be [1000, 1002, 1008, 999] Output should look like [1, 1.002, 1.005988, 0.99107]

Here is my code

date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile, delimiter=',', unpack=True,
                                                      converters={ 0: mdates.strpdate2num('%Y%m%d')})

normalizedData = []
    for i in closep:
    na_normalized_price = closep/closep[i-1]
    print na_normalized_price
    normalizedData.append(na_normalized_price)

my two issues are as follows:

  1. It doesn't stop dividing - so I'm guessing I will need a count of some sort to end the loop

    error: Traceback (most recent call last): File "C:\Users\antoniozeus\Desktop\BuyAndHold.py", line 31, in na_normalized_price = closep/closep[i-1] IndexError: index out of bounds

  2. I dont believe I am understanding how to append in numpy

2
  • Standard recommendation: if you're working with time series, you should check out pandas; it makes things you haven't even thought of yet much easier. Commented Mar 23, 2014 at 19:47
  • good point - my only issue is that I am learning bits of pieces and trying to paste them together... not the best way but its a slow process for me to learn how to program in python. But definitely you are right.. thank you Commented Mar 23, 2014 at 22:01

1 Answer 1

2

Remember that numpy operations are by element.

So just divide the array by one that has been offset;

In [1]: import numpy as np

In [2]: a = np.array([1000, 1002, 1008, 999])

In [3]: b = a[1:]

In [4]: b/a[:-1]
Out[4]: array([ 1.002     ,  1.00598802,  0.99107143])

In [5]: np.insert(b/a[:-1], 0, 1.0)
Out[5]: array([ 1.        ,  1.002     ,  1.00598802,  0.99107143])
Sign up to request clarification or add additional context in comments.

2 Comments

very nicely done - i kept thinking i needed a for loop but you are correct... thank you for helping with this
You're welcome! Have a good look at the numpy reference manual, especially the array manipulation routines. You'll find lots of interesting functions there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.