Simple Pound

A trip down personal finance lane.
  • rss
  • Home
  • About
  • Best Of…
  • Progress
  • Library
  • Book reviews
  • Archive
  • Contact

Geometric mean with negative numbers

July 12, 2008

This won’t quite be a conventional Personal Finance post, but the fact that I cannot calculate my portfolio’s performance without converting negative returns into “false positive” ones annoyed me too much to just ignore. Since I couldn’t find a straightforward way around it, I decided to simply code the Excel function I was looking for myself.

While the code is by no means perfect (yet) it does the job nicely and I’m nevertheless pleased with the result. As long as it gets called properly, it converts your negative percentages into a value equivalent to (100 - x) / 100 where x is your percentage. For positive values, it does the conversion according to (100 + x) / 100. These conversions means that a decrease of 10% will be expressed as 0.9 and an increase of 10% as 1.1 which subsequently allows you to compute the geometric mean (which is exactly what it does).

Below is the VBA code you will need to utilise this functionality. Feel free to use it as you please but don’t worry if you have no clue how exactly to do that. I have included a step-by-step description of how to install and call it from your Excel worksheet underneath the code.

Function geometric(data As Variant)
     Dim vaData As Variant
     Dim rnData As Range
     Dim i As Long
     Dim j As Long
     Dim iblank As Long
     Dim jblank As Long
     Dim bblank As Boolean
     Set rnData = data
     vaData = rnData.Value
     temp = 1
     n = 0
     For j = 1 To UBound(vaData, 2)
          For i = 1 To UBound(vaData, 1)
               If vaData(i, j) <> Empty Then
                    vaData(i, j) = 1 + vaData(i, j)
                    ’ compute product for non-empty data cells
                    temp = temp * vaData(i, j)
                    ’ count number of items in list
                    n = n + 1
               End If
          Next i
     Next j
geometric = (temp ^ (1 / n)) - 1
End Function

Follow the steps below to make the above function available in your Excel worksheet:

  1. In Excel, open the file you want to use the function in. Note: at the moment the function will only be available on a per-file basis. That means, if you’re planning to use it in more than one file, you will need to repeat this procedure for every single file. I’m working on coding a proper add-on that you simply install into Excel and hence make available to any new or existing file. I told you it was work in progress… ;-)
  2. In the menu bar, next to the entry “File”, right-click on the Excel icon and select “View Code”
  3. The Microsoft Visual Basic Editor opens and you stare at a blank document
  4. In the menu bar, click on “Insert” followed by “Module”
  5. Copy and paste the above code into that “new” blank space and hit “Save”
  6. After you have saved the changes, click on “File” and select the entry “Close and return to Microsoft Excel”. This brings you back to where you started, and your function is ready to use.

Here is how you use the function:

  1. Open the file in which you have installed the above function
  2. Pick a cell that you want the result to contain and type “=geometric(”
  3. Note the opening bracket !
  4. With your mouse click and hold until you have highlighted the cell range that contains the numbers you want the geometric mean of. Alternatively, type the cell range yourself as A1:D4 where A1 should be replaced by the coordinates of your first cell and D4 should be replaced by the last cell’s identifier. At the moment, the geometric function only works with a cell range, not individual cells or numbers. I’m working on it… ;-)
  5. Close the bracket by typing “)”
  6. Hit ENTER to see the geometric mean of your highlighted cells

If you format the cell in question in such a way to convert your result back into a percentage (just right-click, choose Format - Number Format - Percentage), the result should make sense in the context of portfolio returns.

Note that the code above has been tested and verified in Excel 2002 and should work with any other Excel version(s) since. The only concern I have regards the compatibility with - you might guess it - Excel 2007. If anyone manages to run it under the new Office version, please let me know!

As usual, if you have questions or concerns, find a bug or just need a hand to get it to work, just give me a shout or leave a comment! I hope you will find it as useful as I did. :-D

Bookmark It

Add to Del.icio.us Add to digg Add to Facebook Add to Google Bookmarks Add to Newsvine Add to reddit Add to Stumble Upon Add to Technorati Add to Yahoo My Web
Hide Sites
Categories
Misc
Tags
calculations, Excel, geometric mean, portfolio, spreadsheets
Comments rss
Comments rss
Trackback
Trackback

« End of month review - June 2008 Change to Portfolio Return series »

13 responses

Ugly! What's wrong with the following? IF(x<0,=(100-x)/100,=(100+x)/100)

abc | July 14, 2008 | 12:53 pm

Ugly!

What’s wrong with the following?

IF(x<0,=(100-x)/100,=(100+x)/100)

That converts the percentage values, very true, but it doesn't

Kirsten | July 14, 2008 | 7:34 pm

That converts the percentage values, very true, but it doesn’t subsequently calculate the geometric mean for which you will need to (as you surely know L!) multiply all the values and then take the nth squareroot. To make it universally applicable to any number of values, a custom function seemed unavoidable…

Unless you have a better suggestion? :-P

Sorry, must have misread you. Even looking back,

abc | July 14, 2008 | 9:04 pm

