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

  Integration of mnch commodities supply chain management

Objective of the study is to examine the outcome of integration of logistic and supply chain management of MNCH commodities on service delivery, specific objectives have been set to achieve the aim of the study.

  Form a program that asks the user to enter a sentence

Form a program that asks the user to enter a sentence, and then writes that sentence in reverse to a file named reverse.txt.

  Programming exercise - routing of telephone

programming exercise - routing of telephone callsdescriptionsome telephone operators have submitted their price lists

  Make your own algorithmic drawing with whatever combination

Make your own algorithmic drawing with whatever combination of color, line, and sequence you choose. Drawings should be uniquely yours.

  Write a program that calculates the occupancy rate for hotel

Write a program that calculates the occupancy rate for a hotel. The program should start by asking the user how many floors the hotel has.

  Calculate and print out the percentage of trips

Create a new column isPeak that indicates whether a trip was both started i.e. the meter was engaged and completed Calculate and print out percentage of trips.

  Design a program that asks the user to enter monthly sales

Design a program that asks the user to enter the monthly sales values for six months. The program should store the monthly sales values in a list.

  Find a python script

Find a python script

  1 one factor that leads to a decline in biodiversity is the

1. one factor that leads to a decline in biodiversity is the introduction of non-native species. however most species

  Write a python program that will validate a password

Write a python program that will Validate a password. The Program will have the user input a password. Check to see if all requirements are met

  Recursive sorts are easier to write in functional style

Recursive sorts are easier to write in functional style than others. Two recursive sorts are  Quicksort and Mergesort. Write functional versions of (a) Quicksort; (b) Mergesort in an  imperative language of your choice (e.g., C, Ada, C++, Python), us..

  Write a python script that reads and analyses the data

ICT702 Task 2 - Apply relevant Python programming concepts to a data analysis challenge - Read data from real sources and wrangle it into the form you need

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