Help us understand the problem. What is going on with this article?

tidyquantでバックテスト

Rでデータ操作と言えばTidyverseですが、RでQuantsと言えばQuantmodでしたが、最近の人はtidyquantなのでしょうか?
時系列操作というジャンルではtsibbleも便利なので難しいところですね。
今回はtidyquantを使って単純なストラテジーのバックテスト例を書いてみいます。

ライブラリを読み込んで組み込みデータを確認します。

require(tidyquant)
data(FANG)

FANG %>% select(symbol, date, adjusted) %>% 
  ggplot(aes(x = date, y = adjusted, colour = symbol)) +
  geom_line() +
  theme_tq() +
  scale_color_tq()+
  labs(title = "price")

image.png

EMA(20)を計算します。

term1 <- FANG %>% group_by(symbol) %>%
  tq_mutate(select = adjusted,
            mutate_fun = EMA, n = 20,
            col_rename = "ema")

リターン計算に使うROCを計算します。

term2 <- term1 %>% tq_mutate(select = adjusted,
                             mutate_fun = ROC,
                             col_rename = "roc")

シグナルとリターンを計算します。シグナルの発生から発注にはラグが発生するので注意が必要です。buy next bar at market;ということです。

term3 <- term2 %>% mutate(sig = lag(if_else(adjusted > ema, 1, -1)),
                          ret = roc * sig)

リターンの推移を確認します。

term3 %>% select(symbol, date, ret) %>% drop_na %>% 
  ggplot(aes(x=date, y=ret, colour = symbol)) +
  geom_line() +
  theme_tq()

image.png

累積リターンを可視化します。

term3 %>% drop_na %>% mutate(eq = cumsum(ret)) %>% 
  select(symbol, date, eq) %>% 
  ggplot(aes(x = date,y = eq, colour = symbol)) +
  geom_line()+
  theme_tq()+
  scale_color_tq()+
  geom_hline(colour = "darkgray", yintercept = 0)

image.png

もっと複雑なストラテジーも簡単にテストできます。
コスト計算やポートフォリオリターンについての分析も必要です気が向いたらそれらについても記事を書きます。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away