-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathExample7_6.py
43 lines (34 loc) · 1.5 KB
/
Example7_6.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
# Example 7-6
# # Backtesting the January Effect
import numpy as np
import pandas as pd
onewaytcost = 0.0005
df = pd.read_table("miscFiles/IJR_20080131.txt")
df["Date"] = df["Date"].round().astype("int")
df["Date"] = pd.to_datetime(df["Date"], format="%Y%m%d")
df.set_index("Date", inplace=True)
eoyPrice = df.resample("Y").last()[
0:-1
] # End of December prices. Need to remove last date because it isn't really end of year
annret = eoyPrice.pct_change().iloc[1:, :] # first row has NaN
eojPrice = df.resample("BA-JAN").last()[
1:-1
] # End of January prices. Need to remove first date to match the years in lastdayofDec. Need to remove last date because it isn't really end of January.
janret = (eojPrice.values - eoyPrice.values) / eoyPrice.values
janret = janret[
1:,
] # match number of rows in annret
for y in range(len(annret)):
hasData = np.where(np.isfinite(annret.iloc[y, :]))[0]
sortidx = np.argsort(annret.iloc[y, hasData])
topN = np.round(len(hasData) / 10)
portRet = (
np.nanmean(janret[y, hasData[sortidx.iloc[np.arange(0, topN)]]])
- np.nanmean(janret[y, hasData[sortidx.iloc[np.arange(-topN + 1, -1)]]])
) / 2 - 2 * onewaytcost # portfolio returns
print(
"Last holding date %s: Portfolio return=%f" % (eojPrice.index[y + 1], portRet)
)
# Last holding date 2006-01-31 00:00:00: Portfolio return=-0.023853
# Last holding date 2007-01-31 00:00:00: Portfolio return=-0.003641
# Last holding date 2008-01-31 00:00:00: Portfolio return=0.088486