Calculate the monthly average prices of apple stock

Assignment Help Python Programming
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()

Reference no: EM132360741

Questions Cloud

Write a function called backwards that takes in one string : Write a function called backwards that takes in one string as a parameter. The function return a new string. The returned string should just be the original.
Describe differing theories on organizational development : Describe differing theories on organizational development, motivation and needs theories, and then compare and contrast the theories by providing strengths
Describe the growth of business intelligence : CISM4000 - Accounting Information Systems - Kaplan Business School - Excel Assignment and Case Study - Describe the growth of Business Intelligence in the past
Business statistics data analysis : Data Analysis and Decision Making For Managers. Adolph Westphalia has recently been assigned to analyze the company's pricing policy.
Calculate the monthly average prices of apple stock : 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.
Calculate the mean score from data on file : Read in the scores file. Calculate the mean score from data on file. Determine the grade for each score and count grade distribution.
Write a program that accepts a word as input : Write a program that accepts a word as input and determines wehther or not it has three consecutive letters in the alphabet.
Internal environment analysis : What internal strengths and weaknesses does your company have? What external market opportunities for growth and increased profitability exist for your company.
Additional research on topic of diversification : Diversification- Conduct additional research on the topic of diversification.you opt to pursue related diversification, unrelated diversification

Reviews

Write a Review

Python Programming Questions & Answers

  Write a python program to implement the diff command

Without using the system() function to call any bash commands, write a python program that will implement a simple version of the diff command.

  Write a program for checking a circle

Write a program for checking a circle program must either print "is a circle: YES" or "is a circle: NO", appropriately.

  Prepare a python program

Prepare a Python program which evaluates how many stuck numbers there are in a range of integers. The range will be input as two command-line arguments.

  Python atm program to enter account number

Write a simple Python ATM program. Ask user to enter their account number, and print their initail balance. (Just make one up). Ask them if they wish to make deposit or withdrawal.

  Python function to calculate two roots

Write a Python function main() to calculate two roots. You must input a,b and c from keyboard, and then print two roots. Suppose the discriminant D= b2-4ac is positive.

  Design program that asks user to enter amount in python

IN Python Design a program that asks the user to enter the amount that he or she has budget in a month. A loop should then prompt the user to enter his or her expenses for the month.

  Write python program which imports three dictionaries

Write a Python program called hours.py which imports three dictionaries, and uses the data in them to calculate how many hours each person has spent in the lab.

  Write python program to create factors of numbers

Write down a python program which takes two numbers and creates the factors of both numbers and displays the greatest common factor.

  Email spam filter

Analyze the emails and predict whether the mail is a spam or not a spam - Create a training file and copy the text of several mails and spams in to it And create a test set identical to the training set but with different examples.

  Improve the readability and structural design of the code

Improve the readability and structural design of the code by improving the function names, variables, and loops, as well as whitespace. Move functions close to related functions or blocks of code related to your organised code.

  Create a simple and responsive gui

Please use primarily PHP or Python to solve the exercise and create a simple and responsive GUI, using HTML, CSS and JavaScript.Do not use a database.

  The program is to print the time

The program is to print the time in seconds that the iterative version takes, the time in seconds that the recursive version takes, and the difference between the times.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd