quantstrat

核心套件blotter

initProfit / initAcct

核心套件quantstrat

add.indicator

add.signal

add.rule

applyStrategy

library(quantstrat)

ttz<-Sys.getenv(‘TZ’)
Sys.setenv(TZ=’UTC’)

if (!exists(‘.blotter’)) .blotter <- new.env() #清除blotter交易資料
if (!exists(‘.strategy’)) .strategy <- new.env() #清除rule資料

suppressWarnings(rm(“order_book.macross”,pos=.strategy))
suppressWarnings(rm(“account.macross”,”portfolio.macross”,pos=.blotter))
suppressWarnings(rm(“account.st”,”portfolio.st”,”stock.str”,”stratMACROSS”,’start_t’,’end_t’)) #移除警告訊息 若mark就可以查

stock.str=’AAPL’ # 可以置換你想要的股票代碼
currency(‘USD’) #設定幣別
stock(stock.str,currency=’USD’,multiplier=1) #multiplier設定兌換率

startDate=”2000–12–31" #設定起始日期
initEq=1000000 #設定本金

portfolio.st=’macross’ #assign portfolio name
account.st=’macross’ #assign 帳本name
initPortf(portfolio.st,symbols=stock.str) #初始化protfolio
initAcct(account.st,portfolios=portfolio.st, initEq=initEq) #初始化 帳本
initOrders(portfolio=portfolio.st) #初始化 order

stratMACROSS<- strategy(portfolio.st) #初始化 strategy

stratMACROSS <- add.indicator(strategy = stratMACROSS, name = “SMA”, arguments = list(x=quote(Cl(mktdata)), n=50),label= “ma50” )
stratMACROSS <- add.indicator(strategy = stratMACROSS, name = “SMA”, arguments = list(x=quote(Cl(mktdata)[,1]), n=200),label= “ma200”)

#add.indicator定義指標 name=指標名稱 arguments=與name相關的指標參數 label=indicator的識別名稱

