EDT and non-EDT delegating to each other

This is a very common swing pattern, so better recognize it. Both techniques are often necessary rather than nice-to-have. Every swing developer needs to master them.

X) a regular thread often passes Runnable tasks to EDT via the event queue. See invokeAndWait() etc.

Y) EDT often passes slow tasks to helper threads so as to keep the GUI responsive. Tasks running on EDT should be quick. For road hogs, EDT can use a thread pool, or SwingWorker thread.

Q: data sharing? Race conditions?
A: I feel most swing apps are ok. The jcomponent objects are effectively singletons, accessible from multiple threads, but usually updated on EDT only.

an event pseudo-field = wrapper over a delegate field

Summary — an event pseudo field is a bunch [1] of callbacks registered (with the host object) to be notified/invoked.

Each callback is a 2-pointer thingy — an enhanced functor known as a delegate instance. First pointer references the “receiver object”.

[1] an ordered list

Suppose an instance of class Thermometer has a bunch of callback listener Objects each registered with this thermometer. When a new temperature is produced, all these listeners are invoked when runtime executes MyEvent(…args). That’s the requirement. C# does it with event pseudo-fields.

Under the hood, this thermometer has a delegate Object enclosing an invocation list. Each node on the list holds 2 pointers to a) the (non-static[1]) method and also to b) the object to call on. Good solution, so what’s the “event” field?

Answer — the event pseudo-field is a wrapper over the hidden delegate field. Like a property pseudo-field, an event defines a pair of add/remove methods. In the case of add(), “myEvent += d1” simply calls “_hiddenDlgField += d1″

http://www.yoda.arachsys.com/csharp/events.html explains why exposing the delegate field is a bad idea.

[1] This is the most common usage of delegate. Alternatively you can also register a static method as a callback.

VaR is!a maximum loss — illustrating Condition VaR

Q: Everyone should know the theoretical maximum loss is 100% [1]. That’s theoretical max. How about realistically? Can we say Value-at-risk is a realistic estimate of “maximum loss” in your portfolio, from a large number of extensive simulations and analysis? The original creators of VaR seems to say no. See https://frontoffice.riskmetrics.com/wiki/index.php/VaR_vs._Expected_shortfal.

Compared to ExpectedShortfall aka ConditionalVaR,  the original VaR measures the most optimistic level of loss i.e. the smallest loss within the fat tail.  Therefore, the magnitude of those big losses are not considered.

“Expected” is used in the statistical sense, like “average”, or average-width [2] of normal bell curve.

Q: Does ES consider the magnitude of the loss in the worst, worst cases?
A: yes. Superior to VaR. Measures severity of fat tail losses.

For a given portfolio and a given period, the 5% expected shortfall is always worse (larger) than 5% VaR. This is Obvious on any probability density distribution curve, not just the Normal distribution bell curve. If PDF is hard to comprehend, try histogram.

— Example —
“My 10-day 5% Expected Shortfall = $5m” means in the worst 5% caseSSS, my AVERAGE-loss is that amount.
In contrast, “My 10-day 5% VaR == $4m” means in the worst 5% caseSSS, my MINIMUM-loss is that amount. Most optimistic estimate.

VaR makes you feel confident “95% of the time, our loss is below $4m” but remember, this level of loss is the SMALLEST-loss in the fat tail. How badly you lose if you are 5% unlucky and one of those 5% cases happen, you can’t tell from VaR.

[1] In leveraged trading, you could lose more than 100% of the fund you bring in to the trading account, because the dealer/broker actually lends you money. If you lose all of the $10,000 you brought in and lose $2000 more, they could go to your house and ask you to compensate them for that loss.

[2] actually “average distance from the vertical-axis”. Vertical-axis being the mean PnL = 0.

wit – increase chance of getting into US job market

For a developer from overseas, another skill valued by US interviewers is wit.

A lot of US interviewers really appreciate it. Many believe it shows an intelligent communicator, who gets things fast. Humor and wit doesn’t always cross borders. Takes a long time to learn the American way, though many US interviewers aren’t American.

If you delight your interviewer with just a little bit of ingenious humor and wit, it will be memorable and outstanding. Most of the time candidate’s wit isn’t ingenious, but some effort is worthwhile.

In US everyday culture, humor is prized more than in other cultures. There is a less hierarchical, more free-flowing, expressive, almost “selling” style.

You mentioned some colleague spending a lot of his personal time getting familiar with fantasy football? Same kind of thing.

Yield as relative value comparator

Yield is the most versatile, convenient (therefore most popular and practical) soft market data for relative value comparison. Yield lets you

– compare across currencies
– compare across time horizons (yield curve)
– compare across credit qualities (credit spread)
– compare across disparate coupon frequencies including zero-coupons
– compare across disparate call provisions
– compare government vs private issuers
– compare across vastly different industries
– compare across big (listed) vs small companies and even individual borrowers
– compare across eras like 70’s vs 90’s
– compare with interest rates. In fact, lenders use credit spread and prevailing IR to derive a lending rate on each loan.

