将不同日期的多个标准化股票图表绘制到单个图中

问题描述 投票:0回答:1

我想下载不同日期的股票数据,标准化它们的回报并将时间与时间 0 对齐,并将该系列绘制在单个图中,以便我可以直观地比较它们随时间的表现。

我有以下脚本:

library(quantmod)
library(ggplot2)

Symbols=spl('AAPL,C')
dates_from=spl('2000-1-1,2008-1-1')
dates_to=spl('2000-12-1,2008-12-1')
noS = length(Symbols)
dataEnv<-new.env()
for(i in 1:noS) getSymbols(Symbols[[i]], src = "yahoo", from=dates_from[[i]], to=dates_to[[i]],env=dataEnv, auto.assign = T, use.Adjusted=T)
for(i in ls(dataEnv)) dataEnv[[i]] = Ad(dataEnv[[i]])#Use adjusted data

# Normalize the series to start from the same point (time 0)

for (i in ls(dataEnv)) {
 dataEnv[[i]] = dataEnv[[i]]/ coredata(dataEnv[[i]])[1]
}
for (i in ls(dataEnv)) {
 dataEnv[[i]] = data.frame(Date = 1:length(dataEnv[[i]]), Price = coredata(dataEnv[[i]]))
}

# Ensure column names are correct and create a single plot for each symbol in dataEnv
for (symbol in ls(dataEnv)) {
  df <- dataEnv[[symbol]]
  names(df) <- c("Date", "Price") # Ensure correct column names
  plot <- ggplot(df, aes(x = Date, y = Price)) +
    geom_line() +
    ggtitle(paste("Normalized Price Series for", symbol)) +
    xlab("Time") +
    ylab("Normalized Price") +
    theme_minimal()
  print(plot)
}

# I want to draw all the series into a single plot instead

我能够绘制多个单独的图,但在将不同系列组合成单个图时遇到问题。我尝试过的各种解决方案将数据帧与大量 NA 结合起来,因为该系列有不同的日期。

r ggplot2 plot
1个回答
0
投票

在单个图中绘制所有单独系列的最简单方法是将它们组合在单个数据框中。我已经调整了您的整个工作流程以简化流程,这不会影响您现有的绘图代码。

library(quantmod)
library(ggplot2)

Symbols <- strsplit("AAPL,C", ",")[[1]]
dates_from <- as.Date(strsplit("2000-1-1,2008-1-1", ",")[[1]])
dates_to <- as.Date(strsplit("2000-12-1,2008-12-1", ",")[[1]])
noS <- length(Symbols)
dataEnv <- new.env()

# Download and process data
for(i in 1:noS) {
  
  getSymbols(Symbols[[i]],
             src = "yahoo",
             from = dates_from[[i]],
             to = dates_to[[i]],
             env = dataEnv,
             auto.assign = TRUE,
             use.Adjusted = TRUE)
  
  dataEnv[[Symbols[i]]] <- Ad(dataEnv[[Symbols[i]]])
  
  colnames(dataEnv[[Symbols[i]]]) <- "Price"
  
}

# Normalize the series to start from the same point, add Symbol column
for (symbol in ls(dataEnv)) {
  
  dataEnv[[symbol]] <- dataEnv[[symbol]] / coredata(dataEnv[[symbol]])[1]
  
}

for (i in ls(dataEnv)) {

  dataEnv[[i]] = data.frame(Date = 1:length(dataEnv[[i]]),
                            Price = coredata(dataEnv[[i]]),
                            Symbol = i)

}

# Function to retrieve xts objects from dataEnv
df_list <- lapply(ls(dataEnv), function(symbol) {
  
  data <- coredata(dataEnv[[symbol]])
  
})

# Combine all dataEnv dataframes
df <- do.call(rbind, df_list)

# Plot all series in single plot, use Symbol column to group and colour each series
ggplot(df, aes(x = Date, y = Price, group = Symbol, colour = Symbol)) +
  geom_line() +
  ggtitle("Normalized Price Series") +
  xlab("Time") +
  ylab("Normalized Price") +
  theme_minimal()

1

© www.soinside.com 2019 - 2024. All rights reserved.