Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Request: Calculating Returns for custom time periods #200

Open
bhattmaulik opened this issue Jun 8, 2021 · 0 comments
Open

Feature Request: Calculating Returns for custom time periods #200

bhattmaulik opened this issue Jun 8, 2021 · 0 comments

Comments

@bhattmaulik
Copy link

I want to calculate returns (arithmetic returns or log returns) for custom time period. In the package, we can calculate returns for monthly or yearly. But in my country, financial year begins from 1st April, and ends on 31st March. I want to calculate returns for this financial year. In the function tq_performance, is there a way to specify when the year begins, and when the year ends? For the time being, I have come up with a workaround. I am attaching its code below. But can we have any simple solution to this?
`# Get data
library("tibble")
library("tidyquant")
RIL<- tq_get("RELIANCE.NS")
RIL1<- RIL %>% mutate(CalYear = year(date),
Month = month(date),
FinYear = if_else(Month<4,CalYear,CalYear+1))

Get minimum and max dates in each year

start_dates = c()
end_dates = c()
for(year in format(min(RIL1$date),"%Y"):format(max(RIL1$date),"%Y")){
start_dates =
c(start_dates,
min(RIL1$date[format(RIL1$date, "%Y") == format(as.Date(ISOdate(year, 1, 1)),"%Y")])
)
end_dates =
c(end_dates,
max(RIL1$date[format(RIL1$date, "%Y") == format(as.Date(ISOdate(year, 1, 1)),"%Y")])
)
}

Get filtered data

RIL2 <- RIL1[(RIL1$date %in% start_dates | RIL1$date %in% end_dates),]

Get log returns, even indexes represent end of each year rows

end_adjusted = RIL2$adjusted[1:length(RIL2$adjusted) %% 2 == 0]
beginning_adjusted = RIL2$adjusted[1:length(RIL2$adjusted) %% 2 != 0]
log_returns = log(end_adjusted/beginning_adjusted)

Put log returns and years in a tibble.

result = tibble(log_returns ,format(RIL2$date[1:length(RIL2$date) %% 2 == 0], "%Y"))

Result

result`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant