開始使用免費開始

tidyquant 套件

tidyquant 套件專注於以最簡單的方式擷取、處理並擴展金融資料分析。若要取得並開始使用 tidyquant,你需要先安裝它。

install.packages("tidyquant")

這會把套件安裝到你的本機電腦。接著,你必須在目前的 R 工作階段載入它,才能使用套件裡的所有函式。

library(tidyquant)

安裝並載入(library)套件是你使用任何 CRAN 套件時都需要的步驟。

本題的程式碼已經為你寫好。你將探索 tidyquant 中一些用於金融分析的函式。

本練習屬於課程

R 金融中級

檢視課程

練習說明

程式碼已經寫好,但以下說明會帶你逐步完成每一步。

  • 先載入套件以使用其中的函式。
  • 使用 tidyquanttq_get() 來取得 Apple 的股價資料。
  • 檢視回傳的資料框。
  • 繪製股價隨時間變化的圖。
  • 使用 tq_mutate() 計算經調整股價的日報酬。此函式會「變異」你的資料框,新增一個欄位;在這裡,新欄位就是日報酬。
  • 將報酬排序。
  • 繪製排序後的報酬圖。你會看到 Apple 有幾天的虧損超過 10%,也有不少天的報酬高於 5%。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Library tidquant
library(tidyquant)

# Pull Apple stock data
apple <- tq_get("AAPL", get = "stock.prices", 
                from = "2007-01-03", to = "2017-06-05")

# Take a look at what it returned
head(apple)

# Plot the stock price over time
plot(apple$date, apple$adjusted, type = "l")

# Calculate daily stock returns for the adjusted price
apple <- tq_mutate(data = apple,
                   select = "adjusted",
                   mutate_fun = dailyReturn)

# Sort the returns from least to greatest
sorted_returns <- sort(apple$daily.returns)

# Plot them
plot(sorted_returns)
編輯並執行程式碼