2012-07-30 32 views
5

Soy un novato en R y ha sido muy útil utilizar su sitio web. Desafortunadamente he estado luchando con mi código ahora durante dos días, así que quería para hacer algunas preguntas. He intentado crear buenos gráficos para ponerlos en una hoja de pdf , pero estoy teniendo pequeños problemas con todos los paquetes que he usado . Entonces, lo que quiero lograr es crear una hoja pdf con tres gráficos y una tabla de correlación. A continuación se muestra un ejemplo que he creado que es muy similar a lo que quiero hacer, pero hay algunas cosas que me gustaría cambiar. Estoy usando chartSeries en quantmod para los gráficos y para la tabla Estoy usando textplot.Trabajando con chartSeries en quantmod

algunas preguntas:

  1. ¿Es posible eliminar la fecha en la esquina superior derecha de los gráficos ?
  2. En lugar del texto Last xxxx (el texto de la serie verde), me gustaría obtener el nombre de la serie en sí, p. Ej. MSFT, ¿es eso factible?
  3. ¿Cómo puedo dar los nombres de los ejes, p. ¿Fecha de regreso?
  4. En el gráfico de Diferencia acumulativa estoy usando el addVo() y esa función le da a este bonito barPlot. En los otros gráficos no estoy usando addVo() simplemente addTA y type = 'h' y puede ver la diferencia de las gráficas de barra/histograma . ¿Es posible obtener la misma trama usando addTA como en addVo?
  5. ¿Hay alguna manera de ajustar mejor la tabla de correlación y hacerlo más profesional? Es tal vez otra función mejor?

mejor,

OTB

install.packages("quantmod") 
install.packages("gplots") 
library(quantmod) 
library(gplots) 

#setwd("..........") 

getSymbols("MSFT") 
getSymbols("AAPL") 
getSymbols("COKE") 
getSymbols("PEP") 

#Get the return 
MSFT.Return <- diff(MSFT)/lag(MSFT) 
AAPL.Return <- diff(AAPL)/lag(AAPL) 
COKE.Return <- diff(COKE)/lag(COKE) 
PEP.Return <- diff(PEP)/lag(PEP) 

#Get the return for last two months and only get close price return. 
#because in my data I only have the close price. 
MSFT.Close <- MSFT.Return['2012-06-01::2012-07-27', 'MSFT.Close'] 
AAPL.Close <- AAPL.Return['2012-06-01::2012-07-27', 'AAPL.Close'] 
COKE.Close <- COKE.Return['2012-06-01::2012-07-27', 'COKE.Close'] 
PEP.Close <- PEP.Return['2012-06-01::2012-07-27', 'PEP.Close'] 

pdf(sprintf("%s.pdf","ExampleGraph"), width=11.69, height=8.27) 

layout(matrix(1:8, nrow=4)) 

#Get the difference in return 
techDifference <- MSFT.Close - AAPL.Close 
bevDifference <- COKE.Close - PEP.Close 

#Rename columns 
colnames(MSFT.Close)[1] <- "MSFT" 
colnames(AAPL.Close)[1] <- "AAPL" 
colnames(techDifference)[1] <- "Difference" 

colnames(COKE.Close)[1] <- "COKE" 
colnames(PEP.Close)[1] <- "PEP" 
colnames(bevDifference)[1] <- "Difference" 

#Combine into two tables 
tech <- cbind(MSFT.Close,AAPL.Close,techDifference) 
bev <- cbind(COKE.Close,PEP.Close,bevDifference) 

#Plot charts 
chartSeries(tech, order=1,up.col='green', name='MSFT & AAPL', layout=NULL, 
TA=c("addTA(tech,order=2,on=1,layout=NULL); 
addTA(tech$Difference,legend='Difference',type='h',layout=NULL)")) 

chartSeries(bev, order=1,up.col='green', name='COKE & PEP', layout=NULL, 
TA=c("addTA(bev,order=2,on=1,layout=NULL); 
addTA(bevDifference$Difference,legend='Difference',type='h',layout=NULL)")) 

#Take the cumulative difference for each sector 
techCumulative <- cumsum(abs(techDifference)) 
bevCumulative <- cumsum(abs(bevDifference)) 
diffCumulative <- techCumulative - bevCumulative 

#Rename columns 
colnames(techCumulative)[1] <- "Tech" 
colnames(bevCumulative)[1] <- "Beverage" 
#If I set the name as Volume, I can use addVo() and get nice barplot. 
#Problem with that is the legend name will be Volume but I would like to 
#have it Difference and of course I'm using wrong column name. 
colnames(diffCumulative)[1] <- "Volume" 

#Combine into one table 
cumulative <- cbind(techCumulative,bevCumulative,diffCumulative) 

#Plot chart 
chartSeries(cumulative,order=1,up.col='green', name='Cumulative Difference', layout=NULL, 
TA=c("addTA(cumulative,order=2,on=1,layout=NULL)", addVo())) 

#Get the correlation matrix 
correlationTable <- cbind(tech[,1:2],bev[,1:2]) 
correlation <- cor(correlationTable) 
corTable <- as.table(correlation) 
corrFormatted <- formatC(corTable, format = "f", digits = 3) 
textplot(corrFormatted,valign="top",col.data=colors()[300], 
col.rownames=colors()[300],col.colnames=colors()[300]) 
title("Correlation",cex.main=2.5,col.main=colors()[300]) 

dev.off() 

Respuesta

2

Algunas buenas preguntas.

P1: No. quantmod:::chartSeries.chob tiene este código:

old.adj <- par('adj') 
par('adj'=0) 
do.call('title',list([email protected], [email protected]$fg.col)) 
par('adj'=1) 
do.call('title',list(paste('[',start(xx),'/',end(xx),']', sep='') 
        ,[email protected]$main.col)) 
par('adj'=old.adj) 

es decir, el bit de inicio (xx)/fin (xx) está codificado.

Q2. Una vez más, parece estar codificado-(misma función):

if([email protected]=='line') { 
    lines(x.pos,Closes,[email protected]$up.col,[email protected]) 
    main.key <- c(list(list(legend= 
         paste('Last',last(Closes)), 
         [email protected]$up.col)),main.key) 
} 

(no pude encontrar nada en mis estudios sobre el código fuente para ayudar con Q3/Q4/Q5, lo siento)

+0

Hola Darren, muchas gracias por tus respuestas, al menos es bueno saber que no es posible. Agradecería que alguien pudiera responder las otras preguntas. – OTB

Cuestiones relacionadas