Reference no: EM132360741
Question
Very new to Python and am trying to solve this classic data mining problem to find the average stock price from an external csv file and output it different external files. ( I pasted the prompt to the bottom of this text box) There are 6 columns in the csv file that I am iterating though to average the numbers. On the first iteration I can average it and write it to a new file just fine. On the second iteration I get this 'IndexError: list index out of range' error. I cannot figure out why it works the first time but stops in the averageData function. I attached my solution so far. Here is the error it produces:
Traceback (most recent call last):
File "...", line 63, in
main()
File "...", line 60, in main
columnAverage = averageData(dataList)
File "...", line 30, in averageData
firstMonth = list_of_tuples[0][0][-5:-3]
IndexError: list index out of range
In this project, we want to do some preliminary data mining of the prices of Apple stock. Your program will calculate the monthly average prices of Apple stock from 1984 to 2013. A file of Apple's daily stock's prices will be given to you, whose name is table.csv. This file could be opened by notepad or similar text editor, and is delimited by commas. If you open it with Excel, it will show you the data as a spreadsheet.
You must implement the following functions:def getInputDescriptor():
validFile = False
while(validFile == False):
fileName = input("Enter a valid CSV file")
if fileName == 'table.csv':
validFile = True
fp = open("table.csv")
return fp
def getDataList(file_object, column_number):
print('file_object', file_object)
print('column_number', column_number)
file_object.readline()
stockPrices = []
for column in file_object:
row = column.strip().split(",")
stockPrices.append((row[0], row[int(column_number)]))
print('stockPrices', stockPrices)
return stockPrices
def averageData(list_of_tuples):
averageList = []
firstMonth = list_of_tuples[0][0][-5:-3]
print(firstMonth)
total = 0
count = 0
for i in range(len(list_of_tuples) - 1):
if list_of_tuples[i][0][-5:-3] == firstMonth:
count += 1
price = float(list_of_tuples[i][1])
total += price
else:
avg = total / count
total = 0
count = 0
averageList.append((avg, list_of_tuples[i][0]))
firstMonth = list_of_tuples[i][0][-5:-3]
return averageList
def outputAverage(filename, average):
newFile = open(filename, 'w')
for i in average:
price = i[0]
formattedPrice = "{0:.2f}".format(price)
newFile.write('{:15}{:15}\n'.format(formattedPrice, i[1]))
# close(filename)
def main():
fp = getInputDescriptor()
for i in range(1,7):
print(i)
dataList = getDataList(fp, i)
columnAverage = averageData(dataList)
outputAverage('data_' + str(i) + '.txt', columnAverage)
main()