Why is yield such a good comparator? Yield is a soft-market-data item derived using many inputs. Yield, in one number, captures the combined effect (on what? Of course valuation) of many factors such as

* different credit qualities
* different probabilities of default
* different embedded options
* different coupon rates
* comparable (but different) maturities

Without capturing all of these differences, it’s unwise to even attempt to compare 2 bonds. You get an obviously biased comparison; or you get an incomplete comparison. No info is better than misleading info.

Yield is so widely adopted that major data sources directly output yield numbers, making yield a “raw” market datum rather than a “soft” market datum.

question on our Reo pricing engine — effective duration

Hi Jerry,

I recently worked on eq derivative pricing. I realized traders need to know their sensitivities to a lot of variables. That made me start thinking about “your” pricing engine — If a bond trader has 100 open positions, she also need to know her aggregate sensitivity to interest rate (more precisely the yield curve).

To address this sensitivity, I know Reo displays dv01 at position level (and rolls up to account/sector levels), but how about effective duration?

If we do display duration on a real time basis, then is it calculated using dv01 or is there option-adjusted-spread factored in for those callable bond positions?


risk system can be front office (KK


One of my systems was a real time risk monitor. Traders use this same system to book trades, price potential trades, make market, monitor market data, conduct scenario analysis. If this is not front office app, then I don’t know what is.

If I don’t say this app also handles real time risk, then no one will question it is front office. In fact, trading floor guys told me traders use this app more than any other app.

However, at the heart of this application is real time risk engine. All those “front office” features are built on top of the pricing module in this risk engine.

In another bank I worked, I know a Fixed Income derivative trading app that’s responsible for position management, deal pricing, live market data, quote pricing, contract life-cycle event processing — all front office functionality, but at the heart, this is a risk system. The team is known as “Risk team”. In fact, there was no other front office app for these derivatives. This was the only thing traders had. If you call it middle office, then there’s nothing front office.

In many derivative systems (including fx options and fx swaps presumably), pricing engine takes center stage in both front and middle office. Derivative traders’ first and last job is (i believe) monitoring her open positions/deals and trade according to existing exposures and sensitivities. That’s the defining feature of derivative trading.

Experts often say derivatives were created as risk management tools. They reduce risk and introduce risk, too. They are creatures of risk.

H-Vol vs I-Vol – options #%%jargon

Volatility measures the dispersion / divergence / scatter / spread-out among snapshots of a fluctuating price, over a period. Most intuitive and simplest visualization of the spread-out is a histogram. Whenever I have problem understanding volatility, i go back to histogram.

– Frequency of observations can be high or low, usually daily.
– The fluctuating price can be a stock, Interest Rate, Forex, Index, ETF…
– But the period’s start/end date must be specified otherwise volatility is meaningless.

σh‘s start/end dates are always in the past. σi‘s start date is always today, and end date is typically 30 days later. In other words, σh is backward looking; σi is forward looking. Therefore only σi (not σh) can affect option pricing

σh‘s sample values are real snapshots. σi‘s “sample values” are unknowable. We predict that if we take snapshots over the next 30 days, stdev will be this σi value.

what can an ibank SELL besides financial products

As an investment bank, Clients most buy/sell financial instruments with us, but there are many value-add “services” we can sell to clients. Some of these services are packaged into a “value meal”.

– research information — selling “information”
* recommendations
– soft market data
– historical data
– indicative/evaluation prices for illiquid instruments
– quant lib? I doubt ibanks sell these, but it's possible in theory.

– trading strategy, algorithms
– trading signals

– low latency “connectivity” to trading venues
– smart order router

– security lending
– custody services
– book keeping service?
– settlement and clearing services

ref-counting string – implementation notes

([[ nitty gritty ]] P202 has simple sample code)

An option exchange interviewer asked me to outline a ref-counting string class “str”.

char* cstr; //field will be null-terminated and allocated on heap.
int counter; // field will be an int allocated on heap.

Now forget about ctor and big 3, and focus on simple, common client operations AFTER instantiation. Now I realize we need to recall how a string variable is USED.

  int length() const;
  char* c_str() const; // STL string offers this conversion method, so do we.
  char* substr(….) const;
  //operator << to print the string
  str operator+() const; // produce a new str object by concatenation. Probably follow the effC++ advice to avoid return-by-reference??

Now the big questions

Q: does copy ctor allocate the cstr or the counter, or share them with sister instances?
%%A: share

Q: does conversion ctor from a C string allocate this->cstr and this->count?
%%A: allocate

Q: how do we create another str variable sharing an existing cstr object?
%%A: copy ctor or assignment
A: cvctor