%%#1sustainable value-add(#1reliable career path):hands-on dev

see also letter to German (post)

Hands-on development, analysis, design, debugging, maintenance, prod support … I get things done. My job interview performance is even better than project performance.

I can do this till age 65, even though my memory will decline.

This is a typical white-collar job, knowledge intensive, and pays “reasonably well” in SG or China but “very well” in US and Europe.

All other roles I am less confident about, including management, Business Analyst, quant research, DBA, data analytics.

Given this #1 thingy, my future belongs to the US.

In SG, at age 50 if I’m given a programming job along with some 20-somethings, I’m likely to be more competent than them, but as Miao and Xiao An pointed out hiring managers may not give me a chance. The Singapore government won’t help me find a high-paying programming job.

##[15]where in c++am I growing: GTD^IV

Short and sharp answers preferred
–Q: where and how fast am I growing in c++ IV?
A: EPI300/Google style coding test, esp with STL, shared_ptr etc
A: the HFT interviews revealed my weaknesses in some QQ areas.
A: ##10 basic programm`constructs for timed c++ cod`IV  — focus, direction for IV preperation
–Q: where and how fast am I growing in c++ zbs
A: debugging using print or gdb. No longer afraid of funny errors
A: experience reading STL errors
A: [[safe c++]]
A: [[21st century C]]
A: Learned to question what low level details are more than academic
A: Learned the practical value of c++ integration with excel, python etc
A: Learned a bit more about instrumentation including debuggers, esp. on Windows
A: Learned a bit more about boost smart pointers. There are many of them, because there exists different needs.
A: Learned a bit more about IDE, make, cmake and friends

dummy’s PCP intro: replicating portf@expiry→pre-expiry #4IV

To use PCP in interview problem solving, we need to remember this important rule.

If you don’t want to analyze terminal values, and instead decide to analyze pre-expiry valuations, you may have difficulty.

The right way to derive and internalize PCP is to start with terminal payoff analysis. Identify the replicating portfolio pair, and apply the basic principle that

“If 2 portfolios have equal values at expiry, then any time before expiry, they must have equal value, otherwise arbitrage“.

Even though this is the simplest intro to a simple option pricing theory, it is not so straightforward!

earning/paying the "roll" in FX swap

Tony gave an example of sell/buy NZDUSD.    NZD is high yielder and kind of inflationary. Therefore, far rate is Lower. We sell high buy low, thereby Earning the swap points.

Buy/Sell USDJPY is another example. USD is high yield, and inflationary, so far rate is Lower. We buy high, sell low, therefore paying the swap points.

KPI operational skills:under-valued #eg IDE…

I know Barclays (or any big bank) pays a VP salary to experienced developers. Would they pay the same for someone very familiar with IDE, CVS, automated build/release/test, script automation, back-up … lots of tools?

No because the latter skill is a commodity “operational” skill compared to the “creational” skill of a product developer. In a way, developers are a revenue center. Developers need analysis, design, deep experience, domain knowledge…

I feel interviewers ask too much about algorithm/data structure, problem solving, financial domain knowledge, and not enough about those operational skills. I guess in 50% of dev team there’s no one specializing in those infrastructure stuff, so every developer must pick up this skill, which can really impact productivity and trouble-shooting.

I think instrumentation skills (see other posts) are closely related to this.

paradox – FX homework#thanks to Brett Zhang

label – math intuitive

 

Q7) An investor is long a USD put / JPY call struck at 110.00 with a notional of USD 100 million. The current spot rate is 95.00. The investor decides to sell the option to a dealer, a US-based bank, on day before maturity. What is the FX delta hedge the dealer must put on against this option?

a) Buy USD 100 million

b) Buy USD 116 million

c) Buy USD 105 million

d) Buy USD 110 million

 

Analysis: The dealer has the USD-put JPY-call. Suppose the dealer has USD 100M. Let’s see if a 1 pip change will give the (desired) $0 effect.

 

at 95.00

at 95.01, after the 1 pip change

pnl

value (in yen) of the option is same as value of a cash position

(110-95)x 100M = ¥1,500M

(110-95.01) x 100M = ¥1,499M

loss of ¥1M

value (in yen) of the USD cash

95 x 100M = ¥9,500M

95.01 x 100M = ¥9,501M

gain of ¥1M

value of Portfolio

 

 

0

Therefore Answer a) seems to work well.

 

Next, look at it another way. The dealer has the USD-put JPY-call struck at JPYUSD=0.0090909. Suppose the dealer is short 11,000M yen (same as long USD 115.789M). Let’s see if a 1 pip change will give the (desired) $0 effect.

 

at 95.00 i.e. JPYUSD=0.010526

at 95.01 i.e. JPYUSD=0.0105252, after the 1 pip change

pnl

value (in USD) of the option is

same as value of a cash position

(0.010526-0.009090)*11000M =

$15.78947M (or ¥1500M, same as table above)

(0.0105252-0.009090)*11000M=

$15.77729M (or ¥1498.842M)

loss of $0.012187M

 

value (in USD) of the short

11,000M JPY position

-0.010526 * 11000M= -$115.789M

-0.0105252*11000M = -$115.777M

 

gain of

$0.012187M (or ¥1.1578M)

value of Portfolio

 

 

0

Therefore Answer b) seems to work well.

 

My explanation of the paradox – the deep ITM option on the last day acts like a cash position, but the position size differs depending on your perspective. To make things obvious, suppose the strike is set at 700 (rather than 110).

1) The USD-based dealer sees a (gigantic) ¥70,000M cash position;

2) the JPY-based dealer sees a $100M cash position, but each “super” dollar here is worth not 95 yen, but 700 yen!

 

Therefore, for deep ITM positions like this, only ONE of the perspectives makes sense – I would pick the bigger notional, since the lower notional needs to “upsized” due to the depth of ITM.

 

From: Brett Zhang

Sent: Monday, April 27, 2015 10:54 AM
To: Bin TAN (Victor)
Subject: Re: delta hedging – Hw4 Q7

 

You need to understand which currency you need to hold to hedge..

 

First note that the option is so deeply in the money it is essentially a forward contract, meaning its delta is very close to -1 (with a minus sign since the option is a put). It may have been tempting to answer a), but USD 100 million would be a proper hedge from a JPY-based viewpoint, not the USD-based viewpoint. (Remember that option and forward payoffs are not linear when seen from the foreign currency viewpoint.)

 

To understand the USD-based viewpoint we could express the option in terms of JPYUSD rates. The option is a JPY call USD put with JPY notional of JPY 11,000 million. As observed before it is deeply in the money, so delta is close to 1 (positive now since the option is a call). The appropriate delta hedge would be selling JPY 11,000 million. Using the spot rate, this would be buying USD 11,000/95 million = USD 116 million. 

 

On Sat, Apr 25, 2015 at 2:21 AM, Bin TAN (Victor) wrote:

Hi Brett,


Delta hedging means holding a smaller quantity of the underlier, smaller than the notional amount, never higher than the notional.

This question has 4 answers all bigger than notional?!

Victor

 

fwd-starting fx swap points

Q: If 9M outright fwd point is 15.2 pips, and 3M is 5 pips, what would be the fwd-starting swap point?

A (not sure now): The swap point would be 15.2 – 5 = 10.2 pips.

The fwd point for a 3Mo (our near date) is F – S = S (1 + R * 90/360)/(1 + r * 90/360) – S, which already considers the 3Mo length.

This formula shows the
* near date fwd point number is linear with (R – r).
* far date fwd point number is linear with (R – r).

However, the linear factors in these 2 cases are Different so it’s wrong (??) to subtract like 12 – 5 basis points. Swap point reflects not only the IR differential, but also the “distance” and the spot level.

The swap points are smaller when the distance is short.

Suppose you as market taker have an existing 3M fwd position and need to roll it forward. You effectively need to close the position for the original maturity and redo it at 9M. That’s 2 transactions with 2 dealers — unwise. Instead, You should go to one dealer to get a fwd-starting swap quote in bid/ask, without revealing your direction. The dealer would charge bid/ask only on the far leg, not twice on near leg and far leg.
Specifically, If there’s a bid/ask on the 3M fwd point (5 pips for eg), that doesn’t increase the swap point bid/ask spread, which would be the same bid/ask spread as the far leg fwd points.

x-ccy basis swap – FX homework3 revelations

For x-ccy fixed/fixed IRS, There are 2 levels of learning
11) the basic cash flows; how this differs from IRS and FX swap …This proves to be more confusing than expected, and harder to get right. Need full-blown examples like course handout from Trac consultant. It’s frustrating to re-learn this over and over. May need to work out an example or self-quiz.
22) the underlying link to x-ccy basis swap
———–
A1b: Either issue EUR fixed bond or USD fixed then somehow swap to EUR
A1: fixed USD
A4: euro. Yes. They can simply convert the USD fund raised, in a detachable spot transaction. This is fully detachable so not part of the currency swap at all.
A9: 0 point. Rate is the trade date spot
A2 no

11) Self-quiz on the Trac illustration, to go thin->thick->thin and develop intuition.
Q1: before the deal, is Microsoft already an issuer of fixed or floating bond? What currency?
Q1b: Before issuing any debt whatsoever, what are Microsoft’s funding choices?
Q2: Is there any principal exchanged on near date (i.e. shortly after trade date)?
Q3: Microsoft is immune to FX movement or USD rate movement or EUR rate movement? What is Microsoft betting on?
Q4: Microsoft needs funding in what currency? Are they getting that from the deal?
Q9 (confusing): how is this diff from FX swap? How is swap point calculated?

My mistake in this homework was forgetting that the far-date FX rate used to exchange the principal amount is the rate pre-determined on trade date, written into the contract, and not subject to FX movement up thereafter.

22) I now think the x-ccy basis swap spread is important to any x-ccy IRS aka “currency swap”, because a x-ccy basis swap is an implicit part and parcel of it….

http://quantfather.com/messageview.cfm?catid=8&threadid=75575 points that usd/aud [1] basis swap of 15 bp is interpreted as

“usd libor flat -vs- aud default floating rate + 15 bp, with tenor basis spread adjusted [2].”

[1] or aud/usd…. It doesn’t matter.
[2] in aud case, the default swap coupon tenor is same as USD and needs no adjustment

I guess the spread is positive because aud is a high yielder? Not sure

–The coca cola bond in http://www.reuters.com/article/2015/02/27/coca-cola-bonds-idUSL5N0W127E20150227
US issuers (needing usd eventually) of eur floating bonds [3] would use x-ccy basis swap to convert the euribor liability to a “usd libor + 33” liability, so the negative and growing spread (-33 now) hurts.

Warning — it’s incorrect to think “ok for this quarter my euribor liability is 2% for this quarter, so 2% – 33 bps = 1.67% and I swap it to a usd libor liability, so the bigger that negative spread, the lower my usd libor liability — great!” Wrong. The meaning of -33 is

“paying euribor floating rate (2% this quarter), I can find market makers to help me convert it into paying a usd libor+33”
“paying 2% – 33 bps on a euribor floating bond, I can convert it into paying a usd libor + 0 floating bond”

[3] fixed bond can be swapped to floating
http://www.global-derivatives.com/forum/index.php?topic=444.0;wap2 explains
There is more demand for funding in one currency and more supply in another currency. For instance many Japanese banks have funding sources in JPY but have committments in USD. They therefore will swap their JPY (inflow) to USD (inflow) to cover their USD commitments. The basis swap spread reflects this supply and demand situation.

Assuming a tiny bid/ask spread, I believe a Japanese bank is equally willing to receive
– a stream of usd libor or
– a stream of jpy libor – 10 bps

By the no-arbitrage pricing principle, two floating rates should trade at par and the basis spread should be zero (Tony also covered this point in the 3rd lecture), but there’s more demand for usd libor inflow.

Similarly, after GFC, European banks need usd more than US banks need euro. see http://www.business.uwa.edu.au/__data/assets/pdf_file/0008/2198339/Chang-Yang-UTS.pdf. A typical bank would be indifferent to receiving
– a stream of usd libor or
– a stream of euribor – 34 bp

https://doc.research-and-analytics.csfb.com/docView?language=ENG&format=PDF&source_id=csplusresearchcp&document_id=1014795411&serialid=mW557HA4UbeT5Mrww553YSwfqEwZsxUA4zqNSkp5JUg%3D explains that

the basis swap markets saw increased demand to receive USD funds in exchange for EUR. This excess demand drove the EURUSD basis swap spreads down to highly negative levels as counterparties were willing to receive lower interest payments in return for US dollar funds

aging memory for a developer … is an attitude

I noticed my colleagues (typically a few years younger) are faster at code reading. I seem to remember less and forget more than them. Also I’m possibly slower at solving problems in my projects…

Many more small tidbits of anecdotal evidence all seem to point to the same explanation — an aging developer.

My dad had really good memory until age … 70? His work requires him to read lots of research papers and books, and remember lots of details. After he turned 70 (or 75?) he told me a few times that his memory had become less sharp.

There are many types of memory capabilities like forgetfulness, reading and learning, short term vs long term memory .. The important memory task for a developer includes things like
* solution we tried a while ago —- for a recurring problem at work. An effective or ineffective solution
* handy tricks and how-to’s —- in a language, on an IDE, on the command line, in an OS etc. A bit similar to spelling for Chinese – I used to write and remember them well.
* important details in my own code —- I often forget them, including code I debugged or struggled with
* where to find some useful info —- If you found it once only a while back, you may not remember it and may not bother to write down the steps.
* who said what during a meeting between departments —- The numerous “less important” details are often skipped in the meeting minutes, if any.
* explanation given by some colleague verbally —- I often forget, so I often ask again — annoying:( Most of the verbal explanations I get are not 100% fully understood, not as clearly explained in an email.
* verbal answers I give to other people — I often forget what I said — embarrassing:(
* jargon terms used at work —- including the large number of standard procedures associated with the jargon
* all the details needed for a tech interview.
* past IV questions and answers

(I’m also becoming more forgetful at home — a different story.)

I won’t try and give a well-defined list of these memory tasks. What I really want to say is, active learning delays aging. Challenging ourselves to learn new things, beyond our comfort zone (familiar territories like Java and SQL) stretches our “memory muscle” and keep it in better condition. Memory is like a muscle – the more we use it the stronger it gets.

We first need to believe in our memory capacity, while recognizing all the negative evidence.

mkt-value – basic concept (confusion) cleared

PnL is a cleaner concept than MV. PnL can be -ve/+ve/$0. For MV,

1) In the simple case of bonds and stocks (think of owning a house), if you buy an asset, the MV is always, always positive
1b) a long option position has strictly positive MV
1c) a unit of any fund has strictly positive MV

In these cases, there’s an upfront full payment to the seller, upon execution.

2) MV (position without upfront payment) can have -ve/+ve/$0 MV. (In practice, such a deal is always initiated with MV=$0.)
* futures
* FRA
* fwd contract on stocks
* FX fwd
* Swaps never require upfront payment

5) FX is tricky
5a) at a money changer, physically buying an asset ccy, using our domestic currency (SGD), is similar to 1). Full payment upfront, so the asset we bought has MV > 0 at all times.
5b) trading a cross (not involving our own ccy SGD) — no upfront. MV can be -ve.

9) Online trading is more tricky. Let’s ban leverage:) Buying an asset ccy using our own currency (ccy2) should be very similar to 5a), but actually the amount of ccy2 doesn’t leave my account. Instead there’s simply a CCY1/CCY2 position recorded in my account. Fundamentally unlike physical trading. In this context, MV of any position can be -ve.

[[21st century c]] – unusually practical update on C

a sub-chapter on string processing in the new world
a sub-chapter on robust Macros in the new world
a sub-chapter on function to report errors in the new world
a full chapter on pointer in the new world
a full chapter on C api to be consumed by other languages like python
a full chapter on struct syntax improvement to support returning multiple values + status code
a sub-chapter on pthreads
a sub-chapter on [[numerical recipes in C]] and the implementation – the GNU scientific library
a sub-chapter on SQLite
briefly on valgrind
function returning 2 values + status code
many innovative macro tricks
innovative and concise explanation of auto(i.e. stack) vs static vs malloc memory

Note a sub-chapter is very short, in a concise book. A remarkably practical update on C, somewhat similar to [[safe c++]]. Content isn’t theoretical, and not so relevant to interviews, but relevant to real projects and GTD

Eclipse CDT + gdb setup

update

PATH is a per-project config, not optional.

CCB->settings->toolSettings->g++compiler->misc -> turn on verbose to see which g++.exe in use
–c++11 mingw
mingw-builds installer either errors out or was too old… I  used mingw-w64 instead

http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win32/Personal%20Builds/mingw-builds/4.9.2/threads-posix/dwarf/i686-4.9.2-release-posix-dwarf-rt_v4-rev2.7z/download

install mingw and fix %PATH%. Go to mingw\bin\ folder. In dos, verify
g++ –version // gcc is the C compiler !!
gdb –version
copy the *make.exe to make.exe // needed in some of my projects
make –version
Even without IDE, I believe mingw g++/linker can convert your c++ source into executable. Mingw is designed to be usable without IDE. Both codeBlocks and eclipse users generally favor mingw over cygwin.

(Note you need the eclipse view “C/C++ projects” to see the Binaries + related stuff)

project properties -> Builders — I didn’t change.
project properties -> c/c++ general (CCG) — no need to change.
project properties -> c/c++ build (CCB) — contains every important config for C++. Amidst the CCB config maze, #1 factor is tool chain ( CCB->toolChainEditor ). Eclipse often defaults to CrossGCC + CDT_InternalBuilder [3]. Leads to this Question

Q1a: is that enough? mingw unnecessary?
A: I thought “Sometimes Partially Usable”, but I guess it’s an illusion, and we still need mingw.

Q: does eclipse come with gdb, so we don’t need to install mingw?
A: probably not. Apparently, gdb.exe must be in %PATH%

[3] To remind you which builder is in use, build console says “…. builder is used”

Now that’s the preliminary. Let’s zoom into compiling and debugging your project.
Q1b: does eclipse come with g++ compiler?
A: probably not. Eclipse looks for g++.exe in %PATH%, failing which it always always always fail to build.

Fix 1) First install mingw. Usually you can but sometimes can’t build using default crossGCC, in which case change toolChain=mingw (usually not needed). Should build a [projectName].exe, just as msvs. Runnable in dos.

Surprise #1 — by default, there’s no debug config for your project. I think that’s why you can build a good executable but can only run it in dos, not F11 — you get BinaryNotFound. That leads to …

Fix 2) create a debug config [2], in Run->RunConfig->c/c++App->new. Mention your [projectName].exe. If it’s not recognized as IDE-runnable, You may need to mess with the CCB->Settings->binaryParser (PEWindowsParser?) and restart IDE, rebuild…. Now you can run it in IDE, but you may or may not have problem debugging it. That leads to another Fix and Q&A

Fix 3) –>
Q: Minimum effort to fix debugging?
A: CCB->ToolChainEditor->currentToolChain = mingw. You can leave InternalBuilder alone.

[2] a debugConfig is also a runConfig.

arbitrage definition – any time before maturity

My understanding of the mathematical definition of arbitrage is vague. (I think in real financial world the precision may not be relevant.)

Here is one interesting point – if portfolio A and B have identical terminal value, then any time before maturity, they must always have equal market value, otherwise arbitrage exists. But what if (short) selling or is restricted or trading over a certain period is restricted?

In  real markets, many factors prevent arbitrage

* no bid or ask when you notice a mispricing
* insufficient quantity in the bid/ask. You may wipe it out then wait in vein.
* trading restrictions by authorities,
** short selling disallowed 
* most common factor – wide bid/ask spread, so you can’t really make any money. I think this is the case in most securities including most options.

eq-fwd contract – delivery price K

Eg: me buying Blk 155 flat. In Oct we agreed on $615 delivery price. Cash-On-Delivery on the delivery date in Feb. “Logistics”… No exposure no mkt risk.

Eg from [[hull]] P104. $40.50 delivery price means $40.50 cash to change hand on the delivery date.

Simple rule — No cash flow on execution date – different from most other trades. Simple difference yet very confusing to some.

Simple rule — To understanding the “delay”, we can imagine sky high interest, carry and inflation rates.

Simple rule – Cash-On-Delivery

I feel the delayed cashflow is at the heart of the (simple) arb and math. If we aren’t absolutely clear about this delay, big messy confusions …

EE context — yes deliver price is an important factor to PnL, risk mgmt etc
QQ context – delivery price is the price quoted and negotiated

Q: In each fwd contract, are there 2 prices?
QQ context – 1 only
EE context – 2 indeed. Similar to simply buying then holding IBM shares. Both prices are relevant in the EE context —
• K is the negotiated “execution” price, implicitly written into the fwd contract
• there’s a live market price for the same fwd contract.

vector initializer: disallowed in field declaration until c++11

in a field declaration, you face restrictions:

vector<int> vec; //acceptable
vector<int> vec(9); // field initialization, disallowed until C++11. See https://stackoverflow.com/questions/24149924/has-the-new-c11-member-initialization-feature-at-declaration-made-initializati

You can write this kinda code in a *local* variable definition though.

swaps illustration diagrams — how to read

This write-up covers IRS, x-ccy swap…

These block diagrams are popular and partially useful, but beginners often don't realize:

* initial context — typically a corporation has a periodic liability, or an investor has a periodic income.

** We had better ignore all the other arrows first.

* the motivation — typically to convert the initial single arrow to other arrows. The swap contract adds 2 arrows, one of them cancelling out the pre-existing arrow.

** we had better focus on the 3 arrows and ignore other parts of the diagram.

yield curve , according to Jeff

Jeff’s lecture notes (in 0xpdf) has detailed explanations on

1) EUR OIS YC bootstrapping using specific OIS instruments
2) Libor YC under OIS discounting — so OIS curve + libor curve needed.
3) Libor curve for a non-default tenor, such as 6M or 2M

lots of “root-finding”… but not too hard.

A YC (or a term structure) can be represented as a series of
* spot disc factors
* fwd disc factors
* spot interest rates
* fwd interest rates

Rebanato – good author on fixed income models

recommended by Sian Hwee.

Ronnie said Black model is popular (largely due to simplicity, and historical reason), and many option products are quoted in terms of vols implied from the Black model. 
TA seems to agree that the advanced models (beyond the Black model) are still needed but indeed harder than the earlier lectures before the Black model.

buying (i.e. long) a given interest rate

Tony (FX lecturer) pointed out “buying” any variable means executing at the current “level” and hope the “level” moves up. (Note a mathematician would point out an interest rate is not directly tradeable, but never mind.)

Therefore, buying an interest rate means borrowing (not lending) at a rock bottom rate.
Wrong intuition — “locking in the interest income stream”.
Eg: Say gov bond interest is super low, we would borrow now, and hope for a rise.
Eg: Say swap rate is super low, we would lock it in — pay fixed and lock in the floating income stream, and hope for the swap rate and floating stream both to rise.

bid side of fx swap point means@@

