Tuesday, February 07, 2017

Selfhosted Google Voice

I've used Google Voice since 2010.  During that time, it's been my main telephone number.  Besides Search, it's my favorite Google product.  Google has even renewed their commitment to the product recently.  Unfortunately, Google Voice only works for US customers and my family and I are moving to Europe later this year.  GV has spoiled me and I don't want to return to the old days when I used my mobile carrier's number directly.  This is how I'm selfhosting an alternative to Google Voice.


Today I finished porting my Google Voice number to Twilio.  They offer a great platform on which to build telephony apps.  I've been very impressed with their customer support too.  It's refreshing to be able to discuss telephony problems with your provider.  That was never possible with Google Voice.

They offer phone numbers in every country we plan to live.  They provide numerous telephony services, but we're only using a few right now.


I selfhost an XMPP server for my family.  We use it all the time for messaging each other.  We run Conversations on mobile and use other XMPP clients on desktop.  It works great.  I wrote a gateway between XMPP and SMS.  You send an XMPP message and it converts it into an SMS.  When someone sends me an SMS, it converts it into an XMPP message.

This all works through Twilio's SMS API.  Since the whole system is under my control, I can add arbitrary logic for handling SMS.


To replace the voice component of Google Voice, I set up an Asterisk instance.  I use Twilio SIP trunking to connect to the telephone network.  I run Zoiper on my Android phone.  To make an outgoing call, I use the Zoiper dialer and Asterisk routes the SIP call through Twilio to the public telephone network.  When someone calls my Twilio number, Asterisk routes the call to Zoiper on my Android device.  The call quality is great.

I have no previous experience with PBX systems, but it was all surprisingly easy to configure.  Once again, since it's all in my control, I can add whatever features I want.


For now I'm using a very basic setup.  SMS accounts for 90% of my Google Voice usage and that part works really well.  Even if I never had more than this, I think I'd be content.  I have a bunch of features in mind and this setup makes it really easy to add them as I need them.

Tuesday, July 07, 2015

Diversifying a Concentrated Portfolio

In the Fall of 2010, I started a business which resulted in a larger return on investment than I anticipated.  In the middle of last year, that single asset accounted for approximately 60% of my net worth.  At that time, the Herfindahl index (a measure of concentration) of our family assets was 0.31. A well-diversified portfolio should have a Herfindahl index closer to 0.02.

We weren't comfortable having so many of our eggs in one basket.  We didn't want to sell the entire asset immediately because that would cost us a lot in taxes and slippage.  After a few weeks of research, we settled on the following plan to diversify over time.  In the last 6 months, this has brought our Herfindahl index down to 0.20 so far.

Asset Caps

The first step was to cap the maximum value of our most concentrated asset.  We used the asset's current percentage of our net worth (60%) as the initial cap.  When an asset increases in value above its cap, we sell the excess and move it into another investment.

This is similar to the time-tested strategy of portfolio rebalancing.  It makes sure that our portfolio doesn't become any more concentrated than it already is.  It also tends to sell assets when their market value is higher than normal.  If a concentrated asset drops below its cap, we do nothing.

Regular Cap Reductions

The next step is to lower the cap over time.  In the context of IPOs, there are many opinions of how quickly to sell off a single stock position.  There are even services to do it for you.  The best articles I found prefer a strategy like "sell 10% each month for 10 months."  Those articles include some fun tools for simulating how these rules would have worked in the case of various, historic IPOs.

Because our family performs these calculations in a spreadsheet, we settled on a simple linear decline where the cap drops from 60% to 1% over the next 18 months.  This makes sure that we never sell 100% of the asset.  The linear decline balances diversifying quickly against minimizing tax/slippage losses.


When the above rules result in a sale, we move the proceeds into our Wealthfront account.  This makes sure that they're quickly and easily placed into a highly diversified portfolio.  Between tax loss harvesting, $0 trades, daily rebalancing and time savings, this is much more cost effective than managing a similar portfolio myself.

We could have used Betterment, which is similar.  I chose Wealthfront because they offer direct indexing (lowers taxes and fees in the long run) and because they publish thorough white papers with gory details on how and why their systems behave the way they do.

Friday, October 26, 2012

Goodbye Mortgage

American culture could stand to be more open about personal finances.  Doing so would give us all an opportunity to learn from one another and avoid common pitfalls.  To that end, I want to describe how our family recently paid off our mortgage.

The pie chart above (click to enlarge) shows a breakdown of which factors contributed to paying off the mortgage.  According to the National Association of Home Builders, a home our size sells for $310,000 on average.  That amount represents the entire pie.

