Files: Exercise Answers#
Write a method named
blastoffwith two parameters: filename and countdown. Using a range function, write a file that looks like10 9 8 7 6 5 4 3 2 1---BlastOff
1def blastoff(filename, countdown):
2 with open(filename, 'wt') as f:
3 for i in range(countdown, 0, -1):
4 if i != countdown:
5 f.write(' ')
6 f.write(str(i))
7 f.write('---BlastOff')
8
9blastoff('blastText.txt', 10)
10
11# Verify
12with open('blastText.txt') as f:
13 print(f.read())
10 9 8 7 6 5 4 3 2 1---BlastOff
Write a method named
sum_blastoff_filewith one parameter - filename. The function reads a file produced by the previous exercise. It will read all the numbers and produce their sum, printing the result to the console.
1def sum_blastoff_file(filename):
2 with open(filename) as f:
3 line = f.readline()
4 total = 0
5 for item in line.split():
6 # Strip everything from the first '-' onward (handles the '---BlastOff' suffix)
7 # and handles multi-digit countdowns correctly (e.g. '10---BlastOff' -> '10')
8 dash_pos = item.find('-')
9 if dash_pos != -1:
10 item = item[:dash_pos]
11 if item:
12 total += int(item)
13 print(total)
14
15sum_blastoff_file('blastText.txt') # expect 55 (1+2+...+10)
55
Given these stocks in some series of files, which stock had the largest monetary day gain, which had the biggest % change (gain or loss), and which has performed the best since its inception? Files:
data/AAPL.csv,data/GME.csv,data/SPY.csv,data/TSLA.csv.
1import csv
2
3def read_stock_data(filename):
4 records = []
5 with open(filename) as f:
6 reader = csv.DictReader(f)
7 for row in reader:
8 records.append({
9 'Date': row['Date'],
10 'Open': float(row['Open']),
11 'Close': float(row['Close'])
12 })
13 return records
14
15stock_files = {
16 'AAPL': 'data/AAPL.csv',
17 'GME': 'data/GME.csv',
18 'SPY': 'data/SPY.csv',
19 'TSLA': 'data/TSLA.csv',
20}
21
22all_data = {symbol: read_stock_data(path) for symbol, path in stock_files.items()}
23
24# --- Largest single-day monetary gain (Close - Open) ---
25best_gain_symbol = None
26best_gain_date = None
27best_gain = float('-inf')
28
29for symbol, records in all_data.items():
30 for record in records:
31 gain = record['Close'] - record['Open']
32 if gain > best_gain:
33 best_gain = gain
34 best_gain_date = record['Date']
35 best_gain_symbol = symbol
36
37print(f"Largest monetary day gain: {best_gain_symbol} on {best_gain_date}: ${best_gain:.2f}")
38
39# --- Biggest single-day % change (gain or loss) ---
40best_pct_symbol = None
41best_pct_date = None
42best_pct = 0.0
43
44for symbol, records in all_data.items():
45 for record in records:
46 if record['Open'] != 0:
47 pct = abs((record['Close'] - record['Open']) / record['Open'] * 100)
48 if pct > best_pct:
49 best_pct = pct
50 best_pct_date = record['Date']
51 best_pct_symbol = symbol
52
53print(f"Biggest % change: {best_pct_symbol} on {best_pct_date}: {best_pct:.2f}%")
54
55# --- Best total return since inception (first Close to last Close) ---
56print("\nTotal return since inception:")
57returns = {}
58for symbol, records in all_data.items():
59 first = records[0]['Close']
60 last = records[-1]['Close']
61 pct = (last - first) / first * 100
62 returns[symbol] = pct
63 print(f" {symbol:4s}: {pct:8.2f}% (${first:.2f} on {records[0]['Date']} -> "
64 f"${last:.2f} on {records[-1]['Date']})")
65
66best = max(returns, key=returns.get)
67print(f"\nBest performer since inception: {best} ({returns[best]:.2f}%)")
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[3], line 22
18 'SPY': 'data/SPY.csv',
19 'TSLA': 'data/TSLA.csv',
20 }
21
---> 22 all_data = {symbol: read_stock_data(path) for symbol, path in stock_files.items()}
23
24 # --- Largest single-day monetary gain (Close - Open) ---
25 best_gain_symbol = None
Cell In[3], line 5, in read_stock_data(filename)
3 def read_stock_data(filename):
4 records = []
----> 5 with open(filename) as f:
6 reader = csv.DictReader(f)
7 for row in reader:
8 records.append({
FileNotFoundError: [Errno 2] No such file or directory: 'data/AAPL.csv'