[R-SIG-Finance] Daily dividend yield
G See
gsee000 at gmail.com
Mon Oct 15 04:39:26 CEST 2012
Hi Frank,
> 1) I have downloaded both the dividends and the OHLCVAdjC data successfully. When I merge the data with fill=0.0 and export the merged data with write.csv, the date is replaced with the index from 1 to 52, first few lines:
I suggest using write.zoo(). But, you can also consult ?write.table
and the R Data Import/Export manual
(http://cran.r-project.org/doc/manuals/R-data.html)
> 2) Divs contains the dividend date and the 1 dividend 0.20. Stock contains theOHLVAdjC data for Microsoft. I can print the dates using Divs[1,0] and Stock[1,0] but a comparison of those dates always results in an error:
What looks like Dates to you is actually a zero-width xts object.
This is the line that's giving you trouble
if ((Stock[i,0]) == (Divs[j,0])) Current_Div <- Divs[j,1]
If you are trying to compare indexes, maybe something along these
lines would work better.
index(Stock[i]) == index(Divs[j])
#----
> if (Stock[i, 0] == Divs[1, 0]) print("equal")
Error in if (Stock[i, 0] == Divs[1, 0]) print("equal") :
argument is of length zero
> Divs[1, 0]
2012-08-14
> length(Divs[1, 0])
[1] 0
> index(Divs[1])
[1] "2012-08-14"
> if (index(Stock[i]) == index(Divs[1])) print("equal") # no error
#----
That said, I'm fairly confident that you should not use a (double) for
loop for this. I can't quite tell from your code what you're trying
to do, but if you provide your desired output, I'm sure we can come up
with a vectorized solution.
For example, if you want to multiply the last quarterly dividend
amount by 4 and use that value every day until the next dividend, you
can do the following:
# Setup based on original question
Divs_Per_Year<-4
startDate=as.Date("2012-05-01")
endDate=as.Date("2012-10-13")
Divs<-getDividends(ticker, from = startDate, to = endDate)
Stock <- getSymbols(ticker, from=startDate, to=endDate, src='yahoo',
auto.assign=FALSE)
# End setup
na.locf(merge(Stock, Divs * Divs_Per_Year, retside=c(FALSE, TRUE)))
Or, if you want to do basically the same thing, but divide the current
estimate for the annual dividend amount by the most recent price in
order to calculate the current yield, you can do this:
with(na.locf(merge(Stock, AnnDiv=Divs * Divs_Per_Year)), AnnDiv /
MSFT.Adjusted)
HTH,
Garrett
On Sat, Oct 13, 2012 at 10:29 PM, FJ M <chicagobrownblue at hotmail.com> wrote:
>
> I'm trying to calculate the current yield for MSFT using the most recent dividend and daily closing price of MSFT. I've tried a couple of approaches that don't work, any suggestions would be appreciated.
More information about the R-SIG-Finance
mailing list