The largest slice, 71%, is attributable to savings we realized by purchasing a home in a depressed, rural housing market.  When coal mines in Hanna closed in the late 1990s, the town lost 13% of its population.  That left dozens of quality houses for sale at excellent prices.  We arrived a couple years late, so we actually paid twice as much for our house as any of our neighbors paid for theirs.

At 11%, the next largest contributor is a frugal lifestyle.  By going without some luxuries (TV, travel, prepared grocery items, low-deductible health insurance, etc.), we were able to make additional principal payments on our mortgage each month.  I'm astonished how quickly they added up.

The third largest contributor was a simple family rule: save a windfall.  If we received any unexpected income, large or small, we put it toward the house.  Before establishing this rule, such windfalls increased our standard of living. That caused financial stress as we inevitably grew accustomed to a standard of living we couldn't afford.

At 5%, Bitcoin investments made a valuable contribution.  In December 2010, during the WikiLeaks payment blockade, I become interested in Bitcoin and subsequently acquired some.  Those assets appreciated rapidly.  At one point, an opportunity arose to sell some Bitcoins and pay down our mortgage.  (Off topic: Bitcoins will change how the world thinks about money)

The smallest contribution, as expected, was the minimum, mandatory mortgage payments the bank required each month.  I personally attribute all but this last component to Providence.  I'd be glad to discuss that aspect further in the comments below.

Friday, June 22, 2012

Puns in Programming Language Design

Henri Bergson defined a pun as a text in which "two different sets of ideas are expressed, and we are confronted with only one series of words."  In natural language, puns are often used for comedy, but a skilled author can also use them for powerful literary effect.  For example, the opening lines of Richard III: "Now is the winter of our discontent / Made glorious summer by this sun of York" which has three relevant meanings.  Or John's pun as he recounts Jesus's words, "Except a man be born again, he cannot see the kingdom of God" in which "again" is a Greek word meaning both "again" and "from above."  In both cases, a pun allows the author to convey his full meaning with fewer words than otherwise possible.

Puns require both a talented author (to create the pun) and a talented reader (to understand the pun).  I admit to missing one of Shakespeare's meanings the first several times I read Richard III's opening lines.  As with all linguistic constructs, it offers benefits and costs.  Those must be weighed in each potential use case.

Puns are not unique to natural language.  They exist in optical illusions such as the Necker Cube.  Many programming languages allow sufficient, intentional ambiguity for productive puns.

Dynamic Type

Consider the following JavaScript function which adds elements of a list to an initial value.

One can invoke the function with integer, float or string values and obtain useful results. Dynamic types and an overloaded + operator provide the necessary ambiguity.  This single function definition gives three useful procedures as a result.  Most statically typed languages prohibit this pun by requiring type annotations on variables and parameters.

A talented JavaScript engine might compile the above code into completely different machine language depending on the context in which it's used, the values available at runtime and the processor architecture on which the code is running.  Just as natural language puns require a talented reader, programming language puns require a talented compiler.

Dynamic languages like Erlang and Dart embrace the ambiguity of dynamic types by adopting smart tools like dialyzer and dart_analyzer, respectively.

Parametric Polymorphism

Most functional languages let one write a generic map function like this:

The function is a pun with meaning across all list types.  The compiler infers types where necessary to ensure safety.  The absence of type annotations provides the necessary ambiguity, so dynamic languages support similar puns, although without compile-time type safety assurances.

Java and C# allow similar puns with generics.

Logic Programming

Languages like Prolog and Mercury offer puns through ambiguity in constructors and pattern matching.  For example, a single append definition creates procedures for combining two lists to make a third, removing a list prefix, removing a list suffix and generating all combinations of two lists which, when combined, produce a third:

One can use similar constructs to create punning predicates that split/join strings, parse/serialize data structures, etc.

In Mercury, goal order is unimportant which allows further puns in which the compiler reorders goals to achieve higher performance, lower memory usage or automatic parallelism.  In each case, a single textual definition provides multiple procedural meanings.

Futures and Laziness

There's a related class of puns in which meaning is the same but a programmer is intentionally ambiguous about an important implementation detail.  For example, Alice ML provides futures for the results of concurrent computations.  In Alice, a future is syntactically identical to a variable.  When one writes a function of a variable, it works on values, completed futures and incomplete futures.  This lets APIs change their internal implementation with respect to concurrency without breaking encapsulation and gives the compiler freedom to schedule concurrent threads as it sees fit.

