En el siguiente post hare uso del algoritmo de DTW de la libreria dtw
Algoritmo dtw
library(quantmod) # graphics finace and data
library(dtw) # dinamic time warping
library(PerformanceAnalytics) # multiple tools for finance
dtwEste ejemplo se puede encontrar en la documentación del paquete usando la siguiente ?dtw
## A noisy sine wave as query
idx<-seq(0,6.28,len=100);
query<-sin(idx)+runif(100)/10;
## A cosine is for template; sin and cos are offset by 25 samples
template<-cos(idx)
## Find the best match with the canonical recursion formula
alignment<-dtw(query,template,keep=TRUE);
## Align and plot with the Rabiner-Juang type VI-c unsmoothed recursion
plot( dtw(query,template,keep=TRUE,
step=rabinerJuangStepPattern(6,"c")),
type="twoway", main="DTW Optimal Match")
legend("bottomleft",legend=c("Cosine","Noisy Sine"), text.col=c("red","black"), lty=c(2,1), col=c("red","black"))
Nota: Algunos países no son tomados por razones del autor
# stock money´s analysis
# latin America
getFX("USD/PEN") # peruvian currency
## [1] "USD/PEN"
getFX("USD/CLP") # chilean currency
## [1] "USD/CLP"
getFX("USD/COP") # colombian currency
## [1] "USD/COP"
getFX("USD/BRL") # brazilian currency
## [1] "USD/BRL"
getFX("USD/BOB") # bolivian currency
## [1] "USD/BOB"
getFX("USD/MXN") # mexican currency
## [1] "USD/MXN"
coins <- data.frame(USDBOB,USDBRL,USDCLP,USDCOP,USDMXN,USDPEN)
colnames(coins)<- c("bolivia","brazil","chile","colombia","mexico","peru")
coins <- data.frame(USDBOB,USDBRL,USDCLP,USDCOP,USDMXN,USDPEN)
colnames(coins)<- c("bolivia","brazil","chile","colombia","mexico","peru")
knitr::kable(coins[1:8,])
| bolivia | brazil | chile | colombia | mexico | peru | |
|---|---|---|---|---|---|---|
| 2020-05-05 | 6.897586 | 5.552686 | 836.9811 | 3964.686 | 23.98359 | 3.384531 |
| 2020-05-06 | 6.892268 | 5.633798 | 837.7839 | 3939.053 | 24.17606 | 3.388430 |
| 2020-05-07 | 6.892734 | 5.773538 | 840.8465 | 3946.198 | 24.17115 | 3.399998 |
| 2020-05-08 | 6.884158 | 5.792438 | 832.7296 | 3921.016 | 23.82004 | 3.398097 |
| 2020-05-09 | 6.892138 | 5.727875 | 825.7750 | 3921.073 | 23.64481 | 3.397475 |
| 2020-05-10 | 6.892138 | 5.728106 | 825.7781 | 3919.393 | 23.65333 | 3.397977 |
| 2020-05-11 | 6.893194 | 5.770768 | 825.4496 | 3896.194 | 23.78798 | 3.410192 |
| 2020-05-12 | 6.897111 | 5.823888 | 823.8733 | 3890.276 | 24.07359 | 3.420316 |
Se generan los siguientes gráficos para una mejor visualización de las series de tiempo:
chart.TimeSeries(scale(coins),legend.loc = "topleft")
plot.ts(coins)
Se puede ver que bolivia se mueve entorno a una media esto puede indicar que es estacionaria para esto se usa el paquete tseries
library(tseries) # for test dicker-fuller
v<- vector()
for(i in 1:dim(coins)[2]){
v[i]<-adf.test(coins[,i])$p.value
}
ata<-c("bolivia","brazil","chile","colombia","mexico","peru")
datos<- data.frame("paises"=ata,"p-values"=v)
knitr::kable(datos)
| paises | p.values |
|---|---|
| bolivia | 0.0177946 |
| brazil | 0.1998313 |
| chile | 0.1427271 |
| colombia | 0.1059194 |
| mexico | 0.1816146 |
| peru | 0.3187079 |
Nota: El p-value tiene que ser menor a 0.05 para que la serie sea estacionaria la unica de las 6 que cumple esto es bolvia con un p-vaule de 0.02 aproxiamadamente.
Se generan los graáficos de Dynamic time warping tomando como punto de comparación a perú
layout(1)
x=5
data<-coins[,-x]
l<- 5
i=1
ata<- colnames(coins)
d<- ata[6]
a<- ata[-6]
while(i <= l){
plot( dtw(scale(coins[,x]),scale(data[,i]),keep=TRUE,
step=rabinerJuangStepPattern(6,"c")),
type="twoway", main="DTW Optimal Match")
legend("topright",legend=c(a[i],d), text.col=c("red","black"),
lty=c(2,1), col=c("red","black"))
i=i+1
}
Ahora se procede a la creación de un dendograma lo que indicara una similitud entre las series dadas
ad<- t(Return.calculate(coins,method = "log")[-1,])
modelo<- hclust(dist(ad,method = "dtw"))
plot(modelo)
ata1<-rect.hclust(modelo,k=2,border = "blue")
Nota: Se tomo los retornos de los tipos de cambio lo que se puede ver que entre bolivia y perú hay una mayor similitud y brazil no presenta similitud con nínguno de estos,
Ahora se procede a una mejor vizualisación del dendograma
library(scales)
library(hrbrthemes)
library(dendextend)
library(factoextra)
library(NbClust)
library(pvclust)
library(flexclust)
library(readxl)
fviz_dend(modelo,k = 2,
cex = 0.7,
k_colors = c("#0040FF", "red"),
color_labels_by_k = TRUE,
rect = TRUE,
rect_border = c("#00FFFF",alpha("#FF00FF",0.5)),
rect_fill = TRUE,horiz = F)+
labs(title = "Dendrograma del tipo de cambio de las monedas latinoamricanas , 2020",
subtitle = "(K = 2)",
caption = NULL,
x = NULL,
y = NULL,
fill = NULL) +
xlab(NULL)+
ylab(NULL)+
theme(panel.grid.major.x = element_blank(),
legend.position = "right")+theme_modern_rc()
Algoritmo dtw