-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathRunStrategy.R
More file actions
107 lines (107 loc) · 2.63 KB
/
RunStrategy.R
File metadata and controls
107 lines (107 loc) · 2.63 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
load (file = 'DataSet.RData ')
source ('BuildLinearModel.R')
source ('LinearStrategy.R')
# ### AVERAGED LAG LINEAR STRATEGY ####
## set trading and model parameters
threshold <- 0.2
period <- 20
lags <- 5
strategy <- 'A'
coefs <- c()
## build the linear models and store their coefficients
for (i in 1:length (data)) {
key <- names (data)[i]
# full -day coefficients
value <-
BuildLinearModel (
key ,
data [[i]],
full.day = T,
delay = period ,
lags = lags,
strategy = strategy
)
model <- value$model
coefs <- rbind (coefs , model$coefficients)
print (names (data)[i])
}
## set the lagged coefficient weights
coef.weights <- c (1)
trade.volume <- c()
trade.costs <- c()
pnl.name <-
paste ('pnl -', threshold , '-', strategy , period , 'F- lag ', lags , sep =
'')
assign (pnl.name , matrix (nrow = length (data), ncol = 2))
pnl.matrix <- get (pnl.name)
pnl.matrix [1 ,] <- 0
trade.pnl <- c()
## apply the trading strategy to each trading day using historical linear model
coefficients
for (i in 1:length (data)) {
key <- names (data)[i]
if (i > 1) {
coef <- 0
w <- coef.weights [1:min (length (coef.weights), i - 1)]
w <- w / sum (w)
for (j in 1:length (w)) {
coef <- coef + coefs [i - j ,] * w[j]
}
# morning trading using the weighted coefficients from T -1, T -2 ,...
strat <-
LinearStrategy (
data [[i]],
coef ,
lags = lags ,
strategy = strategy ,
morning =
T,
threshold = threshold
)
pnl.matrix [i , 1] <- tail (strat$pnl , 1)
trade.pnl <- c(trade.pnl , strat$trade.pnl)
tv <- strat$trade.volume
tc <- strat$trade.costs
# afternoon trading using the weighted coefficients from T -1, T -2 ,...
strat <-
LinearStrategy (
data [[i]],
coef ,
lags = lags ,
strategy = strategy ,
morning =
F,
threshold = threshold
)
pnl.matrix [i , 2] <- tail (strat$pnl , 1)
trade.pnl <- c(trade.pnl , strat$trade.pnl)
tv <- tv + strat$trade.volume
trade.volume <- c(trade.volume , tv)
tc <- tc + strat$trade.costs
trade.costs <- c(trade.costs , tc)
}
print (
paste (
key ,
strategy ,
period ,
threshold ,
'P&L =',
pnl.matrix [i , 1] ,
pnl.matrix [i , 2] ,
'
Total =',
sum(pnl.matrix [1:i ,])
)
)
}
assign (pnl.name , pnl.matrix)
sharpe.ratio <-
mean (rowSums (pnl.matrix)) * sqrt (nrow (pnl.matrix)) / sd(rowSums (pnl.matrix))
write.table (
pnl.matrix ,
paste (pnl.name , '.txt ', sep = ''),
sep = '\t',
row.names = F,
col.names = F
)