-
Notifications
You must be signed in to change notification settings - Fork 1
/
strategies.py
61 lines (51 loc) · 2.14 KB
/
strategies.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
## Strategy functions
import math
import pandas as pd
import numpy as np
from utils import lagit, calc_rollsum
## Calculate the moving average strategy returns
def strat_movavg(closep, retsp, lookback, lagv):
# Calculate moving average stock prices
pricema = closep.ewm(span=lookback, adjust=False).mean()
# Calculate differences between the stock prices and the moving average
posit = closep - pricema
# Positions are equal to the sign of the differences
posit = np.sign(posit)
# Lag the positions by lagv periods
posit = posit.shift(lagv)
# Calculate the strategy returns
return posit*retsp
# end strat_movavg
## Calculate the moving average strategy returns - increase positions gradually
def strat_movavg2(closep, retsp, lookback, lagv):
# Calculate moving average stock prices
pricema = closep.ewm(span=lookback, adjust=False).mean()
# Calculate differences between the stock prices and the moving average
indic = np.sign(closep - pricema)
# Positions are equal to the rolling sum of the signs of the differences
posit = calc_rollsum(indic.to_numpy(), lagv)
# Lag the positions by 1 period
posit = lagit(posit, 1)
# Calculate the strategy returns
return posit*retsp/lagv
# end strat_movavg2
## Calculate strategy with moving average of returns
# If price exceeds MA by n standard deviations then sell.
# If price is below MA by n standard deviations then buy.
def strat_movavg3(closep, retsp, lookback, numsd):
# Calculate standard deviations
stdev = retsp.rolling(lookback).std()
stdev[0:lookback] = 1
# Calculate moving average stock prices
pricema = closep.ewm(span=lookback, adjust=False).mean()
# Calculate differences between the stock prices and the moving average
indic = closep - pricema
posit = pd.DataFrame(np.nan, index=range(0, retsp.shape[0]), columns=['posit'])
posit = np.where(indic > numsd*stdev, -1, posit)
# Positions are equal to the sign of the differences
posit = np.sign(posit)
# Lag the positions by lagv periods
posit = posit.shift(lagv)
# Calculate the strategy returns
return posit*retsp
# end strat_movavg