Sunday, 17 April 2011

Interview Chair: WPF Transformations

As a consultant I sometimes have to attend client interviews to determine whether I am right for a client or (and also to determine if the role is right for me). The experience from some of my interviews has instilled in me the need to fully understand a topic, over and beyond the surface. So, when learning new things or renewing existing knowledge, I like to put myself in the interviewee chair and ask increasingly difficult questions, peeling the layers off the topic.

Today, whilst preparing for the MCTS 70-511 certification exam, I put myself back in the chair.

Q: Do you know about WPF's ability to apply transformations to UIElement objects?
A: Sure, all UIElement derived classes can have WPF transformations applied to them.

Q: Good, do you know which property or properties of a UIElement can be set to apply a transformation?
A: The RenderTransform and LayoutTransform properties. Eg with a button you could set Button.RenderTransform to a ScaleTransform.*

Q: OK, so what is the difference between the LayoutTransform property and the RenderTransform property?
A: Erm, the transformation set on the LayoutTransform property is applied before WPF performs lay out on the element. The transformation set on the RenderTransform property is applied before WPF renders the element.

Q: Can you elaborate on that? What's the resulting effect? Say I have some XAML with 3 buttons placed in a StackPanel and the second button has a RotateTransform applied to it, rotating it say 45 degrees. What is the effect of applying it either as a LayoutTransform or as a RenderTransform?
A: A LayoutTransform rotates the button first before laying it out. This could cause the button layout to use up more space, eg it might use up more vertical space. Elements laid out after the button will appear under the button and will not overlap in their layout. If applied as a RenderTransform however, all elements will be laid out first before the button is rotated. As a result the button's render might overlap other elements.

Q: How many transformations can I set to the LayoutTransform or RenderTransform properties?
A: Both properties only accept a single transformation object.

Q: So, if I wanted to apply a scaling and rotation to an element, how would I do that?
A: One approach would be to group both transformations under a TransformGroup element. WPF takes care of applying the transformations in the right order. You could also calculate and apply a corresponding MatrixTransform which represents the composite of the scaling followed by the rotation.

Q: That's great. If I use a TransformGroup would it matter in which order I specify my transformations?
A: Yes, the order in which the transformations are specified is important. The effect of composite transformations which involve a translation from the center of origin will be different depending on when the translation is applied.3

* LayoutTransform is actually defined on the FrameworkElement class.

Resources
[2] Adam Nathan, WPF Unleashed, Chapter 5
[3] See Remarks section, FrameworkElement.LayoutTransform, MSDN

Tuesday, 12 April 2011

Weak References in .NET

Before garbage collection occurs the CLR creates an graph of reachable objects. Reachable objects are strongly referenced objects. Objects not referenced by any other object are eligible for garbage collection by the .NET Garbage Collector (GC).

Weak references are a memory management pattern which permit an object to exist in the dual state of being reachable and being eligible for garbage collection at the same time. The eventual active state of the object is time dependent. If the target object of a weak reference is accessed and converted to a strong reference before a garbage collection occurs the object will survive the collection. If collection occurs first the object will be collected.
The weak reference pattern requires wrapping a strong reference to an object in a WeakReference class and immediately setting the strong reference to null. When garbage collection occurs the GC determines if the only reference to the object is via the WeakReference instance. If that's the only reference the object is considered garbage and can be collected.
The object wrapped in a WeakReference instance is accessible via the Target property of the WeakReference class. The pattern requires checking whether the Target property returns a reference to an object or whether it returns null. The Target property returns null if the referenced object has already been GC'd.

Use case
One would only use weak references for objects that are reasonably cheap to construct but utilize a lot of memory.

Finalization and Resurrection
The mechanism behind garbage collection of objects that have a finalizer results in a phenomenom known as resurrection. When an finalizable object is identified as eligible for collection rather than immediately collecting the object, the object is placed in a special GC queue called the freachable queue. The freachable queue is a GC root and as such objects in this queue are not considered garbage because their Finalizer methods must be executed. The effect of placing a finalizable object identified as garbage in the freachable queue "resurrects" the object causing it to stay on the heap and evade collection.

Tracking resurrected objects
The weak reference pattern allows a programmer to indicate a preference for how weak references to resurrected objects is managed. This preference is specified via the WeakReference class' constructor. It is possible to pass a boolean parameter into the constructor instructing whether to track ressurections or not.

Long and Short
Weak references that do not track resurrected objects are known as Short Weak References.
Weak references track that track resurrected objects are known as Long Weak References. Using long weak references is a dangerous design because resurrected the internal state of a resurrected object is unpredictable. In any case a well designed finalizable object is likely to throw exceptions whenever an attempt is made to use it after it has been finalized.


Saturday, 9 April 2011

About FX Options

FX options come in two flavours

  • Traditional options ie Call/Put
  • SPOT (Single Payment Option Trading)

Traditonal options

Traditonal options give the right (but not obligation) to purchase something from the option seller on a set date and price.

Eg a EUR call/USD put option gives the right to buy EUR and sell USD at the agreed price.

There's 3 types of options:

  • American-style: can be exercised on any day until expiration
  • European-style: can only be exercised on expiration
  • Bermudan-style: can be exercised on set dates.

Traditional options are traded OTC.

SPOT options

SPOTs allow a trader to take a view on the direction of a currency pair and pays out if the view turns out to be correct on expiry.

Eg, a trader takes the view that EUR/USD will exceed 1.300 in 1 month, buys a premium and if on expiry EUR/USD indeed exceeds the stated price the trade gets a payout.

