-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbacktest.py
59 lines (46 loc) · 1.88 KB
/
backtest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import pandas as pd
df_all_years = pd.read_csv("VTSAX_cleaned.csv")
years = list(range(2001, 2020))
num_places = {xx:[0,0,0,0] for xx in ["Lump", "Monthly", "Biweekly", "Weekly"]} # number of years each method ranked in each position (1st through 4th)
for year in years:
df = df_all_years.loc[df_all_years["Year"] == year]
thismonth = 0
monthly_rows = []
for index, row in df.iterrows():
if row["Month"] != thismonth:
thismonth += 1
monthly_rows.append(row)
df_weekly = df.iloc[::5, :]
df_biweekly = df.iloc[::10, :]
df_monthly = pd.DataFrame(monthly_rows)
# lump sum calc
lump = 6000
num_shares = lump/df.iloc[0]["Close"] # num shares at beginning of year
lump_endval = num_shares*df.iloc[-1]["Close"]
# monthly calc
init = 0
contrib = lump/df_monthly.shape[0]
num_shares = init/df.iloc[0]["Close"] # num shares at beginning of year
for index, row in df_monthly.iterrows():
num_shares += contrib/row["Close"]
monthly_endval = num_shares*df.iloc[-1]["Close"]
# biweekly calc
init = 0
contrib = lump/df_biweekly.shape[0]
num_shares = init/df.iloc[0]["Close"] # num shares at beginning of year
for index, row in df_biweekly.iterrows():
num_shares += contrib/row["Close"]
biweekly_endval = num_shares*df.iloc[-1]["Close"]
# weekly calc
init = 0
contrib = lump/df_weekly.shape[0]
num_shares = init/df.iloc[0]["Close"] # num shares at beginning of year
for index, row in df_weekly.iterrows():
num_shares += contrib/row["Close"]
weekly_endval = num_shares*df.iloc[-1]["Close"]
winners = sorted([("Lump", lump_endval), ("Monthly", monthly_endval), ("Biweekly", biweekly_endval), ("Weekly", weekly_endval)], key = lambda x: x[1], reverse=True)
for pos, tup in enumerate(winners):
name, val = tup
num_places[name][pos] += 1
print(year, winners)
print(num_places)