Haskell's pervasive laziness is in a similar vein.  A variable could represent a value or a thunk which, when needed, computes a value.  A single function definition handles both.  Mailing list threads about overcoming Haskell's laziness remind us that in some cases ambiguity is a pun too far.

Psychology of Puns

Most software developers have strong aesthetic preferences about their languages and tools.  Witness the vi-emacs wars, endless debates about semicolons or brace placement and arguments about static vs dynamic typing.  In these scenarios, there is no right answer.  There are only programmers more or less comfortable with various constructs.

Programming language puns and their linguistic ambiguity are no different.  In this case, psychologists even have a name for it: ambiguity tolerance.  Some people want firm rules and an environment that resolves into clear, precise answers (One True Way).  Others thrive on uncertainty and broad choices (TMTOWTDI).  Programmers bring this psychology with them when they design and choose languages.

Fortunately, I think there's room for compromise.  By making certain language constructs optional and relying on smart compilers, programmers can either be ambiguous or precise, depending on their preference.  The language can stay with them as their preferences evolve.  There's a lot of interest in optional static typing (Perl 6, Python, Newspeak, Dart, Erlang, etc).  I'd like to see further exploration of optional annotations and compilers that can usefully resolve programming puns.

Monday, January 02, 2012

Investment Principles

A few days ago, a friend emailed me with some questions about an investment he planned to make.  During the discussion, I wrote down for the first time, some of the principles I use to guide my personal investments.  I decided to create this document as a more thorough reference for myself and a point of discussion so others can offer correction where I'm wrong.

I'll start with a list of high-level principles, follow with my rough algorithm for asset allocation and conclude by explaining how the latter relates to the former.


The following five principles guide my investment decisions.  I try to evaluate each of them before buying a security.

  1. Hard work and frugality are the foundation of prosperity
  2. I'm not as smart as I think I am
  3. Greed and impatience will ruin the best laid schemes
  4. Emotional attachment prevents sound decisions
  5. Gold is the best cash
Incidentally, these correlate fairly well with some of the seven heavenly virtues, respectively diligence, temperance, humility, charity, patience.  If I can make up principles corresponding to chastity and kindness, I'll have a best selling book on my hands, Seven Virtues of Highly Effective Investors?


When I have some money to invest, I typically follow this algorithm to decide where it should be invested.  I invest in a security corresponding to the first question to which I answer yes.
  1. Could I be working or reducing my personal expenses right now?
  2. Have you found an undervalued stock by spending hours reading annual reports, assessing asset values and calculating cash flows?
  3. Is the stock market relatively undervalued?
  4. Is the bond market relatively undervalued?
  5. Is real estate relatively undervalued?
  6. Did Rumpelstilzchen turn straw into gold?
Deriving an Algorithm from Principles

The first principle is the most important.  Fundamentally, wealth represents someone's previous hard work.  Investment is not a way to get rich.  It's a way to modestly grow wealth that has been obtained through honest labor and sacrifice.  As usual, XKCD applies: "compound interest isn't some magical force"  Thus algorithm step 1 is to try working harder and giving up luxuries.  Investing is like electricity conservation, the most effective method is to decrease consumption.

The first principle has also lead me to value investing.  There are dozens of systems for making investment decisions.  Some people swear by various day trading methods or by technical analysis.  At the end of the day, those techniques are far too easy to be successful in the long run.  If an investment claims to offer wealth without effort, it's a lie; the piper must be paid.  The best exposition I've found on value investing is the book Value Investing: From Graham to Buffett and Beyond or in Buffett's words, "other guys read Playboy. I read annual reports"  The first principle suggests that only that sort of work can bring substantial returns; as embodied in algorithm step 2.

When I get tired of the hard work required by principle one, I'm tempted to substitute vain confidence in my truly dizzying intellect.  The second principle is there to save me from myself.  No matter how much I deceive myself, I'm not smart enough to discern a single winning company based on a few contemporary trends.  The goal of algorithm steps 3, 4 and 5 is to trade substantial investment gains requiring my hard work for small gains requiring hard work from others.  Since I'm not smart enough to pick a single winning company, I restrict myself to choosing from one of three asset classes (stocks, bonds, real estate).  Index funds with very low expense ratios are a cheap way to invest in an entire asset class.  It's also hard to become emotionally attached to an index fund (principle 4).

Of course, deciding whether an asset class is undervalued also requires a fair amount of work.  Since the US Dollar is a highly inflationary measuring stick, I'm partial to long term (100+ years) ratios as a start: 10 year trailing P/E, DJIA in gold, historic bond yields, Shiller's home price index in gold, etc.

