Skip to content

Instantly share code, notes, and snippets.

@vlameiras
Created March 8, 2024 14:20
Show Gist options
  • Save vlameiras/fce42165ae991f418f396962563dc452 to your computer and use it in GitHub Desktop.
Save vlameiras/fce42165ae991f418f396962563dc452 to your computer and use it in GitHub Desktop.
This module analyzes weekly returns of Bitcoin prices.
"""
This module analyzes weekly returns of Bitcoin prices.
"""
import pandas as pd
# Constants for weekdays
MONDAY = 0
FRIDAY = 4
def load_data(filename):
"""Load data from CSV and resample to daily data."""
df = pd.read_csv(filename, parse_dates=['timestamp'])
df.set_index('timestamp', inplace=True)
daily_df = df.resample('D').agg({'open': 'first', 'close': 'last'})
daily_df['weekday'] = daily_df.index.dayofweek
return daily_df
def calculate_weekly_returns(daily_df):
"""Calculate weekly returns based on opening price on Monday and closing price on Friday."""
mondays = daily_df[daily_df['weekday'] == MONDAY]
fridays = daily_df[daily_df['weekday'] == FRIDAY]
weekly_returns = []
for monday in mondays.index:
next_friday = fridays.index[fridays.index > monday][0] if any(fridays.index > monday) else None
if next_friday:
buy_price = mondays.loc[monday]['open']
sell_price = fridays.loc[next_friday]['close']
weekly_returns.append((sell_price - buy_price) / buy_price)
return pd.Series(weekly_returns)
def display_results(weekly_returns):
"""Display the results of the analysis."""
print("Total Weeks Analyzed:", len(weekly_returns))
print("Average Weekly Return:", weekly_returns.mean())
print("Positive Weeks Percentage:", (weekly_returns > 0).mean() * 100, "%")
print("Negative Weeks Percentage:", (weekly_returns < 0).mean() * 100, "%")
def main():
"""Main function to run the analysis."""
try:
daily_df = load_data('btc_1.csv')
weekly_returns = calculate_weekly_returns(daily_df)
display_results(weekly_returns)
except FileNotFoundError:
print("The file 'btc_1.csv' was not found.")
if __name__ == "__main__":
main()
# Results using https://www.gigasheet.com/sample-data/bitcoin-price-2014-2023
#Total Weeks Analyzed: 460
#Average Weekly Return: 0.01164359062566534
#Positive Weeks Percentage: 56.95652173913044 %
#Negative Weeks Percentage: 43.04347826086957 %
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment