货币对交易策略:信号买卖

时间:2018-07-28 22:16:50

标签: r quantitative-finance algorithmic-trading

我正在尝试根据股票的价差建立一个成对交易策略。我已经提出了关于如何多头或空头入仓的逻辑。 我正在努力理解我将如何做的概念: (1)如果我在退出之前已经进入仓位,则忽略该信号 (2)如何根据仓位是否打开来创建信号以退出仓位 (3)计算收益/最大跌幅等。

library(quantmod)
library(tseries)
library(xts)
library(zoo)
library(PerformanceAnalytics)


#disable sci notation
options(scipen=999)



stock1 <- "TECHM.NS"
stock2 <- "HCLTECH.NS"

stock1 <-  getSymbols(stock1, src = "yahoo", auto.assign = F)
stock2 <- getSymbols(stock2, src = "yahoo", auto.assign = F)


##Keep only adjusted close for analysis
stock1 <- stock1[, grep("Adjusted", colnames(stock1))] #must use grep for time series
stock2 <- stock2[, grep("Adjusted", colnames(stock2))] #must use grep for time series


#shortens data set for analysis
cut_off_date <- as.Date("2014-01-01")
stock1 <- stock1[index(stock1) >= cut_off_date]
stock2 <- stock2[index(stock2) >= cut_off_date]

#Replaces NA values with previous observations
stock1 <- na.locf(stock1)
stock2 <- na.locf(stock2)

# Delt() converts closing prices to returns. By default it calculates one period  return
ret_stock1 <- Delt(stock1)
ret_stock2 <- Delt(stock2)



ret_stock1 <- round(ret_stock1+1, 4) #rounds the daily returns
ret_stock1[1] <- 1 #sets the first day equal to $1 invested. 
norm_stock1 <- cumprod(ret_stock1) #computes the cumulative return through all trade days




ret_stock2 <- round(ret_stock2+1, 4) #rounds the daily returns - why the +1?
ret_stock2[1] <- 1 #sets the first day equal to $1 invested
norm_stock2 <- cumprod(ret_stock2) #computes the cumulative return through all trade days

#calculate and plot the differences between the two
diff <- norm_stock1 - norm_stock2

#Create short and long signals
n <- 0.5

me_dynamic <- rollapply(diff, 10, mean)
std_dynamic <- rollapply(diff, 10, sd)

ub <- me_dynamic + n*std_dynamic #upperbound
lb <- me_dynamic - n*std_dynamic #lowerbound

这是我的方法,用以指示哪些股票做多,哪些股票做空。

enterhigh <- ifelse(diff > ub, 1, 0)
enterlow <-  ifelse(diff < lb, 1, 0)
norm1position <- ifelse((enterhigh == 1 | enterlow ==1) & norm_stock1 > 
norm_stock2, -1, 
                    ifelse((enterhigh ==1 | enterlow ==1), 1,0))

norm2position <- ifelse(norm1position == -1, 1, ifelse(norm1position ==1, -1, 0))

如果您有完全不同的方式来执行此操作,我也想学习。 我看过以下示例:https://analyticsprofile.com/algo-trading/pair-trading-part-1-code-distance-based-pair-trading-strategy-in-r/。然而,这些人缺乏将行动与战略真正联系起来的能力。

0 个答案:

没有答案