Algorithm step 6 is a fall through decision to hold cash, in the form of gold, waiting for better investments to arise.  Gold provides no yield and is only the best among a losing team of currencies.  About all it has going for it is a long history and a predictable supply; neither of which other currencies possess.

It's at this point that principle 3 becomes important.  For the last two decades, I think the general stock market has been overpriced.  For the last two years, bonds have been overpriced.  For much of the last two decades, a lot of real estate has been overpriced. It's not much fun to be holding gold, earning nothing in real terms (although 0 is better than negative!).  It's like sitting on the bench at the big game.  "Come on coach, I want to play!"  In these lulls, the only way to invest profitably is to revisit the principles of hard work, frugality and patience.

In honor of principle 2, please enlighten me in the comments below.

Tuesday, November 08, 2011

Bitcoin: Gold of the Future

Six months ago, while visiting San Francisco, I met a successful entrepreneur for dinner to discuss and trade Bitcoins.  He had recently sold his most-recent startup to one of the Big Four.  I assumed he viewed Bitcoin as a startup and wanted in on the ground floor.  It turns out, he was a goldbug whose main interest was Bitcoin as a "better gold."  It's one of the more productive analogies offering some insight into how Bitcoin might develop.

Viewing Bitcoin as digital gold is not a new idea.  Satoshi Nakamoto, who created Bitcoin, says it is partly an implementation of Nick Szabo's bit gold proposal.  Satoshi also uses gold analogies to describe the economics of Bitcoin mining and Bitcoin's adoption as a currency.  I'll draw some further parallels.

Why Gold?

Gold has been used as a currency and store of value for thousands of years, so it has history on its side. It's fungible, durable and easily recognizable.  The supply is moderately predictable and, because of relatively low industrial use, the demand is somewhat more predictable than other precious metals.  The supply grows slowly (about 2% annually).  Gold also has a high value density, being one of the most expensive commodities per weight.  When holding physical gold, there is no counter-party risk, unlike bonds and fiat currencies.

Why Not Gold?

Gold isn't perfect as a currency or store of value.  As a physical good, it must be conveyed with expensive, secure transportation.  Surprise discoveries can dramatically affect the supply.  For instance, 12 million ounces of gold entered the market during five years of the California Gold Rush (sea water contains another 15,000 tons of gold deposits).  Gold can also be destroyed in accidental fires or lost at sea.  Although industrial demand is lower than other commodities, roughly 60% of newly mined gold becomes jewelry.  Changes in jewelry demand can have substantial effects on gold prices.  Some argue that gold mining also has non-trivial environmental costs.

Why Bitcoin?

Bitcoin has nearly every strength that gold does.  Bitcoins are fungible.  They're easily recognizable (by Bitcoin software) and durable (with reasonable data backups).  The supply is almost perfectly predictable.  Bitcoin has no industrial or jewelry uses so demand is less affected by economic conditions.  It possesses almost arbitrary value density.  A single microSD card, weighing 1.5 grams, could hold millions of dollars worth of Bitcoins, if desired.  As a digital commodity, Bitcoin is also immune to counter-party risk.

Many of gold's weaknesses are Bitcoin's strengths.  As a digital good, Bitcoin can be transported securely and cheaply to nearly any location in the world instantly.  The Bitcoin network adapts rapidly to maintain predictable supply in the face of surprise mining advances.  Assuming good data backups, Bitcoins aren't destroyed in a fire and won't be "lost at sea."  Electricity used for Bitcoin mining offers a substantially lower environmental footprint than gold (a subject for another article).  Bitcoin's impact is low enough that an environmental group opposed to gold mining advocates Bitcoin as a replacement for gold.

Why Not Bitcoin (Now)?

If Bitcoin is so much better than gold, why aren't we all using it?  One of gold's major strengths is that it has stood the test of time.  Through thousands of years, it has shown itself a resilient store of value and a useful currency.  Bitcoin has less than three years under its belt.  If Bitcoin were gold, we'd still be in the early stone age carrying gold flecks in a leather pouch.  There aren't any assay offices, there aren't any minted coins, there aren't massive mining operations or liquid futures markets.  There are still doubters claiming they can one day turn lead into gold.  With real gold, those issues were settled long ago.  With Bitcoin, those issues are still to be settled and might never be settled at all.

Even if Bitcoin had a lengthy history to support its utility and resilience, the current inflation rate stands around 35% annually (similar to gold-rush-induced inflation in the 1850s).  In 2017, the inflation rate will drop below typical fiat currencies.  In 2021, it will finally drop below gold's production rate.  Unless you have a long time horizon and a high risk tolerance, right now is not the time to buy Bitcoin.