Q: given a pair of bid/ask quotes in fx swap point, what kind of trades are we talking about implicitly?

A: dealer is sell/Buy ccy1. The spot leg is sell ccy1. The far leg is Buy ccy1.

Note we are taking the dealer’s position, not the market-taker’s.

Note “bid” refers to the far leg, not the near leg.

Note ccy1 (not ccy2) is the asset being traded.

enough c# mileage accummulated@@

Your mileage will show in IV and in projects, but IV is way, way more important than real project performance — You only need to be barely competent to get your job done, solving common problems at your pace (though at Baml my own pace was slower than other team members). No need to be competent to solve all tricky problems, some are too tough for everyone. But you better ace the IV.

– – I still feel less familiar with some everyday tasks than my c# veteran colleagues.
– – i did rather few complete projects like Guardian and many enhancement projects. In contrast, veteran c# guys did more big projects. The number of years isn’t as important as complexity and variety of challenges. VARIETY — for eg a web dev expert (or a DB-centric c# coder) isn’t really a complete c# expert.

– – wpf is a specialized skillset, like swing, or web dev or sockets. I didn’t get a lot of wpf hands-on mileage yet.
– – wcf is another specialized skillset. I lack mileage.
– – assembly, appdomain, GAC

= = people agree that I can get my job done and meet most technical challenges, even if non-trivial. (“tactical”)
= = explaining, justifying my design choices – not always convincing. Not only c#, but java too.

= = excel integration is one of the most valuable among the specialized c# skills. I have some experience.

+ + When presented a new c# challenge, when pushed to the frontier of my c# know-how, I am competent to construct a basic “infrastructure” and then search on-line for the missing pieces to complete the loop meeting the challenge

+ + competent with most everyday troubleshooting.  Some troubleshooting is beyond my current skill but I feel many are hard for my veteran colleagues too. If my colleagues can solve 50% of the tech problems, then my level is close to that. This competence comes from mileage i.e. real world projects. The more projects one takes on, the more competent.

+ + like Venkat, I did practice with some hot c# features like threading, closure, remote debugging …

+ + much more confident with MSVS than before. Perhaps comparable to my Eclipse confidence.
+ + on some of the hot but purely theoretical IV topics (fake mileage), I have read up quite a bit and appreciate their nuances. I can follow most discussions on these topics –
*GC, dtor, finalizer
*threading
*value/reference types
*dynamic type

Morris in-order walk]O(N) #O(1)space

I feel this is too hard and unlikely to come up in coding interviews. Also, most trees have up-links, so the no-uplink constraint is artificial and unrealistic. In reality, Morris complexity is usually unnecessary.

–threaded binary tree is the basis of Morris

https://en.wikipedia.org/wiki/Threaded_binary_tree

The Morris algo need to construct the threaded BST, walk and remove the extra links, all without recursion.

  • Tip: For my ascending walk, I only add right-up thread link to bring me to my ancestors. I don’t need any leftward thread link.
  • Tip: All the thread links point upward
  • How many right-up links? Let’s define two clubs Honey and White.
    • every node HH having a left child will get a incoming right-up link pointing to it! After printing HH’s left subtree, this link is used to revisit HH.
    • Except the very last node, every node WW without a right child needs to add a right-up link, so we don’t get stuck at WW.
    • If the Honey club has H members, and White club has W members, then I think we create H right-up links. W +1 = H
    • A node can be both Honey and White i.e. it has a right-up link and is also target of a right-up link.
  • Tip: the sequence of Honey nodes to try has to be top-down. We must create the uplink to every higher Honey node first, as insurance that we can always come back.  While a higher Honey node is locked down and we search for its predecessor in its left subtree, we ignore any lower Honey node
    • First time we hit a Honey node, I’m sure it is not uplinked. After we get it uplinked, we must descend Left.
    • 2nd time we hit a Honey node, I believe its left subtree is completely fixed, so if we descend left again, we will go to a dead end. We must move right, either down or up.
  • Tip: should really use a few variables instead of “cur”. This “cur” is like a “temp1” variable used in first pass, then temp2 variable in 2nd pass etc. These variables are not related at all.

https://github.com/tiger40490/repo1/blob/cpp1/cpp1/binTree/MorrisInOrder.cpp is my c++ implementation with a concise/cryptic implementation and an “unfolded” elaborate implementation

c++IV: importance: knowledge imt dev xp

1) Many hard-core tech interviewers (Yaakov, Jump, 3Arrows, Bbg, nQuants …) often asked me to explain a language feature, then drill in to see if I really do understand the key ideas, including the rationale, motivation and history. This knowledge is believe to … /separate the wheat from the chaff/

This knowledge can’t be acquired simply by coding. In fact, a productive coder often lacks such knowledge since it’s usually unnecessary theoretical knowledge.

2) West Coast always drills in on algo (+ data structure). No way to pick up this skill in projects…

1+2 —> many interviewers truly believe a deep thinker will always learn faster and design better.

#1@what I enjoy: body-build`

(Avichal asked me …)

#1 of what I enjoy most – body-building. There are various elements that make it challenging, engaging, sustainable

* some value-add for the tech community

* relevant to immediate IV -and- value-add-for-employer, which translates to stable and hopefully rising income…
Example – high performance c++ on linux

* unlocking additional job markets
Example – c++, c#, swing, socket
Example – FX domain knowledge
Example – quant stuff

* Real insight gained only by in-depth study, overcoming a non-trivial entry barrier, and building a lead over competitors
Example – quant trading strategy
Example – threading, STL,
Example – insights into c#
Example – stat risk content, even though not really relevant to my interviews.

* strategic value to my competitive position
counter-example: secDB

c++IV Art@Click #Jens

Q: buffer overflow?
%%A: avoid arrays, use vector
Q: XOR usage?
AA: usages? easy to google
Q: why bitwise shift?
%%A: mostly an optimization as far as I know, but the compiler probably translates integer multiply/divide already.
AA: usages? easy to google
Q: what’s wrong with pointers?
Q: dangling pointer?
Q3: what are the common exceptions in c++?
%%A: c++ has a few standard exceptions and a lot of UB; java has lots of standard exceptions and no UB. q(new) and dynamic_cast…
Q3b: undefined behavior?
%%A: much worse than exceptions or error codes
%%A: perhaps fairly consistent on one platform, but I know writing beyond an array’s limit is indeterminate. See [[c++ debugging)]
Q: exceptions – why do you not want to use it in your API?
%%A: can of worm. If I throw I can’t control how clients use this API. What if it’s thrown in a dtor? What if they don’t catch by reference? What if they catch a sliced one or a copy rather than the original exception object I want them to get? What if they catch by pointer and try to delete or forget to delete? Java cleaned it up.
%%A: I don’t see a lot of well-regarded API’s exposing exceptions
%%A: there’s performance cost
A: the best practice has always frowned on exception specifications. C++11 favors “noexcept”
A: now I think we should be consistent throughout – either throw exceptions consistently or never.
Q: memory leak – what is it and how do you deal with it?
%%A: valgrind replaces malloc with …?
%%A: provide class-specific op-new (and delete), which is safer (see effC++) than a customized global op-new. Add your own house keeping code therein…
Q: how is semaphore different from a mutex
%%A: I think a mutex is more basic and usually provided by the kernel (For a userland thread the thread library not the kernel must provide the mutex). I guess the counting semaphore is implemented using mutex + condition variables, since the semephore may need to inform the waiting threads.
Q: preprocessors?
%%A: 3 usages in my projects – #includes, macros and conditional compile. Now I think template meta programming also uses a lot of macros.
Q: stack trace?
%%A: very useful, that’s why java, c#, python, perl provide it, and GDB too.
A: [[safe c++]] shows simple and robust technique to build a stack trace upon assertion failure
I said many times “I’m philosophical about that” – meaning “it’s controversial IMO and I have my views which may look naive or extreme or eccentric”

[[java performance]] by Scott Oaks

–[[java performance]] by Scott Oaks

 

best of breed..see chapter details on

[jvm] heap memory

[jvm] threading

[jvm] instrumentation

JPA

serialization

lambda, stream  (java 8 interviews!)

 

The Introduction chapter outlines 3 broad aspects

* JVM – like memory tuning

* java language – like threading, collections

* Java API — like xml parser, JDBC, serialization, Json

 

JVM tuning is done by “system engineers” who may not be developers.

 

C++bbg Standard IV Questions { Zack

1. How is keyword virtual used in C++?

2. Does better O() algorithm always works faster in real cases?

3. Between pre-increment (++i) and post-increment (i++) operator, which one is more efficient in both built-in and overloading case? …….. [[more eff c++]] item 6

4. Please compare array and linked-list in terms of insertion and access

5. Please name some sorting algorithms and their time complexity

6. Can you tell me the difference between stack and heap?

7. What Linux command do I use the find a file in a directory recursively?

8. what is the virtual functions and destructors

9. what is the constructor destructor orders of a class then an inherited class

10. what is the most known sort algorithms , and what is the complexity of each

11. Smart Pointer, how does it work.

12. Templates, when use instead of inheritance…….. [[eff c++]] Item 41

13. Polymorphism, when use multi inheritance, problems that can happen, ……. [[eff c++]]

14. Sockets, monitoring sockets.

15. Multithreading, give a small example of Producer, Consumer.

16. Debugging issues, using GDB

19. TCP/IP and Multicast

20. STL and Boost libraries

par swap rate drop means …@@

For a given tenor (say 1Y)

 

I think treasury yield rise (or drop) has a simpler interpretation….

 

I think Libor ED deposit rate drop (or rise) has another simple interpretation …. and has a credit element.

 

Libor par swap rate drop has a non-trivial interpretation….

 

OIS swap rate is even more complicated…

OIS fund.rate – which side pay xq@collateral#eg IRS

I think whoever accepting/receiving/holding the collateral would pay interest on the collateral. I think the same guy can also lend it out, perhaps overnight. Similar to a bank holding your deposit…

Consider cash collateral for simplicity…

The original owner of the collateral could earn a daily interest if deposited in a bank. When she pledges it as collateral, she is still entitled to the same interest income. Someone has to pay that interest.

Now consider a MBS or a bond. They all generate a periodic income, just like cash collateral.

null^stray^uninitialized^void pointer

$ dangling/wild/stray ptr and *ref* — holds an address but already bulldized, possibly *reused* => u can’t delete, write or read the memory location. Merely reading (not touching) someone else’s memory location can have unknown effects — like incrementing a read counter.

P132 effC++ confirms a dangling reference can point to a memory cell already reused by someone else.

$ uninitialized/unseated ptr — address[2] undefined and could be a completely wrong address mapped to some program’s hot button => u can’t delete, write or read it. Always anchor your pointer before dereferencing.
[2] However, ptr object has an address and occupies 4 bytes

Objects can be uninitialized  too. See post on default-initialize.

$ uninitialized ref? won’t compile

$ null ptr — address 0, interpreted as a well-defined fake address. Safe deletion
$ null ref? won’t compile

$ void ptr — java. qq[ Object o ]
$ void ref? won’t compile

For each of these special scenarios, delete, deref/unwrap, detection (of null…), compare, reseat, assign … have special semantics.

%% priorities in a take-home cod`IV

A lot of times the requirements are way too numerous or stringent, given the time limit. Must give up some. Here are my priorities:

  1.  basic functionality. The essential problem should be solved, or shown to be solvable.
    • pass the essential test cases only
  2. On that foundation, add as many big features (in the problem statement) as I can within the time limit. Leave out the small features.
  3. simplify. Simplicity is the first element of clean , readable code.

I guess some hiring managers are very particular about code quality and readability. I feel it’s like beauty contest. I would give up in those cases. I was told JPM follows [[Clean Code]] when judging/scoring/ranking code submitted.

Need to ensure file timestamps are all within a short window. Prefer to use fewer files. Java solutions require more files :(. If I claim 2H, then better leave some rough edges in the code like input validations.

typedef: non-optional in this case

Someone asked me to write a utility function to print any STL container, in my own loop. I suggested we follow the STL convention to use iterator inputs. Echoed on http://stackoverflow.com/questions/4657767/how-to-templatize-a-function-on-an-stl-container-that-has-an-iterator. However, what if we pass the container itself as input (assuming it’s a standard-conforming container)?

template
void dump(const CT& cont) {
typedef typename CT::const_iterator iterator; //no choice
iterator i;
//won’t compile — CT::const_iterator i;
for(i = cont.begin();   i!= cont.end();   ++i){
cout<<*i <<” “<<endl;
}
}

This works but the typedef isn’t sugar-coating. Without it you get

dependent-name ` M::const_iterator’ is parsed as a non-type, but instantiation yields a type

Very loosely, CT::const_iterator i suggests to the compiler to create a concrete type for i but CT::const_iterator is not a generic type, not “concretized” [1]. Solution — The typedef dresses up this “generic type” as if it’s an end-user type, usable in a variable declaration

[1] remember the Barcap FMD eval objects?

typedef as prefix: syntax demystified

I find the typedef syntax not as simple as it appeared. http://stackoverflow.com/questions/3783016/fundamental-typedef-operand-syntax is the best explanation of the very confusing typedef syntax.

        int x; // declares a variable named ‘x’ of type ‘int’
typedef int x; // declares a type     named ‘x’ that is ‘int’
typedef char Decimal[20];
        int(*F)(size_t); // declares a variable named F of type ‘int(*)(size_t)’
typedef int(*F)(size_t); // declares a type     named F that is ‘int(*)(size_t)’

If you add the “typedef” prefix, instead of declaring a VARIABLE, you’ve declared a new TYPE-ALIAS instead.

dtor is simple thing.. really@@

update: [[safe c++]] has a concise argument that if ctor is allowed to throw exception, then it’s possible to have dtor skipped accidentally. Only an empty dtor can be safely skipped.

This is typical of c++ — destructor (dtor) is one of the most important features but quite tricky beneath the surface

* exception
* dtor sequence – DCBC
* virtual dtor
* synthesized dtor is usually no good if there’s any pointer field
* lots of undefined behaviors
* there are guidelines for dtor in a base class vs leaf class — never mindless
* objects put into containers need a reasonable dtor
* when the best practice is to leave the dtor to the compiler, you could look stupid by writing one, esp. in an interview.

* smart pointer classes is all about dtor

* RAII is all about dtor

* interplay with delete

*** placement new, array-delete vs delete

*** override operator delete

*** double-delete

*** ownership !

java 8 default method – phrasebook

[[mastering lambdas]] is concise about method call resolution — corner cases, backward incompatibilities… I’m glad to be able to understand all of the practical issues.

j4, mtv — and the problem addressed : adding methods to a published interface. Impossible before java 8. Need to really understand it.

MI … isn’t a problem in java 8 – no “state” allowed in default methods.

vs abstract classes – instance state…

diamond – not a problem in itself

why delayed for so long – aversion of  MI

return to sg as a West Coast programmer@@ too niche

Upshot: I feel the dev (coding) experience in West Coast would be even less relevant in Singapore.

Financial domain tech skills are considered niche. West coast is even more so.

A realistic scenario — what if I specialize in php or big data? Extremely rare tech roles to match the US salary. I think the 2016 Zaobao article  interviewed some of these techies.

The type of tech skill considered in-demand and “upstream” in the US (c++, quant dev, core java not non-J2EE..) is probably too niche in the Singapore context…

In terms of technical expertise (not management expertise) I think SG needs system integration “specialists” (I consider them generalists) in large government projects.

FRA^ED-fut, another baby step

I think the differences like convexity adjustment are not “sticky” in my memory, after I tried many times to internalize, so no thin->thick->thin…

Jeff (MSFM) pointed out

* FRA — on expiry date you know the settlement amount. 2 days later that amount physically settles. That’s the accrual period start date!
* ED futures – every day you give or take a bit of the (usually big) settlement amount. On IMM date full amount settles. No 2-day delay.
ED has Neg convexity versus FRA, so whether your realized pnl is P or L, FRA is a bit “better” (for the holder) than ED for the same strike.

rope-cliff puzzle #use stopper

Q:You are on the top of a 200m cliff. You have a 150m long rope and a knife. You can only tie your rope where you stand, or 100m below on a tree. Can you reach the bottom of the cliff without doing any free fall?

—-Well-known solution, using a loop
Suppose top of cliff is point C and the tree is point T and the midpoint between C and T is point M.

Cut (1st and last cut) 100M of rope and put into pocket. Tie the remaining 50M at C then descend to M. Convert the end of this rope into a loop at the point M. Lubricate the loop then pass the 100M rope through, to convert it into a 50+50 double rope. Descend to T then retrieve the entire 100M.

—- my solution that can go down 150m below the tree 🙂
Form a small loop at top of cliff. Tie a “stopper” object like the knife (bigger than the loop) at end A of the rope and run end B of the rope through the loop until the stopper touches the loop. Now hold end B and descend 100m to the tree. Now let go of end B so the stopper pulls the entire rope down through the loop and falls into your hand.

socket stats monitoring tools – on-line resources

This is a rare interview question, perhaps asked 1 or 2 times. I don’t want to overspend.

In ICE RTS, we use built-in statistics modules written in C++ to collect the throughput statistics.

If you don’t have source code to modify, I guess you need to rely on standard tools.

tryGet, tryAdd … on maps – c#, STL etc

TryGet?
* in dotnet the plain lookup operation will throw exception if non-existent. I hit this frequently in my projects…
*** STL map silently adds an empty entry! For the justifications (crazy interviewers?), see http://stackoverflow.com/questions/4382656/why-is-stdmapoperator-so-counter-intuitive
*** java returns null http://stackoverflow.com/questions/5220619/return-from-hashmapstring-string-when-no-key
* basic Dictionary offers TryGet…()

TryAdd? Concurrent dict only, not the basic Dictionary.
* in dotnet, the plain Add() will throw exception if clash
*** STL map will silently ignore the insert() attempt, but operator[] can be used to insert or overwrite ???

TryRemove? No such thing. Using the plain Remove to remove a non-existent is no-throw.

FB 2questions #regex..

—Q1: write a stateless utility function to take in any string consisting of a-z, and return a string with all the original characters appearing once only. All 2nd and subsequent occurrences should be removed. eg: abcbdc → abcd

I don’t want to new up a string in my utility, so I decided to take in an output char* buffer which should be large enough.

I guess this is all about efficient speed coding.
—Q2: Suppose there’s a regex grammar that can accept exactly 3 constructs
1) literals — any combination of abcdefghijkljmnopqrstuvwxyz,
2) dot (.) that matches any one character
3) asterisk — a standard quantifier

For example,

“a*” can match empty string, a single a, or aa, or aaa etc.
“.*” matches any string including the empty string.
“a*b*a” should match “a” and also match “aa”, or “ba”, or “aaa”

—-
Now, write a utility function bool match(char const * regex, char const * S);

Note entire string S must match entire regex. We don’t want to get a false positive when only a substring of S matches the regex.
—– some tips—–

  1. Easy part — if regex ends in literals, then they must “eat up” the tail of S exactly.
  2. After this step, if regex ends with a dot, it will just eat up the last char of S. After this step, regex definitely ends in a star.
  3. If 2nd char in regex is not a star, then first char must eat up head of S.
  4. Repeat previous step until we see star as 2nd char.
  5. Now we can basically split the regex into segments. Each segment is either a single literal, a single dot, or a non-star followed by a star.

Interviewer said — First assume dot is not allowed in regex. We will deal with the dot later.

—– analysis
EPI Question 6.23 is very similar to my Facebook interview. I told FB interviewer that we don’t NEED such problem solving at work. He said this is one method (standard method?) they assess a candidate’s coding abilities.

I feel it (and google questions) is like IQ test or probability test or abstract reasoning test — irrelevant to work, but used to assess learning capacity. They don’t want a dumb person on their team.

The truth is, practice is key. There are patterns. A very very smart person will still fail if without enough practice. A mediocre guy can speed up significantly if practised enough. I said the same thing to My Hwa Chong math teacher Tony Tan. This factor is also the reason I became so strong in physics.

Q: A simple regex (SRE) can use alphanumerics, dot and star. It is enclosed between implicit ^ and $. Write a match() function taking a SRE and a word. No white space allowed.

https://github.com/tiger40490/repo1/blob/py1/py/regexFB.py is my implementation. Here are a few test cases:

assert not match(”, ‘.’)
assert match(‘xyab-abc’, ‘.*ab.*c.*x*’)
assert match(‘xyab-abc’, ‘.*ab.*c.*.*’)
assert match(‘xyab-abc’, ‘.*ab.*c’)
assert match(‘aaaaaaab-abc’, ‘a*aab.*c’)
assert match(‘aab-abc’, ‘a*aab.*c’)
assert match(‘aabc’, ‘a*aab.*..*x*’)
assert not match(‘abc’, ‘a*aab.*c’)
assert match(‘a-aab’, ‘a*.*a*aab’)
assert not match(‘a-aab’, ‘a*a*aab’)

bonds let us to lock in a profit today to be realized in N years

After my lecturer touched on this point, I did some research.

For equities, say IBM, if we buy it at $100 and hope to cash out about
5 years from now, we are never confident. At that time, price could
drop below $100 and we may have to wait indefinitely to recover our
capital. That’s the nature of equity investment. Barring another
financial crisis (which i consider unlikely in the next 20 years),
price should recover but I might have bought at the peak, as I did
many times in my experience.

For a bond with a coupon rate 7.5% per year, maturing in 5 years, the
current price could be about $100, which translates to a yield around
7.5%, probably a high yield bond issued by some lesser-known entity
XYZ. If all the coupons are paid out only on maturity without
compounding, then the yield turns to be around 6.5%, as illustrated in
the attached spreadsheet.

The special thing about bond (relative to stocks) is, we kind of lock
in an annualized return of 6.5% at the time we buy it, barring credit
events.

As the attached spreadsheet illustrates, today we pay about $100 to
own the bond, and in 60 months we are sure to receive exactly $137.5
i.e. $7.5 x 5 years coupon payment. This terminal value is not subject
to any market movement. The only uncertainty is credit default. Most
bonds we deal with, even the high yield bonds, are very unlikely to
default. If you buy a bond fund, then you would invest into hundreds
of bonds, so some defaults may be compensated by other bonds’ positive
return.

If you don’t want to worry about defaults at all, then get a
investment grade bond, perhaps at a yield of 4%. You still lock in
that annualized 4% if you hold it till maturity.

The spreadsheet shows that even if there’s a credit crunch some time
before maturity, the bond’s market value (NAV) may drop drastically,
but it is sure to recover. Even if yield goes up in the last year,
barring default, the maturity value is still exactly $137.5. This
guaranteed return is something stocks can’t offer.

There are other factors to muddy the water a bit, but the simple fact
is, barring default, we could effectively lock in a profit today, to
be realized on the bond’s maturity date.

I guess that’s how insurers can guarantee returns over many decades.
They buy very long bonds which offer higher yields.

What do you think?

PURE-interface types ] c++^java

http://stackoverflow.com/questions/318064/how-do-you-declare-an-interface-in-c
Someone pointed out

“The whole reason you have a special Interface type-category in addition to abstract base classes in C#/Java is because C#/Java do not support multiple inheritance. C++ supports multiple inheritance, and so a special type isn’t needed. An abstract base class with only pure virtual methods is functionally equivalent to a C#/Java interface.”…. actually with minor differences.

The sample code shows no special ctor, though the dtor is public virtual but without “=0” (not pure virtual), so I assume an “interface” type in c++ should have a virtual dtor, since it is designed to be subclassed.

Google style guide is more strict — A class is a pure interface if it meets the following requirements:

  • It has only public pure virtual methods, non-pure virtual destructor, and static methods
    • I feel the dtor should be empty since there’s no instance field.
  • It may not have non-static data members — same as java8 interfaces
  • It need not have any constructors defined. If a constructor is provided, it must take no arguments and it must be protected.

FX, short term rate, YC…again

(labels – fixedIncome, original_content, z_bold)

I feel FX market mostly watch short term rates, not long term rates. Short-term typically means below 1 year.

– long term IR Futures are based on government debt + … other factors. Examples — T-futures, German Bund futures,…
– short term IR is usually based on OIS, Libor or similar inter-bank offer rates in other cities like Tokyo, Singapore, Hongkong …

Short term (including O/N) borrowing is probably more prevalent than long term borrowing. Credit risk grows significantly with the borrowing duration.

Yield Curve and Swap Curve are directly comparable. Yield curve is about spot Interest Rate. Swap curve is also about spot IR !! although swap curve is constructed using mostly forward Interest rates — only the first few (3) months of the curve data points are constructed using spot IR rates

* Conceptually, you can imagine we convert either spot IR or fwd IR to discount factors at various valuation dates.
** we could get a DF from 2040 to 2030.
** we could get a DF from 2042 to today.

From a discount curve, we can “back out” the spot rates for various tenors. A spot rate is directly related to a DF to today.

* Libor itself is a spot lending rate but Libor Futures and Libor swap contracts are about Forward lending rates — Very important

[15]essential GTD/zbs to build algo trading system

Hi

(See also http://bigblog.tanbin.com/ post on HFT)

Just to share some observations and reflections. More than one Asia (and to a lesser extent US) recruiters have reached out to me as a potential lead-developer for a HFT engine, to be created from scratch. I believe there are not many old hands in Singapore. Even in the US, this is a relatively small circle. Not a commodity skill.

A small trading shop would have very different needs than a big bank, so their HFT engine will use off-the-shelf tools for all but the most critical, customized modules. (I had a brief blog post on it.) What are the 10 essential know-how i.e. Essential functionalities you must know how to create (prove)?

  • see also my 2018 post on execution system^OMS^FIX…
  • executing strategy for order origination, i.e. machine trading
    • market data processor, sockets
    • order book replicated from market data? perhaps at the center of the engine
    • OMS (Kenny) ? in some cases we leverage the exchange query API or 3rd-party solutions
  • [W] FIX or other order submission protocol
  • in-sample testing. I used Matlab for this. Can be much simpler than the production system.
  • [3] real time pnl, updated by market data
  • [3] barebones blotter, or perhaps command line interface?
  • [3] store historical data for analysis. Perhaps SQL or KDB.
  • [3N] reference data
  • [3] post-trade STP

Low-level tech knowledge
• [N] threading
• [NW] Boost
• debugger
• [N] memory leak detection
• [W] socket programming

[3 = 3rd party products could be good enough in Every component, but this one is more likely]
[N = Not needed in every shop, but often required by interviewer]
[W = my weakness, relatively speaking]

-ve fwd points => ccy1 weakening => ccy1 higher inflation

(As we get older we rely increasingly on intuition, less on memorizing)

Tony shared this quick intuition :
* when we see a …negative fwd point, we know ccy1 is …weakening due to … higher inflation in that country, such as AUD or BRL
* when we see a positive fwd point, we know ccy1 is strengthening due to ultra-low inflation such as EUR.

(Note the lowest inflation currency, JPY, is never a first currency…)

Remember ccy1ccy2 = 108.21 indicates the “strength of cc1”

– When we see ccy1 IR lower than ccy2, we know ccy1 will likely strengthen in the short term. You can imagine hyper-inflation in ccy2
– When we see ccy1 IR higher than ccy2, we know ccy1 will likely weaken in the short term. You can imagine hyper-inflation in ccy1

option math : thin -> thick -> thin

Many topics I may have to give up for lack of bandwidth. For the rest of the topics, let’s try to grow the “book” from thin to thick then to thin.

—–

+ PCP

+ delta hedging

+ graphs of greeks

+ arbitrage constraints on prices of European calls, puts etc. Intuition to be developed

+ basic strategies like straddle                     

 

LG American options

LG GBM

LG binary options but ..

+ Roger’s summary on N(d1) and N(d2)

LG div

LG most of the stoch calc math but ..

LG vol surface models

+ some of the IV questions on martingale and BM

 

Z_0 == discount factor

Background – in mathematical finance, DF is among the most basic yet practical concepts. Forward contracts (including equity fwd used in option pricing, FX fwd, FRA…) all rely directly on DF. DF is part of most arbitrage discussions including interview questions.

When we talk about a Discount Factor value there are always a few things implicit in the context

* a valuation date, which precedes

* a cash flow date,

* a currency

* a financial system (banking, riskfree bond…) providing liquidity, which provides

* a single, consistent DF value, rather than multiple competing values.

* [1] There's no uncertainty in this DF value, as there is about most financial contracts

– almost always the DF value is below 1.0

– it's common to chain up 2 DF periods

An easily observable security price that matches a DF value is the market price of a riskless zero-coupon bond. Usually written as Z_0. Now we can explain [1] above. Once I buy the bond at this price today (valuation date), the payout is guaranteed, not subject to some market movement.

In a math context, any DF value can be represented by a Z_0 or Z(0,T) value. This is the time-0 price of some physical security. Therefore, the physical security “Z” is a concrete representation of the abstract _concept_ of discount factor.

math power tools transplanted -> finance

南橘北枳

* martingale originates in gambling…
* Brownian motion originates in biology.
* Heat equation, Monte Carlo, … all have roots in physical science.

These models worked well in the original domains, because the simplifications and assumptions are approximately valid even though clearly imperfect. Assumptions are needed to simplify things and make them /tractable/ to mathematical analysis.

In contrast, financial mathematicians had to make blatantly invalid assumptions. You can find fatal flaws from any angle. Brian Boonstra told me all good quants appreciate the limitations of the theories. A small “sample”:

– The root of the randomness is psychology, or human behavior, not natural phenomenon. The outcome is influenced fundamentally by human psychology.
– The data shows skew and kurtosis (fat tail).
– There’s often no way to repeat an experiment
– There’s often just a single sample — past market data. Even if you sample it once a day, or once a second, you still operate on the same sample.

binary tree in-order walk #famed bbg Q

Is there a way to design an iterator over a binary search tree with the following properties?

1. Elements are visited in ascending order (i.e. an in-order traversal)
2. next() and hasNext() queries run in O(1) time.
3. Memory usage is O(1)

——-
I feel O(1) memory is impossible since this is recursive (though all recursions can convert to iteration with a queue bigger than O(1)), with a stack data structure of size H := height of tree.

Similarly, hasNext() need to work through the stack of size H, so O(1) run time impossible

Morris may meet the requirement.

academic route as a long term career option#Sam UChicago

A letter never sent out…

Hi Sam

(This is more like a personal blog, to record my thoughts and conversations.)

I never considered those options you posed today

Q: 2nd master's degree?

A: I liked the part time study experience so far. Will take a 2nd Masters if someone pays for me.

Q: I did think about teaching at polytechnic level, but teach what subject?

A: Either IT or financial math, or perhaps data science — after I spoke to Bernie.

local vol^stoch vol, briefly

Black-Scholes vol – constant, not a function of anything.
** simplest

stoch vol – there’s a dB element in dσ. See http://en.wikipedia.org/wiki/Stochastic_volatility

** most elaborate
** this BM process is correlated to the BM process of the asset price. Correlation ranging from -1 to 0 to 1.

local vol – sigma_t as a deterministic function of S_t and t, without any “stochastic” dB element.
** middle ground. A simplification of stoch vol

how effective is %%resume]NY^sg fin IT

* On Wall St, the battlefield is  the tech IV.
* In Singapore financial IT, the battlefield is the resume. I feel 70% of the battle is on the resume.

In Singapore, I have tried 3 times (2011, 2014 and 2015). Much fewer “senior” roles (i.e. 150k+); much lower chance of shortlist. I believe the competitors are way too many for each role.

On Wall St, Many friends (XR, YH, Mithun etc) all get many interviews without too much effort.

 

calling unknown code while hold`(or Not hold`) lock #XR

In c++, if the unknown code does a fork(), then all locks are replicated to new born process. See after fork(): threads

[[eff c#]] warns against calling “unknown” code while holding a lock. This advice applies to java and c++ too.

Now, What defines “unknown”? Any delegate can have an inv list containing unknown callbacks. Raising an event involves delegate invocation. If you receives an Action instance, realize it’s a delegate instance too.
Another category of “unknown code” might be implementations of an interface. You get a IComparable instance, and you just call Compare() without knowing the implementation
Suppose within obj1.method1() we grab a lock and then call the unknown code. Such unknown code could circle back to call obj1.method2(). If method2() also grabs the same lock, then no issue, thanks to c# reentrancy. Note c# reentrancy is implemented by counting — http://stackoverflow.com/questions/3687505/recursive-nested-locking-in-c-sharp-with-the-lock-statement
If method2 is on another thread, then we get a classic single-lock deadlock — method2 would be blocked by the lock held by method1(), hopefully for a short time only. If method1() is unfortunately waiting for method2 to finish its work on the other thread, then the deadlock would persist.
Even if there’s no locking involved, method2 may circle back to invoke method1 (on the same or a separate thread, on the same obj1 or another object), recursively. If this recursion is unplanned (like unplanned pregnancy:), then stack overflow may ensue.
Dumb luck if unintentional recursion doesn’t hit stack overflow.

PRICE is clean or dirty;YIELD is always "dirty"

Traders quote clean price. However, Full price, Dirty price, or Invoice price is the price used for settlement.

YTM is neither clean or dirty. YTM is always “converted” from dirty price. My lecturer said —

There is only one yield to maturity.  It is neither of a “clean” nor “invoice” type.  The formula relating yield to maturity to bond price refers to the invoice price, not the clean price. 

bond "callable" provision is a risk to investor#my take

see also post on price spread between callable and non-callable bonds

————
To a buyer of a callable bond, the call feature poses a “call risk”.

Q: Why is early repayment a risk to the lender? To me it sounds like an added value.
A: The issuer only exercises this option when advantageous. Advantageous to issuer always means bad luck for the counter-party i.e. bond holders.

Bond is called only in a low-interest period. Imagine you receive 10% pa coupons year after year and suddenly you get the principal back but you can get only 0.0% pa (like Japan or Europe) from now on 😦

When an investor is comparing 2 otherwise identical bonds, the one with the call option is worth less because there’s a risk (“call risk”) that cash-flow will be lower after the call option exercise.

Yield-to-worst is basically the lowest yield that could be realized if the embedded call is exercised. Buyer assumes what could go wrong WILL go wrong — Murphy’s Law. In such an analysis, the worst case to the investor is an early repayment, and reduced cash-flow subsequently.

However, my friend Ross (in the bubble room) in Macquarie said the callable bond they hold could get called and as a result they could realize a windfall profit. He said it’s a good thing but I believe they would forgo the high coupon interest.

bond "callable" provision is a risk to investor#CFA textbook

See also post on why a bond’s callable provision is a risk.

P260 of CFA textbook on Eq and FI has a concise explanation.

– Suppose A issues a riskless non-callable bond, for a $109 price.
– Suppose B issues a callable bond, with identical features otherwise, for $106.8 price. The $2.2 price difference is the value of the embedded call option (to the issuer).

If issuer A uses $2.2 of the sales proceeds to buy a call option (to receive the coupons), then A’s position would match B’s. When rates drop to a certain level, the B issuer would call the bond, ending her obligation to pay those high coupons. A would continue to pay coupons, but his call option would produce a cash flow matching the coupon obligations.

Notice the callable bond is cheaper because the issuer holds a call option — to be exercised if low-interest happens.

Also notice — as expected IR volatility (implied vol) rises, the embedded option is worth more and the price spread between the A vs B bonds will widen.

In fact, since A price isn’t sensitive to vol, B price must drop — intuitive?

The B issuer is (believed to be) more likely to call the bond and refinance at a lower coupon, whereas the A bond will continue to pay the super-high coupon until maturity. So bond A is more valuable to an investor.

c++11 QnA IV 3arrow

Q: In a move constructor, is the parameter “x” an rvalue reference? is there another rvalue reference in the call?
%%A: x is a rvr, but as a variable is an l-value expression since it is named and has a Location.

Q: What’s an rvalue reference actually, like a std::string && rvr1
A: I feel it’s similar to a regular reference variable and often treated as a pointer. Since “pointer” has multiple meanings, I would not say that. I speculate that compiler treats rvr1 as an special alias to the original object. A special name plate on the memory location. Compiler knows to treat the object-behind as suitable-for-stealing.

Q: what’s lockfree? How did you make it work in your projects?
A: see my blog about atomic{int}

Q: What part of the boost thread library did you use?

Q: for-loop in c++11?
AA: work for C-style arrays, initializer lists, and any type that has begin() and end() functions defined for it that return iterators.

Q: Why did you implement your own smart pointer and wrapper over int?
A: to avoid uninitialized variables. See post on uninitialized ..

Q: Can ctor throw exception? Why do you say it’s not best practice?
A: now I think it’s not necessarily best practice. Exception is the only way constructors can signal failure.

Q: What kind of algo is qsort? Average and worst runtime complexity?
A: average nLog(n), worst case n^2

Q: Recursive vs iterative, which is faster?
A: comparable, but space complexity lower for iterative?

Q: How did you use parallel processing in GS?
A: data parallellism, threading, and other techniques. Coarse-grained is ideal.
A: i guess pipelining parallellism is also relevant, using task queues

Q: (rarely quizzed) Translation lookaside buffer

Q: mutable keyword’s usage? How about in c++11?
AA: closure – captured variables can be modified if “mutable”.
http://stackoverflow.com/questions/105014/does-the-mutable-keyword-have-any-purpose-other-than-allowing-the-variable-to

Q(seldom quizzed): noexcept
AA: both an operator and a function specifier…

 

%%jargon — describing c++ templates

The official terminology describing class templates is clumsy and inconsistent with java/c#. Here’s my own jargon. Most of the words (specialize, instantiate) already have a technical meaning, so I have to pick new words like “concretize” or “generic”

Rule #1) The last Word is key. Based on [[C++FAQ]]
– a class-template — is a template not a class.
– a concretized template-class — is a class not a template
————————–

“concretizing” a template… Officially terminology is “instantiating”

A “concretized class” = a “template class”. Don’t’ confuse it with — “concrete” class means non-abstract

A “unconcretized / generic class template” = a “class template”.
(Note I won’t say “unconcretized class”as it’s self-contradictory.)

A “non-template” class is a regular class without any template.

Note concretizing = instantiating, completely different from specializing!

“dummy type name” is the T in the generic vector

“type-argument”, NOT “parameter“, refers to an actual, concrete type like the int in vector