hgeorgako / rfortraders Goto Github PK
View Code? Open in Web Editor NEWQuantitative Trading with R
License: MIT License
Quantitative Trading with R
License: MIT License
Great book Harry !
I really like this chapter.
As it is, the code will not run correctly unless the dates are corrected in getSymbols.
Best,
Nick Kirk
On page 131, the chunk about "#Generate sell and buy signals"
buys <- ifelse(data_out$spread > threshold,1,0);
sells <- ifelse(data_out$spread < -threshold,-1,0)
Shouldn't it be
sells <- ifelse(data_out$spread > threshold,-1,0);
buys <- ifelse(data_out$spread < -threshold,1,0)
Hi, Harry ! How are your quantitative feeling? =)
I have a question about the content, as a young Quantic .
On page 37 you mention about the csv file, but you have not created it , where you get information ? You have described the basic operation assignment , vectors , lists , matrices and data structures , but why you omitted the issue of export summary data in the form as described on page 38?
I need to help!
Tried running Code.R of Chapter 7 but got this error at runtime
Code.R Line 191 : test <- applyIndicators(strategy.st, mktdata = OHLC(XLB))
Error in
[.xts(x, seq_len(xlen - n)) : subscript out of bounds
Could you take a look at it and fix it? Thank you Harry!
It is impossible to go on and read and try to work - everywhere a huge number of mistakes for which there is no explanation in the R & stackoverflow communities
RStudio
aapl_2 <- read.csv(file = "C:/aapl.csv", header = TRUE, stringsAsFactors = FALSE)
Warning messages:
1: графический параметр "type" устарел
2: графический параметр "type" устарел
3: графический параметр "type" устарел
4: графический параметр "type" устарел
5: графический параметр "type" устарел
6: графический параметр "type" устарел
7: графический параметр "type" устарел
8: графический параметр "type" устарел
aapl_2 <- read.csv(file = "C:/aapl.csv", header = TRUE, stringsAsFactors = FALSE)
aapl_2 <- aapl_2[rev(rownames(aapl_2)), ]
aapl_close <- aapl_2[, "Close"]
Error in aapl_2[, "Close"] : incorrect number of dimensions
summary(aapl_close)
Error in summary(aapl_close) : object 'aapl_close' not found
RGui
aapl_2 <- read.csv(file = "C:/aapl.csv", header = TRUE, stringsAsFactors = FALSE)
aapl_2 <- aapl_2[rev(rownames(aapl_2)), ]
aapl_close <- aapl_2[, "Close"]
Ошибка в aapl_2[, "Close"] :неправильное количество измерений
summary(aapl_close)
Ошибка в summary(aapl_close) :объект 'aapl_close' не найден
There are no full data in the file rfortraders/Chapter_03/aapl.csv
from which we make a request on page 43 and 44 does not contain data on the closing price
aapl <- read.table ( "clipboard")
head (aapl)
instead of these data gives
head (aapl)
V1
1 Close
2 104.08
3 110.26
4 96.8
5 88.74
6 89.79
Code does not work
install.packages(pkgs, lib, repos = getOption("repos"),
- contriburl = contrib.url(repos, type),
- method, available = NULL, destdir = NULL,
- dependencies = NA, type = getOption("pkgType"),
- configure.args = getOption("configure.args"),
- configure.vars = getOption("configure.vars"),
- clean = FALSE, Ncpus = getOption("Ncpus", 1L),
- verbose = getOption("verbose"),
- libs_only = FALSE, INSTALL_opts, quiet = FALSE,
- keep_outputs = FALSE, ...)
Error: '...' used in an incorrect context
I know someone already posted this issue but it has been a while since someone actively commented something on there.
I'm unable to reproduce the spread results in page 125. I get a beta of 0.3946 and a level of 3.2386.
I have done the analyisis with close and adjusted prices and still get similar results around 0.3 and 3 respectively.
What I find interesting is, that the spread plot I'm getting looks very similar only that the scale of the y axis goes from around 0 to 10 and the one in the book ranges from -200 to -50.
Thus, I infer that, this is due to AAPL price differences i'm getting are far more smaller than those in the book. Don't know why this is happening so, if someone is getting the correct results and could attach a .csv file for the prices that reproduce this would be amazing.
Hi Harry,
Thanks for your excellent book! I'm making my way through it, running much of the code, and I'm learning a great deal.
When I got to page 104, the following line fails because returns_matrix is not defined:
sv <- as.xts(returns_matrix[, c(1, 6)])
I wasn't sure how to set returns_matrix, and not sure what dates to use, but I played around with some ideas and managed to make progress with the code in that section by doing this:
getSymbols(c("SPY", "VXX"), from="2009-01-30", to="2013-09-12", auto.assign=TRUE)
SPY_VXX_prices <- merge(SPY, VXX, join = "inner")
sv <- diff(log(SPY_VXX_prices[, c("SPY.Close", "VXX.Close")]))[-1,]
The sv I got is not an exact match, but it's very close to what's shown on page 104:
head(sv)
The cor(sv) also produces very similar results as compared to the page 104 value of -0.4603908. I tried different date ranges to get it as close as possible:
So, I'm OK for now - just thought you'd like to know in case you wanted to add some more code in a future edition to show how the returns_matrix was constructed.
prices <- aapl$V1
plot(prices, main = "AAPL plot", type = 'l')
Warning messages:
1: In plot.window(xlim, ylim, log = log, ...) :
графический параметр "type" устарел
2: In axis(if (horiz) 2 else 1, at = at.l, labels = names.arg, lty = axis.lty, :
графический параметр "type" устарел
3: In title(main = main, sub = sub, xlab = xlab, ylab = ylab, ...) :
графический параметр "type" устарел
4: In axis(if (horiz) 1 else 2, cex.axis = cex.axis, ...) :
графический параметр "type" устарел
in your book you calculate spreadR, but then you never use it?
great book by the way!
write.csv(aapl_2, file = "C:/aapl_2.csv")
save(aapl_2, file = "C:/aapl_2.csv.rdata")
aapl_old <- aapl_2
rm(aapl_2)
load(file = "C:/aapl_2.rdata")
Error in readChar(con, 5L, useBytes = TRUE) : cannot open the connection
In addition: Warning message:
In readChar(con, 5L, useBytes = TRUE) :
cannot open compressed file 'C:/aapl_2.rdata', probable reason 'No such file or directory'
identical(aapl_old, aapl_2)
Error in identical(aapl_old, aapl_2) : object 'aapl_2' not found
First, thank you for writing the book. It is very well written.
I am having some trouble of reproducing the results on page 125.
I found that beta = 0.3853952 and level = 3.658218 which was drastically different from 4.92 and - 239.06 presented in the book. I merely copied and pasted the code and didn't make any changes.
Thanks
> # Get the data
> SPY <- getSymbols('SPY', from = '2011-01-01',
+ to = '2012-12-31', adjust = T, auto.assign = FALSE)
> AAPL <- getSymbols('AAPL', from = '2011-01-01',
+ to = '2012-12-31', adjust = T, auto.assign = FALSE)
> # Compute price differences
> x <- diff(as.numeric(SPY[, 4]))
> y <- diff(as.numeric(AAPL[, 4]))
> plot(x, y, main = "Scatter plot of returns. SPY vs. AAPL",
+ cex.main = 0.8, cex.lab = 0.8, cex.axis = 0.8)
> abline(lm(x ~ y), lty = 2)
> # Total least squares regression
> grid()
> r <- prcomp( ~ x + y )
> intercept <- r$center[2] - slope * r$center[1]
Error: object 'slope' not found
> abline(lm(y ~ x))
> slope <- r$rotation[2, 1] / r$rotation[1, 1]
> # Show the first principle component on the plot
> abline(a = intercept, b = slope, lty = 3)
Error in abline(a = intercept, b = slope, lty = 3) :
object 'intercept' not found
> slope <- r$rotation[2, 1] / r$rotation[1, 1]
> intercept <- r$center[2] - slope * r$center[1]
> # Show the first principle component on the plot
> abline(a = intercept, b = slope, lty = 3)
> ###########################
> # Constructing the spread #
> ###########################
> # Function to calculate the spread
> calculate_spread <- function(x, y, beta) {
+ return(y - beta * x)
+ }
> # Function to calculate the beta and level
> # given start and end dates
> calculate_beta_and_level <- function(x, y,
+ start_date, end_date) {
+ require(xts)
+ time_range <- paste(start_date, "::",
+ end_date, sep = "")
+ x <- x[time_range]
+ y <- y[time_range]
+ dx <- diff(x[time_range])
+ dy <- diff(y[time_range])
+ r <- prcomp( ~ dx + dy)
+ beta <- r$rotation[2, 1] / r$rotation[1, 1]
+ spread <- calculate_spread(x, y, beta)
+ names(spread) <- "spread"
+ level <- mean(spread, na.rm = TRUE)
+ outL <- list()
+ outL$spread <- spread
+ outL$beta <- beta
+ outL$level <- level
+ return(outL)
+ }
> # Function to calculate buy and sell signals
> # with upper and lower threshold
> calculate_buy_sell_signals <- function(spread, beta,
+ level, lower_threshold, upper_threshold) {
+ buy_signals <- ifelse(spread <= level -
+ lower_threshold, 1, 0)
+ sell_signals <- ifelse(spread >= level +
+ upper_threshold, 1, 0)
+ # bind these vectors into a matrix
+ output <- cbind(spread, buy_signals,
+ sell_signals)
+ colnames(output) <- c("spread", "buy_signals",
+ "sell_signals")
+ return(output)
+ }
> # Implementation
> # Pick an in-sample date range
> start_date <- "2009-01-01"
> end_date <- "2011-12-31"
> x <- SPY[, 6]
> y <- AAPL[, 6]
> results <- calculate_beta_and_level(x, y,
+ start_date, end_date)
>
>
>
>
>
>
> results$beta
[1] 0.3853952
>
>
> results$level
[1] 3.658218
`
require(RODBC)
con <- odbcConnect("rfortraders")
Warning messages:
1: In odbcDriverConnect("DSN=rfortraders") :
[RODBC] ERROR: state IM002, code 0, message [Microsoft][Диспетчер драйверов ODBC] Источник данных не найден и не указан драйвер, используемый по умолчанию
2: In odbcDriverConnect("DSN=rfortraders") : ODBC connection faileddatabase_name <- "OptionsData"
table_name <- "ATMVolatilities"
symbol <- "SPY"sql_command <- paste0("SELECT Symbol, Date, Maturity,
- Delta, CallPut, ImpliedVolatility
- FROM ", database_name, ".", table_name,
- " WHERE Maturity = 91
- AND Symbol IN ('", symbol, "');")
iv <- sqlQuery(con, sql_command)
Error in sqlQuery(con, sql_command) :
first argument is not an open RODBC channelodbcClose(con)
Error in odbcClose(con) : argument is not an open RODBC channelhead(iv)
Error in head(iv) : object 'iv' not found
In the code errata on line 107 buy signals are created when the spread is below the threshold,
Yet on line 255, buys are created when the spread is above the threshold, this doesn't make sense.
https://github.com/hgeorgako/rfortraders/blob/master/Chapter_06/code.R
buy_signals <- ifelse(spread <= level -
lower_threshold, 1, 0)
buys <- ifelse(data_out$spread > threshold, 1, 0)
Нельзя идти дальше и читать и стараться работать - везде огромное количество ошибок, для которых нет никакого объяснения в R & StackOverflow общин
RStudio
aapl_2 <- read.csv (файл = "C: /aapl.csv", заголовок = TRUE, stringsAsFactors = FALSE)
Предупреждающие сообщения:
1: графический параметр "тип" устарел
2: "типа" графический параметр устарел
3: графический параметр " типа "устарел
4: графический параметр" тип "устарел
5: графический параметр" тип "устарел
6: графический параметр" тип "устарел
7: графический параметр" тип "устарел
8: графический параметр" тип "устарел
aapl_2 <- read.csv ( File = "C: /aapl.csv", заголовок = True, stringsAsFactors = ЛОЖЬ)
aapl_2 <- aapl_2 [об (rownames (aapl_2)),]
aapl_close <- aapl_2 [ "Закрыть"]
Ошибка в aapl_2 [ "Закрыть "]: неправильное количество размеры
резюме (aapl_close)
Ошибка в резюме (aapl_close): Object 'aapl_close' не найден
RGui
aapl_2 <- read.csv (файл = "C: /aapl.csv", заголовок = TRUE, stringsAsFactors = ЛОЖЬ)
aapl_2 <- aapl_2 [об (rownames (aapl_2)),]
aapl_close <- aapl_2 [ "Закрыть"]
ошибка в aapl_2 [ "Закрыть"]: неправильное количество измерений
резюме (aapl_close)
ошибка в сводной (aapl_close): объект 'aapl_close' не найден
Please give me some advice , what should I do to avoid these errors?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.