-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperTradeStatsTest.R
70 lines (48 loc) · 2.13 KB
/
perTradeStatsTest.R
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
# I spotted "poor" performance of perTradeStats compard to lighning fast addTxns.
# Below is an example that shows this.
# I test a "stupid" strategy that goes long on close of each day/bar and then
# the next day it closes the previous long position from previous day/bar and
# immediately goes long again on that same close of day/bar.
#
###############################################################################
options(width=250)
TZ <- "UTC"
Sys.setenv(TZ=TZ)
require(blotter)
symbol <- "SPY"
getSymbols(symbol, from="1990-01-01", auto.assign=TRUE)
SPY <- adjustOHLC(SPY)
SPY <- na.omit(SPY)
maxPosValue <- 100000 # Maximum number of $ bet on each trade
txnFees <- 0 # txnFees need to be positive since I take negative value when constructing transaction
entryTransactions <- Cl(SPY)
colnames(entryTransactions) <- "TxnPrice"
entryTransactions$TxnQty <- floor(maxPosValue/entryTransactions$TxnPrice)
entryTransactions$TxnFees <- (-1)*txnFees
exitTransactions <- Cl(SPY)
colnames(exitTransactions) <- "TxnPrice"
exitTransactions$TxnQty <- (-1)*lag.xts(entryTransactions$TxnQty)
exitTransactions$TxnFees <- (-1)*txnFees
# Remove last entry transaction in order not to have open trades
entryTransactions <- head(entryTransactions, -1)
# Remove first exit transaction since there is no entry yet (from previous close)
exitTransactions <- exitTransactions[-1, ]
transactions <- rbind(exitTransactions, entryTransactions)
init.eq <- maxPosValue
portf.test.pts <- "portf.test.pts"
account.test.pts <- "acct.test.pts"
init.date <- as.Date(first(index(get(symbol))))
try(rm(list=ls(pos=.blotter), pos=.blotter), silent = TRUE)
currency("USD")
stock(symbol, currency="USD", multiplier=1)
initPortf(portf.test.pts, symbols=symbol, initDate=init.date)
initAcct(account.test.pts,
portfolios=portf.test.pts,
initDate=init.date,
initEq=init.eq)
addTxns(Portfolio=portf.test.pts, Symbol=symbol, TxnData=transactions, verbose=FALSE)
updatePortf(portf.test.pts)
updateAcct(account.test.pts)
updateEndEq(account.test.pts)
# Very slow compared to everything else
per.trade.stats.result <- perTradeStats(portf.test.pts, symbol)#, tradeDef="flat.to.reduced")