2018年11月1日木曜日

Date Format Conversion mondate() index() format()





October 2018 was quite wild. Let us see the historical data on the other occasion. There were only 9 cases in 11 years, when the lowest price of the month is more than 11% lower than the open.

> to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1][to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1] < 0.89]
         GSPC.Low
 1 2008 0.8651744
 9 2008 0.8591352
10 2008 0.7213723
11 2008 0.7649871
 5 2010 0.8756500
 8 2011 0.8521960
 8 2015 0.8871556
 1 2016 0.8891620
10 2018 0.8897068

Use "as.mondate" to calculate one month after the examples.

> as.mondate(index(to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1][to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1] < 0.89])[-8])+1
mondate: timeunits="months"
[1] 2008-02-01 2008-10-02 2008-11-01 2008-12-02 2010-06-01 2011-09-01 2015-09-01 2018-11-01

use "format()" to normalize. "%Y-%m" should be the option.

> format(as.mondate(index(to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1][to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1] < 0.89])[-9])+1,"%y-%m")
[1] "08-02" "08-10" "08-11" "08-12" "10-06" "11-09" "15-09" "16-02"


> format(as.mondate(index(to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1][to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1] < 0.89])[-9])+1,"%Y-%m")
[1] "2008-02" "2008-10" "2008-11" "2008-12" "2010-06" "2011-09" "2015-09" "2016-02"

But index() returns yearmon calss and the direct coversion from yearmon to mondate triggers the warning message. If you don't like it, insert "as.Date()" between them.

警告メッセージ:
Attempting to convert class 'yearmon' to 'mondate' via 'as.Date' then 'as.numeric'. Check results!

> format(as.mondate(as.Date(index(to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1][to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1] < 0.89]) ))+1,"%Y-%m")[-9]
[1] "2008-02" "2008-10" "2008-11" "2008-12" "2010-06" "2011-09" "2015-09" "2016-02"

The result was disappointing. Hope, this month is exceptional.

> monthlyReturn(GSPC)[format(as.mondate(index(to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1][to.monthly(GSPC)[,3]/to.monthly(GSPC)[,1] < 0.89])[-9])+1,"%Y-%m")]
           monthly.returns
2008-02-29    -0.034761193
2008-10-31    -0.169424524
2008-11-28    -0.074849043
2008-12-31     0.007821577
2010-06-30    -0.053882442
2011-09-30    -0.071761988
2015-09-30    -0.026442832
2016-02-29    -0.004128360

you can do the similar calculation for monthlyReturn().

0 件のコメント: