Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- from datetime import datetime
- from collections import defaultdict
- # CSV with format date,start_price,daily_high,daily_low
- # Can be downloaded here: https://finance.yahoo.com/quote/BTC-USD/history/
- filename = 'BTC-USD.csv'
- def get_weekday(date_str):
- date_obj = datetime.strptime(date_str, '%Y-%m-%d')
- return date_obj.strftime('%A')
- # Initialize dictionaries to store counts and cumulative losses
- analysis_count = defaultdict(int)
- analysis_loss = defaultdict(float) # Use float for loss values
- analysis_gain = defaultdict(float)
- with open(filename, 'r', newline='') as csvfile:
- reader = csv.reader(csvfile)
- next(reader) # Skip the header
- for row in reader:
- date_weekday = get_weekday(row[0])
- start_price = float(row[1])
- day_high = float(row[2])
- day_low = float(row[3])
- difference_low = (1 - (day_low / start_price)) * 100 # Calculate the loss
- difference_high = (day_high / start_price - 1) * 100
- # Increment the count sum of losses for the weekday
- analysis_count[date_weekday] += 1
- analysis_loss[date_weekday] += difference_low
- analysis_gain[date_weekday] += difference_high
- # Calculate average for each weekday.
- average_loss = {weekday: analysis_loss[weekday] / analysis_count[weekday] for weekday in analysis_loss}
- average_gain = {weekday: analysis_gain[weekday] / analysis_count[weekday] for weekday in analysis_gain}
- print('Average loss:')
- for weekday, avg_loss in average_loss.items():
- print(f'{weekday}: {avg_loss:.3f}') # Formats the average loss to two decimal places
- print('Average gain:')
- for weekday, avg_gain in average_gain.items():
- print(f'{weekday}: {avg_gain:.3f}')
Add Comment
Please, Sign In to add comment