To date, the world has mined 5.3 billion troy ounces of gold.  Dividing the US M2 money supply by that number, gives a price for gold of $1,792 per oz, within a few cents of today's gold spot price.  To date, the network has mined 7.624 million Bitcoins.  A similar calculation yields a price of $1.24 million per Bitcoin. When all is said and done, there will be somewhat less than 21 million Bitcoins in existence (through carelessness, some have been lost along the way).  Even at that volume, the calculated price would be $452,000 per coin.

Like the '49ers of old, we began this discussion in San Francisco.  I'm not saying the parallels are exact, but having a few flecks in a leather pouch sounds like a reasonable idea to me.

Wednesday, October 12, 2011

Dart Hits Some Bullseyes

On Monday, Google announced a new programming language named Dart.  It aims to be faster than JavaScript and better suited to large scale software projects.  After thinking about the language for the last couple days, I think Google's engineers have started a compelling replacement for JavaScript.

Any client-side web programming language will be used by programmers from all backgrounds.  Dart's optional typing lets both static typing enthusiasts and dynamic language enthusiasts have what they want (with some minor compromises).  Throughout this article, I've linked to Dart code samples on the Dartboard so you can try for yourself.

"I Hate Static Types"

Many web developers come from a dynamic languages background and actively dislike static typing.  Many more probably have no idea what static types are and simply grew up writing JavaScript code.  Both groups of developer should be happy with Dart.  They never have to enter a type declaration and Dart is still an improvement over JavaScript.

Dart provides block scoped variables rather than the function scoped variables used in JavaScript.  Accidentally overwriting a function scoped variable is one of the most common JavaScript errors I encounter.  It's more likely to become a problem as functions evolve and grow.  With Dart, for example, this is less likely to happen.

Dart also provides a succinct function syntax rather the verbose JavaScript one.  As often as client-side programming uses callback functions, this sort of code is a pleasant change of pace.

Dart even has string interpolation.  Anyone who's programmed in Perl and JavaScript for longer than 5 minutes knows how nice this will be.

Some developers may not care, but Dart provides immutable variables with compile time errors.  As far as I can tell, JavaScript "const" just silently ignores subsequent assignments.  I've debugged quite a few JavaScript programs where code modified a variable it shouldn't have.  Declaring a final variable and receiving an error would have saved me lots of debugger time.

Dart makes some other improvements which aren't as noticeable.  For example, Dart's namespace rules should eliminate bugs from global variables.  The language spec makes several accommodations which should eventually make Dart run faster than all current JavaScript engines.  Lars Bak, who developed the super-fast V8 JavaScript engine is one of Dart's main developers.  He ought to know a thing or two about making a language that can run fast.  Dart's library system also allows for optimizations that could substantially improve website load times someday.

Even if Dart just used dynamic typing, these changes alone are enough for me to switch.

"I Love Static Types"

Many other web developers come from a static typing background and want types when developing for the browser.  GWT and Closure Compiler show how far these developers will go to have their static types.  Dart's type system gets them most of what they want.

One benefit of static typing is describing a developer's intentions.  JavaScript developers often use specially formatted comments for this purpose.  One can think of Dart type annotations as a more succinct version of the same thing.  Since Dart type annotations don't change a program's semantics, they really are just fancy comments.  As always, the comments can be wrong if your tools don't enforce otherwise.

The Dart compiler performs type checking.  If you want to catch type problems at compile time, just pay attention to the warnings (hover over line 4).  Even though they're not errors, the compiler did the hard work for you. Dart also provides a development mode for runtime type checking.  These checks are disabled in production, but it reminds me of the well-tested robustness principle, applied to programming languages.

Since type annotations are part of the language, it's likely that future tools will handle type inference.  Closure Compiler already does this for JavaScript, so the tools will probably arrive soon.  Type annotations also provide additional hints the JIT could use to further improve performance.  With JavaScript, the JIT must rely entirely on its own observations.

Be Patient

Many of Dart's critics act as though the language is finished.  Yes, the Dart to JS compiler produces horribly bloated JavaScript.  No, Dart doesn't have mixins.  Yes, Dart's VM is slow.  A quick glance at the version number (0.01) suggests we should be patient.  The Dart issue tracker and mailing list are full of good discussions about solving these problems.  The language designers are open to evolving and improving the language.

Dart isn't perfect and can't be perfect, but I think it will become a meaningful, valuable improvement over JavaScript