0
votes

Write a function named "read_prices" that takes one parameter that is a list of ticker symbols that your company owns in their portfolio. You are to read a CSV file for each of these tickers which contains the price of each stock throughout the year and return these prices in a single dictionary. The returned dictionary will contain ticker symbols as keys and dictionaries as values where the inner dictionaries will have dates as keys (as strings in the format "YYYY-MM-DD") and prices as values as floats. All said this dictionary will contain the price for any stock on any date over the past year. You may assume there will be files named ".csv" for each ticker symbol in the input list. For example, if "TXN" is in the ticker list then a file named "TXN.csv" will be in the same directory as your code during testing and each row of this CSV file will be in the format "date,price,volume" where date is in the format YYYY-MM-DD, the price is a float, and volume is an integer representing the number of shares that were traded on that day by all traders (you will not need the trading volume for this prelab).

Example line for AAPL stock: "2015-10-20,112.673677,48967800"

import csv
def read_prices(ticker):
    with open(ticker) as f:
        reader = csv.reader(f)
        dict = {}
        for items in reader:
            if items[0] in dict:
                dict[items[0]] += float(items[1]) * int(items[2])
            else:
                dict[items[0]] = float(items[1]) * int(items[2])
    return dict

I am getting error on input [['AAPL', 'GOOG', 'FB']]. How would I solve this problem?

1
Is there any reason that you don't use pandas? - Hyunwoo
Just not familiar with it. - user10454314

1 Answers

0
votes

As the description of your assignment says, your input files are named with ticker names followed by .csv so you should concatenate .csv to the ticker names as file names. Your function also treats the input as one ticker name rather than a list of ticker names so naturally passing to it a list won't work. You should iterate through the input as a list of tickers instead:

import csv
def read_prices(tickers):
    d = {}
    for ticker in tickers:
        with open(ticker + '.csv') as f:
            for date, price, _ in csv.reader(f):
                d.setdefault(ticker, {})[date] = float(price)
    return d

Or you can use dict comprehension to accomplish the same:

def read_prices(tickers):
    return {ticker: {date: price for date, price, _ in csv.reader(open(ticker + '.csv'))} for ticker in tickers}