Sorry, must have misread you. Even looking back, I thought you meant that the only problem was with negative numbers and Excel not being able to compute a geometric mean if the product is negative (actually it’s worse than this - if any value in the array is negative it spits #NUM out). In actual fact not only are negative numbers a problem but, even when using the percentage cell type, gains and losses must be expressed as 0.9 rather than 10% loss.

Thankfully, converting to decimals removes the possibility for negative numbers breaking the GEOMEAN function.

Think this array formula works though:

{=(PRODUCT((A1:AN+1)/1))^(1/COUNT(A1:AN))}

Apologies if I wasn't terribly clear... my problem basically was

Kirsten | July 14, 2008 | 9:39 pm

Apologies if I wasn’t terribly clear… my problem basically was that I want to maintain an Excel spreadsheet with stock or fund performances on a weekly and/or monthly basis. Unfortunately stocks go down as well as up so I can’t be sure that I won’t have a negative value among the results.

Since you can’t compute the geometric mean if negative numbers are involved, I needed a way to both convert percentages to 1.x or 0.x values AND subsequently compute the mean. And I refuse to keep my stock performances as 0.9 instead of -10%. Hence I had to find a way to do the conversion in the background, “remember” the values and compute the mean of those.

I see what you’re trying to do with the formula, but then I’m also refusing to believe that you can express my 30 lines of code in one single line! :-D Luckily, Excel proves me right and gives me a big fat #VALUE! when I try to use your formula on my old -10% and 30% example.

:-)

I still think I tick all your boxes :)

abc | July 14, 2008 | 9:44 pm

I still think I tick all your boxes :) You just need to remember to enter array formulae with Ctrl+Shift+Enter (and you don’t need to type in the curly brackets yourself - Excel adds them automatically).

ARGH. Conversation over. I guess there is a reason you

Kirsten | July 14, 2008 | 9:49 pm

ARGH. Conversation over. I guess there is a reason you stayed in academia and I left… :-)

Can I just repeat? ARGH.

I don't think I am who you think I am

abc | July 14, 2008 | 10:03 pm

I don’t think I am who you think I am - I’m not in academia either.

However, I think it says a lot about VBA that I did manage to condense your thirty lines of code into one :-P

Doh, and I was trying to be too clever for

abc | July 14, 2008 | 10:06 pm

Doh, and I was trying to be too clever for my own good. It’s actually possible to condense your 410 characters into 21. That’s a decrease of 95% or 0.05 :-P

=GEOMEAN((A1:AN+1)/1)

Oops... I apologise. I mistook you for a friend of

Kirsten | July 14, 2008 | 11:20 pm

Oops… I apologise. I mistook you for a friend of mine from Uni who has a habit of leaving comments with names like “ABC”. I take all my swearing back and return to my polite self to say “Thanks very much. Impressive effort”.

I just wish you would have told me all this before I spent hours to come up with the code in the post… :-(

So, before it keeps me up all night - who

Kirsten | July 14, 2008 | 11:33 pm

So, before it keeps me up all night - who are you? Since you seem to know me, or at the very least you know P… ?!

(Use the “Contact” menu entry to send me an email)

Thx! :-D

Just a passer-by who hates VB and likes a challenge

abc | July 15, 2008 | 11:47 pm

Just a passer-by who hates VB and likes a challenge :)

I tried your solution, but I got the following syntax

Robin | February 6, 2009 | 4:36 am

I tried your solution, but I got the following syntax error for this line: ’ compute product for non-empty data cells

Please advise.

yes , I tried your solution, but I got the

Ng | November 5, 2009 | 7:26 am

yes , I tried your solution, but I got the following syntax error for this line: ’ compute product for non-empty data cells

Please advise as above.

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Net Worth

39.2%

Categories

  • Budgeting (6)
  • General (11)
  • Goals (7)
  • Housing (8)
  • Insurance (1)
  • Investing (36)
    • Bonds (5)
    • Funds (13)
    • Shares (3)
  • Misc (15)
  • News (17)
  • Popular (11)
  • Read this! (20)
  • Reviews (19)
    • Books (3)
    • End of month (16)
  • Savings (16)
  • Uncategorized (1)

Library

I am reading...

Just finished...
The Art of Asset Allocation
The Essays of Warren Buffet

Blogroll

  • Dividend Money
  • Fat Pitch Financials
  • Get Rich Slowly
  • I Will Teach You To Be Rich
  • Money Watch (UK)
  • Money, Matter, and More Musings
  • MoneyPot (UK)
  • My Open Wallet
  • My Wealth Builder
  • No Credit Needed
  • Plonkee Money (UK)
  • Punny Money
  • The Digerati Life
  • The Dividend Guy Blog
  • The Finance Buff
  • The Simple Dollar
  • This is Money (UK)
  • Well-Heeled
  • Wise Bread

Financial Sites

  • Digital Look
  • Fool
  • Morningstar (UK)
  • Totally Money

Sponsors

Financial Web
Information about everything from Debt Consolidation to Credit Cards

Tags

Asia bank charges bond prices Bonds Books Budgeting calculations compound interest CPI credit risk Dilbert downloads emergency fund end of month Europe Excel Fixed Income funds Goals graduates house prices index tracker inflation interest rates Investing ISA national insurance net worth News overdraft charges parents piano portfolio quotes risk return Savings Shares Simple Dollar spreadsheets statistics stock indices student loans tax Tom Brennan Zopa
rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox