|
1 | | -# report.py |
2 | | -# |
3 | | -# Exercise 2.4 |
| 1 | +import csv |
| 2 | +import sys |
| 3 | +from pprint import pprint |
| 4 | + |
| 5 | + |
| 6 | +def read_portfolio(filename: str) -> list: |
| 7 | + """Reads the portfolio files""" |
| 8 | + |
| 9 | + portfolio = [] |
| 10 | + with open(filename, 'rt') as f: |
| 11 | + rows = csv.reader(f) |
| 12 | + next(rows) # skip the header |
| 13 | + for row in rows: |
| 14 | + try: |
| 15 | + portfolio.append({'name': row[0], 'shares': int(row[1]), 'price': float(row[2])}) |
| 16 | + except ValueError: |
| 17 | + print('broken line', row) |
| 18 | + |
| 19 | + return portfolio |
| 20 | + |
| 21 | + |
| 22 | +def read_prices(filename: str) -> dict: |
| 23 | + """Reads the file with assets prices""" |
| 24 | + |
| 25 | + prices = {} |
| 26 | + with open(filename, 'rt') as f: |
| 27 | + rows = csv.reader(f) |
| 28 | + for row in rows: |
| 29 | + try: |
| 30 | + prices[str(row[0])] = float(row[1]) |
| 31 | + except (ValueError, IndexError): |
| 32 | + print('broken line', row) |
| 33 | + |
| 34 | + return prices |
| 35 | + |
| 36 | + |
| 37 | +def compute_investment_results(portfolio: dict, prices: dict) -> str: |
| 38 | + """Computes wheather portfolio makes money or losses""" |
| 39 | + |
| 40 | + result = 0.0 |
| 41 | + for asset in portfolio: |
| 42 | + try: |
| 43 | + result += asset['shares'] * (prices[asset['name']] - asset['price']) |
| 44 | + except KeyError: |
| 45 | + print('no asset', asset['name']) |
| 46 | + |
| 47 | + if result > 0: |
| 48 | + return f'Investments are success! Total profit = {result}' |
| 49 | + return f'Investments are failure! Total profit = {result}' |
| 50 | + |
| 51 | + |
| 52 | +if len(sys.argv) == 2: |
| 53 | + filename = sys.argv[1] |
| 54 | +else: |
| 55 | + filename = 'Data/portfolio.csv' |
| 56 | + |
| 57 | +prices = read_prices('Data/prices.csv') |
| 58 | +portfolio = read_portfolio('Data/portfolio.csv') |
| 59 | +result = compute_investment_results(portfolio, prices) |
| 60 | +print(result) |
0 commit comments