Wednesday, April 25, 2007

Digging DLINQ

Just gave DLINQ a quick shot and it indeed is quite impressive. The way Table and Column attributes are used for database mapping is similar to that of XML Serialization:

    [Table(Name="Products")]

    public class Product

    {

        [Column]

        public int ProductID { get; set; }

 

        [Column]

        public string ProductName { get; set; }

 

        [Column]

        public decimal UnitPrice { get; set; }

    }

Now, you can use LINQ syntax to perform strong typed database query:

public static void DLinqQuery()

{

    string ConnStr =

        @"Server=localhost;Database=Northwind;";

 

    DataContext ctx = new DataContext(ConnStr);

    Table<Product> prods = ctx.GetTable<Product>();

 

    //this is COOL!

    var list = from p in prods

               where p.UnitPrice > 30

               select p;

 

    foreach (var p in list)

    {

        Console.WriteLine("{0,5}\t{1,-32}\t{2,-6}",

            p.ProductID, p.ProductName, p.UnitPrice);

    }

}


Pretty neat, agree? I only wish this were available eailier so that I didn’t have to deal with typed dataset. That was aweful… Some further point of interests:

  • Is the underlying SQL generated by DLINQ effecient? (IQueryable and the expression tree do deserve their own blog entries).
  • Mapping between foreign key relationship to object graphs.
  • Stored Proc and Transaction support

Tuesday, April 24, 2007

How to price a CDS


As with any other derivative contract, the valuation of CDS is (was?) primarily based on replicate portfolio and no arbitrage argument. The picture below (from Merrill Lynch Credit Derivative Handbook 2003) depicts a portfolio that replicates a credit default swap:

  • A fix rate corporate bond is acquired by the investor. This exposes the investor to two major risks: interest rate risk and credit risk. The bond pays treasury rate plus a spread (Sc).

  • The bond purchase is repo financed. This is necessary because par CDS is unfunded transaction.

  • An interest rate swap transaction is then arranged. The investor pays fixed leg and receives LIBOR plus spread (Ss). This effectively eliminates the interest rate risk component.

  • A single counter-party would package the bond and swap into a single asset swap to minimize counter-party risk.

  • The investor is now holding only the credit risk of the bond issuer, which is the same for a CDS contract. Hence the "price" of this portfolio should be the same as a CDS with the same maturity (with adjustments on coupon interval, day count, yadayada...)
One thing to note is that this pricing framework is now mostly theoretical. With exponential growth in the credit market, CDS contracts have become more liquid than corporate bonds. CDS is considered a plain vanilla product and its spread quote is used to derive default probability and price other credit derivative products

Monday, April 23, 2007

How CDS Works

A basic introduction on the mechanics of CDS (credit default swaps).

Breaking Changes in Linq, Syntactic Sugar? Syntactic Heroin?

Breaking changes in Linq

Two days into the Linq jungle, I have noticed quite a few breaking changes in C# 3.0 Beta compare to the CTP release last year. The majority of sample code off the web can no longer compile under the new version. The poor documentation (well, to be fair, it's documentation for Beta...) made it a lot worse:

  • System.Query namespace is now System.Linq.
  • System.Expressions is now System.Linq.Expressions
  • Extension methods ToQueryable and ToEnumerable are now AsQueryable and AsEnumerable
  • Sequence class has been substituted with Enumerable, although this likely has no impact on code compilation.
What's "Syntactic Sugar" anyway?
All C# 3.0 new features are described as "Syntactic Sugar" by someone at some point. This leads me to think what exactly is Syntactic Sugar: Is OOP just a web of Syntactic Sugar(think Objective C, for example)? "Member Method" covers up the underlying function with an added this pointer, and the almighty "Polymorphism" is just a short hand for function pointer tables... So where do we end with this stripping process? "MOV EBP, ESP"? Oh, wait, that's just "Syntactic Sugar" for a bunch of 0s and 1s...
Syntactic Heroin
Some called operator overloading "Syntactic Heroin" because of the potential abusive use. I have the same concern for Extension Method: I see the legit use in certain situations, but it's so easy to abuse the concept by using it to quickly "hack up" a incorrectly designed class contract. It's not hard to see the code would become virtually unmaintainable when extension method is overused.

Ways to skin a LINQ query

Quite naturally, the very first step to understand LINQ is to go behind curtain and see how the magic select/where statement works. Although this has been explained many, many, many times, I still couldn't resist the temptation:

    public class Customer
    {
        public string Name { get; internal set; }
        public int Age { get; internal set; }
    }

    //...
            List<Customer> list = ...;
            var ret = from s in list
                      orderby s.Age descending
                      where s.Name == "Ming"
                      select s;
