Exercise 2.2 - Solution

(a) List of tuples

# report.py
import csv

def read_portfolio(filename):
    '''
    Read a stock portfolio file into a list of (name, shares, price) tuples.
    '''
    portfolio = []
    f = open(filename)
    f_csv = csv.reader(f)
    headers = next(f_csv)
    for row in f_csv:
        stock = (row[0], int(row[1]), float(row[2]))
        portfolio.append(stock)
    f.close()
    return portfolio

(b) List of dictionaries

# report.py
import csv

def read_portfolio(filename):
    '''
    Read a stock portfolio file into a list of dictionaries with keys
    name, shares, and price.
    '''
    portfolio = []
    f = open(filename)
    f_csv = csv.reader(f)
    headers = next(f_csv)
    for row in f_csv:
        stock = {
             'name' : row[0],
             'shares' : int(row[1]),
             'price' : float(row[2])
        }
        portfolio.append(stock)
    f.close()
    return portfolio

(c) Dictionaries as a container

# report.py
import csv

...
def read_prices(filename):
    '''
    Read a CSV file of price data into a dict mapping names to prices.
    '''
    prices = {}
    f = open(filename)
    f_csv = csv.reader(f)
    for row in f_csv:
        try:
            prices[row[0]] = float(row[1])
        except IndexError:
            pass
    f.close()
    return prices

(d) Finding out if your can retire

# report.py
import csv

def read_portfolio(filename):
    '''
    Read a stock portfolio file into a list of dictionaries with keys
    name, shares, and price.
    '''
    portfolio = []
    f = open(filename)
    f_csv = csv.reader(f)
    headers = next(f_csv)

    for row in f_csv:
        stock = {
             'name' : row[0],
             'shares' : int(row[1]),
             'price' : float(row[2])
        }
        portfolio.append(stock)
    f.close()
    return portfolio

def read_prices(filename):
    '''
    Read a CSV file of price data into a dict mapping names to prices.
    '''
    prices = {}
    f = open(filename)
    f_csv = csv.reader(f)
    for row in f_csv:
        try:
            prices[row[0]] = float(row[1])
        except IndexError:
            pass
    f.close()
    return prices

portfolio = read_portfolio('Data/portfolio.csv')
prices    = read_prices('Data/prices.csv')

# Calculate the total cost of the portfolio
total_cost = 0.0
for s in portfolio:
    total_cost += s['shares'] * s['price']

print 'Total cost', total_cost

# Compute the current value of the portfolio
total_value = 0.0
for s in portfolio:
    total_value += s['shares'] * prices[s['name']]

print 'Current value', total_value
print 'Gain', total_value - total_cost

[ Back ]