Why trade options

  • Downside is limited to the premium you paid
  • Unlimited upside
  • Provides a means of hedging
  • Requires less capital outlay than a cash trade to gain similar exposure

Why avoid options

  • SPOT options cannot be traded
  • You may be going against the odds

Pricing Options

These factors go into pricing options

  • intrinsic value: this is the value of the option of it were exercised now. This value depends on whether the option is in-the-money, at-the-money, or out-of-the-money.
  • time value: the further the option is to expiry the more risk it carries hence the costlier the premium
  • interest rates: impacts on the time value
  • volatility: higher volatility increases the chances of the option hitting the strike price. Higher volatility implies higher premiums

References

  1. http://www.investopedia.com/articles/trading/04/101304.asp

About Option Payoff

I find options are more confusing than other derivatives. You can't think of option positions as simply being long or short. An option is either an option to buy, i.e. a Call option, or an option to sell, AKA a Put option.

A position in either option type is either long or short. So we have four option positions to reason about, long calls, short calls, long puts and short puts.

The long party on an option pays a premium to the short party. If the option expires out of the money the buyer loses their premium. The long party's potential for loss is limited to the premium but their upside potential is unlimited.

The short party on the other hand receives the option premium. The premium received is the only upside available to the option seller, and their potential for loss is virtually unlimited.

The thoughts above are helpful when thinking about the payoff of an option deal. It indicates that the long party earns zero or more while the short party loses zero or more.

For the long party, payoff P = MAX(0, difference between spot price and strike price).

For the short party, payoff P = MIN(0, difference between spot price and strike price).

This result is can be expressed more meaningfully when the option type is identified.

· A long CALL option is in the money when the spot price is greater than the strike.

· A long PUT option is in the money when the strike price is greater than the spot price.

· A short CALL option is out-of-the-money when the spot price is greater than the strike. If you are the short party to a long call option, you will lose money if your counterparty is able to exercise their option. She will only exercise it under the conditions described above, hence what's in-the-money for her is out-of-the-money for you.

· A short PUT option is out-of-the-money when the strike price is the greater than the spot price. Again, your counterparty, i.e. the holder of the long put makes money when they can sell the underlying back to you for more than it is worth in the open market.

With

P = option payoff,

S = spot price

K = strike price


PCALL,LONG = MAX(0, S - K)

PPUT,LONG = MAX(0, K - S)

PCALL,SHORT = MIN(0, K - S)

PPUT,SHORT = MIN(0, S - K)

Bond Prices: Clean and Dirty

As we know, a coupon paying bond pays interest at a regular interval. This interval is typically 6 months. When a bond is priced all expected future coupon payments are factored into the price.

If a bondholder sells their bond mid way between coupon payments they would ordinarily expect to be compensated for the portion of the payment accrued since the last payment to the date the bond was sold. This makes sense. Say the bond is sold 2 months after the last coupon payment, the buyer will receive the six month coupon even though they only owned the bond for four months.

The amount accrued on the coupon in between payments is called Accrued Interest.

If the bond price includes accrued interest the price is known as the dirty price. When the price does not include any accrued interest the price is known as the clean price.

About Interest Rate Swaps

An interest rate swap (IRS) contract is a deal where two parties agree to exchange payment obligations. The common case is where one party has interest payments specified as a floating rate (eg LIBOR + 50BP) but would prefer the certainty of a fixed payment interest rate. This party could enter an IRS agreement with a counterparty whereby they would pay the counterparty a fixed rate and the counterparty would pay their floating rate obligations.

Who sells them?
IRS contracts are sold by swap dealers from investment banks or other sell side financial institutions.

Who buys them?
There are 2 categories of buyers:
- Hedgers: companies with floating rate loans might prefer to eliminate the uncertainty of unknown future rates with a known fixed rate. Why wouldn't the company just get a fixed rate loan in the first place? Well, floating rate loans are cheaper than fixed rate loans. A bank would rather offer a floating rate loan because it better suits their operating models. So most companies will find it easier and cheaper to take a floating rate loan and enter a swap deal to convert it into a fixed rate loan.
- Speculators: IRS contacts enable investors to speculate on the future direction of interest rates.

How do you price one?
Pricing and valuation of an IRS depends on where we are in the life of the swap.
For a brand new swap, the issue to determine is not so much the price but the fixed rate governing the swap. The value of a new swap is expected to be zero. This makes sense, being a swap it should not initially represent a profit or loss to either party.
For an existing swap, the price is the difference between the net present value of expected fixed rate cashflows and the net present value of expected floating rate cashflows.

The long and short of it
The long party on an IRS is the party paying the fixed rate and receiving the floating rate. This is analogous to buying money at a fixed price. The short party is the one receiving fixed and paying floating. This is analogous to selling money at a fixed price.
So, if you're paying the fixed rate, you're buying, you're long. If you're receiving the fixed rate, you're receiving a payment, you're selling, you're short.

What are the risks involved?
- Market Risk: The short side is exposed to market risk. This is simply the risk of changes to interest rates. The obligations of the fixed payer (long party) is, well, fixed! She is not exposed to market risk.
- Credit Risk: It is possible that the value of the swap swings so heavily in favour of one party that the other party defaults on their obligation. Both sides are exposed to the potential of credit risk

Who's carrying the can?
From the analysis above it seems reasonable to suggest that the short side bears additional risk. Typically, a swap dealer will factor in an additional amount when determining the fixed rate that governs the deal.

Sources
[3] Michael Durbin, All About Derivatives, Ch 4, 9, Appendix B