Answer:
import csv
# Initialize variables
mean_SP = 0
max_interest = 0
count = 0
# Read in data from file
with open('data.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# Extract date and convert to datetime object
date = datetime.strptime(row['DATE'], '%Y-%m-%d')
# Check if date is within June 2016 and May 2017
if date >= datetime(2016, 6, 1) and date <= datetime(2017, 5, 31):
# Extract closing price and update mean_SP
closing_price = float(row['SP500'])
mean_SP += closing_price
count += 1
# Extract long-term interest rate and update max_interest
interest_rate = float(row['LONGTERM_IR'])
if interest_rate > max_interest:
max_interest = interest_rate
# Compute mean_SP
mean_SP /= count
# Display results
print(f"Average closing price (June 2016 - May 2017): {mean_SP:.2f}")
print(f"Highest long-term interest rate (June 2016 - May 2017): {max_interest:.2f}")
Step-by-step explanation:
In this code, we use the csv module to read in the data from the data.csv file. We initialize the variables mean_SP, max_interest, and count to 0 to keep track of the sum of closing prices, the highest long-term interest rate, and the number of rows within the time period of interest, respectively.
We then loop over each row in the CSV file and extract the date, closing price, and long-term interest rate. We use the datetime module to convert the date string to a datetime object, and we check if the date is within the time period of interest (June 2016 through May 2017).
For each row within the time period of interest, we update the mean_SP variable by adding the closing price to the sum and incrementing the count variable. We also update the max_interest variable if the long-term interest rate is higher than the current maximum.
After looping over all rows, we compute the average closing price by dividing the sum by the count.
Finally, we display the results using the print function, formatting the values to two decimal places using the f-string format.