Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to compute difference in years between daily dates?

    I have daily stock data, inputted and formatted properly for stata. I wish to calculate the return on that stock from one period to 1,2,3...10 years prior.

    My current code is:
    Code:
    gen date = date(date_str,"YMD")
    format %td date
    tsset date
    
    forvalues t=1(1)10 {
        local days = `t' * 365
        gen d`t'y_close = close - L`days'.close
    }
    
    forvalues t=1(1)10 {
        di "`t' years return"
        di "number of days in which return was negative or zero"
        count if d`t'y_close <= 0
        di "total number of non missing days"
        count if d`t'y_close 
    }
    I have two questions regarding this:
    1. Currently, I manually calculate the number of days (as the data is daily) as products of 365 days a year and number of years I'm interested in. Is there a more elegant way to do so? a command that decreases X years from a given date, and handles leap years etc. appropriately?

    2. Sometimes, "5 years prior" to a specific date falls on a day which doesn't exist in the data as there's no trade on this day (sunday, holidays, etc.). Is there a way to create an expression (i thought using cond but I think it's gonna amount to lots of nesting conds), in which the logic is "if X years prior to given date is missing, go the smallest amount of days backward and use that date instead"?

    Thank you

  • #2
    There are probably more elegant solutions, but three options you might consider:

    1) Since you have all trading days, you might use 250 trading days as your measure of a year (most years have 250, 251 or 252 trading days) rather than 365 or 366 calendar days.

    2) I assume you pulled your data from CRSP or WRDS. If you have access to EVENTUS through WRDS, EVENTUS will take care of this for you.

    3) There are several user-contributed commands that you could use: ascol (SSC) converts daily stock prices to annual returns. You might also look at asrol and asreg. rangerun and rangestat would also work. (All are on SSC)

    Comment

    Working...
    X