First, let's take out the syntax sugar out of the query. It's then equivalent to:
            Func<Customer, bool> p1
                = c => c.Name == "Ming";
            Func<Customer, int> p2
                = c => c.Age;
            return list.Where(p1).OrderByDescending(p2);
Still, this uses Lambda Expression. Taking that out, we have:
            var ret = list.Where<Customer>(
                new Func<Customer, bool>(
                    delegate(Customer c) {
                        return c.Name == "Ming";
                    }
            ));
            ret = ret.OrderByDescending<Customer, int>(
                new Func<Customer, int>(
                    delegate(Customer c) { return c.Age; }
            ));
And finally, without the Extension Method and var magic, the C# 2.0 way to write the query:
            IEnumerable<Customer> ret =
                System.Linq.Enumerable.Where<Customer>(
                    list,
                    new Func<Customer, bool>(
                        delegate(Customer c) {
                            return c.Name == "Ming";
                        }
            ));
            ret = System.Linq.Enumerable.
                OrderByDescending<Customer, int>(
                    ret,
                    new Func<Customer, int>(
                        delegate(Customer c) {
                            return c.Age;
                        }
            ));
It's now clear that LINQ is a compiler feature plus corresponding library support (System.Linq.Enumerable, for example). There really isn't anything new from CLR point of view.

Things to look at in C# 3.0

I'm actually a bit worried about the readability of MSIL code, which has been the primary method for me to understand what really happens behind the scenes.

With all the compiler generated members (for generics, iterators and now lambda expression, automatic property and Linq), the MSIL code generated for C# now tastes awfully like Managed C++...

By the next release, there probably is no need for an Obfuscator.

Friday, April 20, 2007

Under the Hood of Iterators and yield statement

Took a brief look at the mechanics of C# iterator and yield statement --- more in terms of the MSIL level implementation than just how to use it.

  • The compiler generates a state machine implementation of the IEnumerator interface internally.
  • Each yield return statement produces a separate state, while each yield break transits the machine to the terminate state
For example, for the function here:
        private string[] _names = { "Foo", "Bar", "Poo"};

        public IEnumerator GetEnumerator() {
            for (int i = 0; i < _names.Length; ++i) {
                yield return _names[i];
            }
        }
The compiler produces a state machine with one working state and a memeber variable that keeps track of the current index into _names. But for the following code:
        public IEnumerator GetEnumerator() {
            yield return "Foo";
            yield return "Bar";
            yield return "Poo";
        }
The compiler would generate a state machine with 3 working states. It seems Reflector chokes on compiler produced iterator code. I don't expect it to reverse engineer the state machine into yield statements, but the C# code it produces is totally out of whack. I end up had to read the MSIL to understand what's going on.

The Orcas is here

  • Visual Studio "Orcas" (Beta) is now available for download (need MSDN Subscription).
  • Or you can download "Orcas" express editions here (Community Technology Preview).

Thursday, April 19, 2007

CME Credit Derivative Future Contracts

CME is tapping into the $30 trillion credit market with its single name and index credit default swap future contracts. Eurex is also set to launch future contract on Itraxx CDS indices. This is hardly surprising given the hyper growth in OTC credit derivative market in the last couple years (also in the news today, the overall size of credit derivative market has been growing at 100% three years in a row). It would be interesting to see the impact of exchange involvements on the overall credit market (I.E. on counter-party credit risk, liquidity, etc).

Wednesday, April 18, 2007

Visual Studio Tools for Office Second Edition

Technically speaking, VSTO 2005 SE is not really the second edition of VSTO. While VSTO 2005 is an independent version of Visual Studio 2005, VSTO SE is more of an add-on to different editions of Visual Studio. For example, VSTO 2005 SE can be installed on top of VSTO 2005. In addition, VSTO SE doesn't really cover all VSTO features. Noticeably, document level customization and action pane are not available in SE. On the other hand, it does add support for Custom Task Panes and Ribbons. And here is an decent overview of the mechanics of VSTO (Outlook is used as an example, but I imagine it should be almost identical for other office products). To my surprise, VSTO still works its way through the good (bad? evil?) old COM interfaces (IDTExtensibility2, etc), with AddInLoader.DLL wraps around managed code. It seems .NET is not treated as a first class citizen even in Office 2007 (to be fair, VSTO does add some nice touches of the managed world, such as added security with separate AppDomain).