stratMACROSS <- add.signal(strategy = stratMACROSS,name=”sigCrossover”,arguments = list(columns=c(“ma50”,”ma200"), relationship=”gte”),label=”ma50.gt.ma200")
stratMACROSS <- add.signal(strategy = stratMACROSS,name=”sigCrossover”,arguments = list(column=c(“ma50”,”ma200"),relationship=”lt”),label=”ma50.lt.ma200")

#add.signal定義訊號 name= sigComparison/ sigCrossover/ sigThreshold/ sigAND : relationship= gt, lt, lte and gte stand for greater than, less than, less than or equal to and greater than or equal to

https://s3.amazonaws.com/assets.datacamp.com/production/course_1296/slides/chapter4.pdf

stratMACROSS <- add.rule(strategy = stratMACROSS,name=’ruleSignal’, arguments = list(sigcol=”ma50.gt.ma200",sigval=TRUE, orderqty=100, ordertype=’market’, orderside=’long’),type=’enter’)
stratMACROSS <- add.rule(strategy = stratMACROSS,name=’ruleSignal’, arguments = list(sigcol=”ma50.lt.ma200",sigval=TRUE, orderqty=’all’, ordertype=’market’, orderside=’long’),type=’exit’)

#add.rule訂定交易規則 list(sigcol=”ma50.gt.ma200"短>長,sigval=TRUE, orderqty=100數量100, ordertype=’market’市價, orderside=’long’買),type=’enter’進場)

#list(sigcol=”ma50.lt.ma200"短<長,sigval=TRUE, orderqty=’all’全部, ordertype=’market’市價, orderside=’long’買),type=’exit’出場)

#ordertypeone of “market”,”limit”,”stoplimit”, “stoptrailing”, or “iceberg”

getSymbols(stock.str,from=startDate)
for(i in stock.str)
 assign(i, adjustOHLC(get(i),use.Adjusted=TRUE))

#getSymbols Load Data

#assign(i, adjustOHLC(get(i),use.Adjusted=TRUE))

assign(x,value) : Assign a value to a name in an environment.

#adjustOHLC(get(i),use.Adjusted=TRUE)

get(i) Return the Value of a Named Object ;Search by name for an object

use.Adjusted=TRUE

Using use.Adjusted = TRUE will be less precise than the method that employs actual split and dividend information. This is due to loss of precision from Yahoo! using Adjusted columns of only two decimal places. The advantage is that this can be run offline, and for short series or those with few adjustments the loss of precision will be small.

The resulting precision loss will be from row observation to row observation, as the calculation will be exact for intraday values.

start_t<-Sys.time() #時間
out<-applyStrategy(strategy=stratMACROSS , portfolios=portfolio.st)

#執行策略 apply the strategy to arbitrary market data . This function is the wrapper that holds together the execution of a strategy.

end_t<-Sys.time() #時間
print(end_t-start_t) #經過的時間

start_t<-Sys.time() 
updatePortf(Portfolio=’macross’,Dates=paste(‘::’,as.Date(Sys.time()),sep=’’)) #更新帳本

#update Portfilio P&L over a Dates range . The updatePortf function goes through each symbol and calculates the PL for each period prices are available.Dates optional xts-style ISO-8601 time range to run updatePortf over, default NULL (will use times from Prices)

end_t<-Sys.time() 
print(“更新交易帳”)
print(end_t-start_t)

chart.Posn(Portfolio=’macross’,Symbol=stock.str)

#Chart trades against market data, position through time, and cumulative P\&L . Produces a three-panel chart of time series charts that contains prices and transactions in the top panel, the resulting position in the second, and a cumulative profit-loss line chart in the third.

add_SMA(n=50 , on=1,col=’blue’)
add_SMA(n=200, on=1)

#addSMA(n = 10, on = 1, with.col = Cl, overlay = TRUE, col = “brown”)

addEMA(n = 10, wilder = FALSE, ratio=NULL, on = 1,
 with.col = Cl, overlay = TRUE, col = “blue”)

addWMA(n = 10, wts=1:n, on = 1, with.col = Cl, overlay = TRUE, col = “green”)

addDEMA(n = 10, on = 1, with.col = Cl, overlay = TRUE, col = “pink”)

addEVWMA(n = 10, on = 1, with.col = Cl, overlay = TRUE, col = “yellow”)

addZLEMA(n = 10, ratio=NULL, on = 1, with.col = Cl, overlay = TRUE, col = “red”)

book = getOrderBook(‘macross’) #getOrderBook : get the order book object

A data.frame containing:

Order.Qty
Order.Price
Order.Type
Order.Side
Order.Threshold
Order.Status
Order.StatusTime
Prefer
Order.Set
Txn.Fees
Rule

stats = tradeStats(‘macross’)

# calculate statistics on transactions and P&L for a symbol or symbols in a portfolio or portfolios

a data.frame containing:

Portfolio
name of the portfolio

Symbol
symbol name

Num.Txns
number of transactions produced by addTxn

Num.Trades
number of flat to flat trades performed

Net.Trading.PL
Avg.Trade.PL
mean trading P&L per trade

Med.Trade.PL
median trading P&L per trade

Largest.Winner
largest winning trade

Largest.Loser
largest losing trade

Gross.Profits
gross (pre-fee) trade profits

Gross.Losses
gross trade losses

Std.Dev.Trade.PL
standard deviation of trade P&L

Percent.Positive
percent of trades that end positive

Percent.Negative
percent of trades that end negative

Profit.Factor
absolute value ratio of gross profits over gross losses

Avg.Win.Trade
mean P&L of profitable trades

Med.Win.Trade
median P&L of profitable trades

Avg.Losing.Trade
mean P&L of losing trades

Med.Losing.Trade
median P&L of losing trades

Avg.Daily.PL
mean daily realized P&L on days there were transactions, see dailyStats for all days

Med.Daily.PL
median daily P&L

Std.Dev.Daily.PL
standard deviation of daily P&L

Ann.Sharpe
annualized Sharpe-like ratio, assuming no outside capital additions and 252 day count convention

Max.Drawdown
max drawdown

Avg.WinLoss.Ratio
ratio of mean winning over mean losing trade

Med.WinLoss.Ratio
ratio of median winning trade over median losing trade

Max.Equity
maximum account equity

Min.Equity
minimum account equity

ptstats = perTradeStats(‘macross’)

#calculate flat to flat per-trade statistics

One ‘trade’ is defined as the entire time the symbol is not flat. It may contain many transactions. From the initial transaction that moves the position away from zero to the last transaction that flattens the position is all one ‘trade’ for the purposes of this function.

rets = PortfReturns(‘macross’)

#Calculate portfolio instrument returns

This function (for now) calculates return on initial equity for each instrument in the portfolio or portfolios that make up an account. These columns will be additive to return on capital of each portfolio, or of the entire account.

txns = getTxns(‘macross’, stock.str)

#Retrieve transactions and their attributes.

Find and return the transactions and attribute values for the symbol and date in a specied portfolio.

#Date workaround, remove later
Sys.setenv(TZ=ttz)

Overall

Show your support

Clapping shows how much you appreciated Steven Wang’s story.