Skip to content

Instantly share code, notes, and snippets.

@auryn31
Last active January 4, 2024 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save auryn31/8baff95832622f2997bfb594c05a8eca to your computer and use it in GitHub Desktop.
Save auryn31/8baff95832622f2997bfb594c05a8eca to your computer and use it in GitHub Desktop.
Monthly investing vs weekly investing
# %%
import csv
import datetime
import pandas as pd
from typing import Tuple, List
from datetime import date
# %%
years = 10
# we start at 10 years ago
start_date = date.today() - datetime.timedelta(days=365*years)
end_date = date.today()
allWeeks: List[date] = []
allMonth: List[date] = []
# Loop through each month and get the first day
current_date = start_date.replace(day=1)
while current_date <= end_date:
allMonth.append(current_date)
current_date = current_date + datetime.timedelta(days=31)
current_date = current_date.replace(day=1)
# Loop through each week and get the first day (Monday) of the week
current_date = start_date - datetime.timedelta(days=start_date.weekday())
while current_date <= end_date:
allWeeks.append(current_date)
current_date = current_date + datetime.timedelta(days=7)
# %%
# create dict for all prices
dateToPrice: dict[Tuple[int, int, int], float] = {}
with open('./msci_historical_yahoo.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count > 0:
if line_count == 1:
lastPrice = float(row[1].replace(",", ""))
currentDate = datetime.datetime.strptime(row[0], "%Y-%m-%d")
if row[1] == "null":
continue
openPrice = float(row[1])
highPrice = float(row[2])
lowPrice = float(row[3])
close = float(row[4])
price = (openPrice + lowPrice + highPrice + close) / 4
dateToPrice[(currentDate.date().year,currentDate.date().month,currentDate.date().day)] = price
line_count += 1
# %%
def get_next_buy_price(current_date: date)-> float:
current_search_date = current_date
index = 0
while index < len(dateToPrice):
index += 1
searchTuple = (current_search_date.year, current_search_date.month, current_search_date.day)
if searchTuple in dateToPrice:
return dateToPrice[searchTuple]
current_search_date = current_search_date + datetime.timedelta(days=1)
# %%
def print_results(stocks_month, stocks_week, investment_month, investment_week):
total_invested_month = len(stocks_month) * investment_month
total_invested_week = len(stocks_week) * investment_week
current_value = get_next_buy_price(date.today() - datetime.timedelta(days=3))
final_stocks_month = stocks_month[len(stocks_month)-1]
final_stocks_week = stocks_week[len(stocks_week)-1]
final_value_month = final_stocks_month * current_value
final_value_week = final_stocks_week * current_value
if final_value_month > final_value_week:
print(f"Investing monthly is better than investing weekly by {round((final_value_month / final_value_week - 1) *100, 2)} %")
else:
print(f"Investing weekly is better than investing monthly by {round((final_value_week / final_value_month - 1) *100, 2)} %")
data = [
["Month", stocks_month[len(stocks_month)-1], total_invested_month,round(final_value_month, 2),round(final_value_month - total_invested_month, 2), round(((final_value_month-total_invested_month)/total_invested_month) * 100, 2)],
["Week", stocks_week[len(stocks_week)-1], total_invested_week,round(final_value_week, 2),round(final_value_week - total_invested_week, 2), round(((final_value_week-total_invested_week)/total_invested_week) * 100, 2)],
]
return pd.DataFrame(data, columns=["Week/Month", "Stocks", "Invested", "Current Value","Gained", "Gained %"])
# %%
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
# %%
# Buy every month for 1k for last 10 year
# or every week for 250
stocks_month : List[float] = []
investment_month = 1000
stocks_week: List[float] = []
investment_week = 250
for month in allMonth:
price = get_next_buy_price(month)
if stocks_month == []:
stocks_month.append(investment_month / price)
else:
stocks_month.append(stocks_month[len(stocks_month)-1]+ investment_month / price)
for week in allWeeks:
price = get_next_buy_price(week)
if stocks_week == []:
stocks_week.append(investment_week / price)
else:
stocks_week.append(stocks_week[len(stocks_week)-1]+ investment_week / price)
fig, ax = plt.subplots()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=400))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
for label in ax.get_xticklabels(which='major'):
label.set(rotation=30, horizontalalignment='right')
ax.set_ylabel(r'Amount of stocks')
ax.set_title('every Month 1k\$ vs. every week 250\$', loc='left', y=1,
fontsize='medium')
x = np.array(allWeeks)
y = np.array(stocks_week)
ax.plot(x, y, label="250 a week")
x = np.array(allMonth)
y = np.array(stocks_month)
ax.plot(x, y, label="1k a month")
ax.legend()
# %%
print_results(stocks_month, stocks_week, investment_month, investment_week)
# %%
# Buy every month for 1k for last 10 year
# or every week for 1/12 of year investment
stocks_month : List[float] = []
investment_month = 1000
stocks_week: List[float] = []
investment_week = investment_month * 12 / 52
for month in allMonth:
price = get_next_buy_price(month)
if stocks_month == []:
stocks_month.append(investment_month / price)
else:
stocks_month.append(stocks_month[len(stocks_month)-1]+ investment_month / price)
for week in allWeeks:
price = get_next_buy_price(week)
if stocks_week == []:
stocks_week.append(investment_week / price)
else:
stocks_week.append(stocks_week[len(stocks_week)-1]+ investment_week / price)
fig, ax = plt.subplots()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=400))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
for label in ax.get_xticklabels(which='major'):
label.set(rotation=30, horizontalalignment='right')
ax.set_ylabel(r'Amount of stocks')
ax.set_title(f"every month {round(investment_month, 0)}\$ vs every week {round(investment_week, 0)}\$", loc='left', y=1,
fontsize='medium')
x = np.array(allWeeks)
y = np.array(stocks_week)
ax.plot(x, y, label=f"{investment_week} a week")
x = np.array(allMonth)
y = np.array(stocks_month)
ax.plot(x, y, label=f"{investment_month} a month")
ax.legend()
# %%
print_results(stocks_month, stocks_week, investment_month, investment_week)
# %%
# Buy every month for 1k for last 10 year
# or every week for 1/12 of year investment
# but pay also 1$ fee per buy
stocks_month : List[float] = []
investment_month = 1000
stocks_week: List[float] = []
investment_week = investment_month * 12 / 52
for month in allMonth:
price = get_next_buy_price(month)
amount = (investment_month - 1) / price
if stocks_month == []:
stocks_month.append(amount)
else:
stocks_month.append(stocks_month[len(stocks_month)-1]+ amount)
for week in allWeeks:
price = get_next_buy_price(week)
amount = (investment_week - 1) / price
if stocks_week == []:
stocks_week.append(amount)
else:
stocks_week.append(stocks_week[len(stocks_week)-1]+ amount)
fig, ax = plt.subplots()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=400))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
for label in ax.get_xticklabels(which='major'):
label.set(rotation=30, horizontalalignment='right')
ax.set_ylabel(r'Amount of stocks')
ax.set_title(f"every month {round(investment_month, 0)}\$ vs every week {round(investment_week, 0)}\$ with 1\$ fee", loc='left', y=1,
fontsize='medium')
x = np.array(allWeeks)
y = np.array(stocks_week)
ax.plot(x, y, label=f"{investment_week} a week")
x = np.array(allMonth)
y = np.array(stocks_month)
ax.plot(x, y, label=f"{investment_month} a month")
ax.legend()
# %%
print_results(stocks_month, stocks_week, investment_month, investment_week)
# %%
# Buy every month for 1k for last 10 year
# or every week for 1/12 of year investment
# but pay also 1% fee per buy
stocks_month : List[float] = []
investment_month = 1000
stocks_week: List[float] = []
investment_week = investment_month * 12 / 52
for month in allMonth:
price = get_next_buy_price(month)
amount = (investment_month - (investment_month/100)) / price
if stocks_month == []:
stocks_month.append(amount)
else:
stocks_month.append(stocks_month[len(stocks_month)-1]+ amount)
for week in allWeeks:
price = get_next_buy_price(week)
amount = (investment_week - (investment_week/100)) / price
if stocks_week == []:
stocks_week.append(amount)
else:
stocks_week.append(stocks_week[len(stocks_week)-1]+ amount)
fig, ax = plt.subplots()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=400))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
for label in ax.get_xticklabels(which='major'):
label.set(rotation=30, horizontalalignment='right')
ax.set_ylabel(r'Amount of stocks')
ax.set_title(f"every month {round(investment_month, 0)}\$ vs every week {round(investment_week, 0)}\$ with 1% fee", loc='left', y=1,
fontsize='medium')
x = np.array(allWeeks)
y = np.array(stocks_week)
ax.plot(x, y, label=f"{investment_week} a week")
x = np.array(allMonth)
y = np.array(stocks_month)
ax.plot(x, y, label=f"{investment_month} a month")
ax.legend()
# %%
print_results(stocks_month, stocks_week, investment_month, investment_week)
# %%
# Buy every month for 1k for last 10 year
# or every week for 1/12 of year investment
# but end of week / end of month
allWeeks: List[date] = []
allMonth: List[date] = []
# Loop through each month and get the first day
current_date = start_date.replace(day=31)
while current_date <= end_date:
allMonth.append(current_date)
current_date = current_date + datetime.timedelta(days=2)
current_date = current_date.replace(day=28) + datetime.timedelta(days=4)
current_date -= datetime.timedelta(days=current_date.day)
# Loop through each week and get the first day (Monday) of the week
current_date = start_date - datetime.timedelta(days=start_date.weekday())
while current_date <= end_date:
allWeeks.append(current_date)
current_date = current_date + datetime.timedelta(days=7)
stocks_month : List[float] = []
investment_month = 1000
stocks_week: List[float] = []
investment_week = investment_month * 12 / 52
for month in allMonth:
price = get_next_buy_price(month)
amount = investment_month / price
if stocks_month == []:
stocks_month.append(amount)
else:
stocks_month.append(stocks_month[len(stocks_month)-1]+ amount)
for week in allWeeks:
price = get_next_buy_price(week)
amount = investment_week / price
if stocks_week == []:
stocks_week.append(amount)
else:
stocks_week.append(stocks_week[len(stocks_week)-1]+ amount)
fig, ax = plt.subplots()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=400))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
for label in ax.get_xticklabels(which='major'):
label.set(rotation=30, horizontalalignment='right')
ax.set_ylabel(r'Amount of stocks')
ax.set_title(f"end of every month {round(investment_month, 0)}\$ vs end of every week {round(investment_week, 0)}\$", loc='left', y=1,
fontsize='medium')
x = np.array(allWeeks)
y = np.array(stocks_week)
ax.plot(x, y, label=f"{investment_week} a week")
x = np.array(allMonth)
y = np.array(stocks_month)
ax.plot(x, y, label=f"{investment_month} a month")
ax.legend()
# %%
print_results(stocks_month, stocks_week, investment_month, investment_week)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment