Category Archives: mathematica

Jesus loves gay marriage

There was an earthquake near Washington DC last week, and a hurricane tore through New York City this morning, for the first time in many years. Naturally, some took this as a sign of God’s wrath. The same sort of thing was said about Hurricane Katrina. Republican presidential candidate Rick Perry regularly treats changes in weather as indicia of Jesus’s favor.

For what it’s worth, the numbers suggest that if Jesus is in fact using hurricanes to guide our behavior, he’s trying to guide us to approve gay marriage

and to vote for democrats.

[boring details: Irene deaths from http://www.ksro.com/news/article.aspx?id=3182755, population data from http://quickfacts.census.gov/qfd/index.html, % voting from McCain from http://en.wikipedia.org/wiki/United_States_presidential_election_in_Connecticut,_2008 and equivalent pages for the other states with Irene deaths, and gay marriage stats from http://en.wikipedia.org/wiki/Same-sex_marriage_law_in_the_United_States_by_state using a dummy variable of 1 if gay marriage is allowed, 0 if it isn’t, and 0.5 if some kind of intermediate right is granted.]

Futures conversion factors in Mathematica

Sovereign debt futures in the U.S. and elsewhere are designed to accept multiple different bonds for delivery. The exchange specifies a delivery factor algorithm to normalize the prices of these bonds (or notes) to make them roughly of equal value upon delivery. Since they’re not precisely of equal value, traders can make money trading around the cheapest to deliver bond.

The conversion factor in the U.S. is designed to convert the yield on any bond or note to 6%. Considering the semi-annual or monthly coupon payments on bonds and notes, the formula to do this looks as follows.

Options[conversionfactor] = {type -> "bond"};
(* versus "10yr note", "5yr note", or "2yr note" *)

conversionfactor[coupon_Real, wholeYearsToMaturity_Integer,
stubMonthsToMatury_Integer, OptionsPattern[]] :=
Module[{v, a, b, c, d},
v = If[stubMonthsToMatury < 7, stubMonthsToMatury, If[OptionValue[type] == "bond" || OptionValue[type] == "10yr note", 3, stubMonthsToMatury - 6]](* for 10 year, other options possible for other instruments *); a = 1/1.03^(v/6); b = coupon/2*(6 - v)/6; c = If[stubMonthsToMatury < 7, 1/1.03^(2*wholeYearsToMaturity), 1/ 1.03^(2*wholeYearsToMaturity + 1)]; d = coupon/.06*(1 - c); a*(coupon/2 + c + d) - b]

wholeYearsToMaturity represents the number of whole years from the first day of the delivery month to the maturity (or call) date of the bond or note.

stubMonthsToMatury represents the number of whole months between wholeYearsToMaturity and the maturity (or call) date rounded down to the nearest quarter for Treasury Bonds and 10 Year Note futures, or to the nearest month for 5-year and 2-year note futures.

For a 2 year note with 1 year, 10 months remaining and a coupon of .015,

In[]:= conversionfactor[.015, 1, 10, type -> "2yr note"]
Out[]= 0.922939

For a 5 year note with 4 years, 10 months remaining and a coupon of .0275

In[]:= conversionfactor[.0275, 4, 10, type -> "5yr note"]
Out[]= 0.86533

Date functions in Mathematica

The date functions in Mathematica are in some regards excellent — you can use almost any common date format and the program will decipher it, and it computes date additions and date differences to high precision, and the date graphing functions work well. However these features come at a cost, the date functions in Mathematica are quite slow.

When writing functions that involve dates, the most important speed optimization is typically to move all date functions outside the inner loops, even if this means doing elaborate computations of all possible date combinations in advance, so that the inner loops can do table lookups for needed results. I have even created my own date functions that, though interpreted rather than compiled as Mathematica’s built in functions are, run ten times faster. (One difference being that my function is less flexible in the format of the inputs it accepts, and can proceed directly with date addition or subtraction, whereas Mathematica’s built-in function must spend epic amounts of time trying to figure out what precisely is meant by, for example “11/5/1980”. However even when you convert all Mathematica dates to AbsoluteTime[] format, it’s still slow.)

I ran some benchmarks tonight, comparing Mathematica to Visual Basic for Applications. This seems a fair comparison, as both are interpreted lanaguages. The inner loop in Mathematica looks like


{DateDifference["11/15/1997", "12/1/1998", "Day"],
DatePlus["11/15/1997", {36, "Day"}],
AbsoluteTime["December 30, 1997"]}

While the equivalent code in VBA is

diff = DateDiff("d", #11/15/97#, #12/1/98#)
sum = DateAdd("d", 36, #11/15/97#)
intTime = DateValue("December 30 1997")

Mathematica 8.01 runs that triad of lines 121 times/second, while VBA completes it about 10,000 times/second. VBA is about 82 times as fast.

An amusing quine in Mathematica

I had the idea for this Quine even before writing the longer, more traditional quine I posted yesterday. That one actually took hours to craft; this one practically wrote itself. It is based on the TextRecognize[] command that was introduced in Mathematica 8. Essentially, I wrote a line of code that prints a picture, then runs OCR on that picture and prints the result. The seed picture is an image of the program’s own source code.

Mathematica reduces the size of the picture so it fits neatly on a line of text, which makes it hard for a human to read. As they appear in the notebook, the Quine and its output look like
image quine

If we zoom in on the guinePNG image, we see
quinePic

Ta-da!

The only time consuming part of the process was selecting a font that led to an accurate OCR result. The TextRecognize command seems to do best with dictionary words, and does a comparatively lousy job of recognizing Mathematica code, which is full of odd terms and punctuation. I changed the name of the variable from “quinePNG” to “guinePNG” because TextRecognize[] was identifying the “q” as a “g” anyway.

Quine in Mathematica

A “quine” is a curious object in computer science of far-reaching implications. It is a program that generates itself as output. This is more complex than it sounds, as if you have your program source, to print that source requires that the program have something like Print[program source], but then to capture that leading print command, you need to amend your code to something like Print[“Print[”,program source,“]”], and to capture the new complexity you need another level of nesting, ad infinitum. Some people, discovering this problem upon their initial efforts to write a quine, conclude the problem is hopeless.

However, it is not at all hopeless. These can be created in every Turing-complete computer language, and in fact can be created an infinite number of ways in each language. I learned about quines recently from their Wikipedia page, and from a very nice discussion at the web page of David Madore. Reading Madore’s page, I immediately realized an extremely slick implementation that would be possible in Mathematica 8, but before trying to implement that I thought I would try a more general approach first.

Three different techniques seemed promising. The first involved putting a program that uses ToExpression[] to render a string into a string, and then run ToExpression on it. My efforts in this direction all hit infinite recursion loops.

The second direction involved using StringReplace to print a string that contained its own StringReplace command. The substring being replaced seemed to get Held, however, and I couldn’t get it to behave as desire.

The third way uses the Print command, thusly:


quine[x_String] := Print[x, ";", FromCharacterCode[10] , "quine[", InputForm[x], "]"];
quine["quine[x_String]:=Print[x,\";\",FromCharacterCode[10],\"\quine[\",InputForm[x]],\"]\""]

The output is precisely as we want —
quine

I think this meets the definition of Quine. I’ll set to the elegant Mathematica 8 only version shortly.