0

I am trying to calculate the Average True Range of a data series which has been read and parsed from a .csv file. my code is as follows:

import datetime
import time
import matplotlib.pyplot as plt
import numpy as np

fhand = open('C:\Users\Stuart\Desktop\FX Programming\EURUSD_hour.csv', 'r')



for line in fhand:
    line = line.split(',') 
    fxpair, _date, _time, _open, _high, _low, _close = line[0], line[1], line[2], line[3], float(line[4]), float(line[5]), float(line[6])
    date_time = datetime.datetime.strptime('{} {}'.format(_date.partition(' ')[0], _time),'%Y%m%d %H:%M:%S')



#define Average True Range function    
def TR(d,c,h,l,o,yc):
    x = h-l
    y = abs(h-yc)
    z = abs(l-yc)

    print x
    print y
    print z

    if y <= x >= z:
        TR = x
    elif x <= y >= z:
        TR = y
    elif x <= z >= y:
        TR = z

    print d, TR
    return d, TR

x = 1

TRDates = []
TrueRanges = []

while x < len(_date):
    TRDate, TrueRange = TR(_date[x],_close[x],_high[x],_low[x],_open[x],_close[x-1])
    TRDates.append(TRDate)
    TrueRanges.append(TrueRange)
    x+=1   

def ExpMovingAverage(values, window):
    weights = np.exp(np.linspace(-1., 0., window))
    weights /= weights.sum()
    a =  np.convolve(values, weights, mode='full')[:len(values)]
    a[:window] = a[window]
    return a


print len(TrueRanges)
ATR = ExpMovingAverage(TrueRanges,14)

print ATR

However I am getting the following error message:

     46 while x < len(line):
---> 47     TRDate, TrueRange = TR(_date[x],_close[x],_high[x],_low[x],_open[x],_close[x-1])
     48     TRDates.append(TRDate)
     49     TrueRanges.append(TrueRange)

TypeError: 'float' object has no attribute '__getitem__'

So there is obviously something wrong with the while statement, and it isnt iterating over the _date like I want it to. I have also tried using date_time instead of _date but then I get:

---> 46 while x < len(date_time):
     47     TRDate, TrueRange = TR(date_time[x],_close[x],_high[x],_low[x],_open[x],_close[x-1])
     48     TRDates.append(TRDate)

TypeError: object of type 'datetime.datetime' has no len() 

Can someone help me to get this working?

I have a very similar code which I have pasted below that actually works, which uses a different text file for data and unpacks it a different way. Can someone help me reconcile the two so that the top code works?

import numpy as np


sampleData = open('C:\\Users\\Stuart\\Desktop\\FX Programming\\sampleData.txt','r').read()
splitData = sampleData.split('\n')

date,closep,highp,lowp,openp,volume = np.loadtxt(splitData, delimiter=',',unpack=True)

def TR(d,c,h,l,o,yc):
    x = h-l
    y = abs(h-yc)
    z = abs(l-yc)

    print x
    print y
    print z

    if y <= x >= z:
        TR = x
    elif x <= y >= z:
        TR = y
    elif x <= z >= y:
        TR = z

    print d, TR
    return d, TR

x = 1

TRDates = []
TrueRanges = []

while x < len(date):
    TRDate, TrueRange = TR(date[x],closep[x],highp[x],lowp[x],openp[x],closep[x-1])
    TRDates.append(TRDate)
    TrueRanges.append(TrueRange)
    x+=1



################

def ExpMovingAverage(values, window):
    weights = np.exp(np.linspace(-1., 0., window))
    weights /= weights.sum()
    a =  np.convolve(values, weights, mode='full')[:len(values)]
    a[:window] = a[window]
    return a


print len(TrueRanges)
ATR = ExpMovingAverage(TrueRanges,14)

print ATR
1
  • 1
    All that error message means is that one of the inputs to TR, which you attempt to index with [x] is a number, not an array or list. Before jumping to using TR, make sure that the for line in fhand: block is producing the desired values (lists of numbers?). Off hand it looks like those variables might be strings. Commented Jul 10, 2014 at 16:19

1 Answer 1

1

In the code that works, high low and close are all arrays so you can index them by date. For example (I used a list instead of an array, but it's similar):

hi = [10, 11, 12]
print hi[0]
# 10

In your code you're looping over your file, converting these values to float and then discarding them. Here is a simple example to demonstrate:

for value in ['10', '11', '12']
    x = float(value)
print x
# 12

Notice that each assignment replaces the existing x and sets x to a new float. When you finally print x you get the last thing it was assigned to. You need to rewrite the parsing of your text file to save all the values. Maybe something like:

x = []
for value in ['10', '11', '12']
    x.append(float(value))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I have changed my code to append each individual "open, high, low, close, date" to a separate array o = [], h = [], l = [] etc. Now I manage to get past that line, but encounter an "index out of bounds" error on the line ---> 61 a[:window] = a[window]. But i guess that is a question for another page...thanks very much for your help!

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.