How to group data then apply functions to the grouped data?
- To: mathgroup at smc.vnet.net
- Subject: [mg119501] How to group data then apply functions to the grouped data?
- From: Tyler <hayes.tyler at gmail.com>
- Date: Tue, 7 Jun 2011 06:46:02 -0400 (EDT)
Hi Everyone: Below is a snippet of code to calculate the annualized returns for a ten year set of data. Ultimately, I want to find the "ten-year annualized returns." I know, cryptic. But, as I understand it, it is to find the average annualized return over the last ten years. In other words, find the annualized return for each year, then average (if you think that's wrong, let me know!). So in my mind the challenge before me is to work on the data in one-year chunks (one year defined as March 31 to March 31) much the same way a SQL query would group the data. So, the big question, how would any of you suggest I group efficiently? Any suggestions are greatly appreciated. Cheers, t. (* TSX Composite Index *) data = FinancialData["^GSPTSE", {{2001, 3, 31}, {2011, 3, 31}}]; px = data[[;; , 2]]; dates = data[[;; , 1]]; period = 252; (* number of trading days *) (* Arithmetic Returns *) aret = Differences[px]/Rest[px]; (* Log Returns *) lnret = Differences[Log[px]]; (* Find Annualized Arithmetic Returns - must be a better way to code this *) annualizeAret = ( Product[(1 + aret[[i]]), {i, Length[aret]}])^(period/Length[aret]) - 1 (* Find Annualized Logarithmic Returns *) annualizeLNret = Mean[lnret]*(period)