# valuation of existing IR swap – example

On P54 the “closing a swap position” discussion is … very relevant. Start at the example on P57.

On T+0, enter 5.5%/Libor swap as fixed payer.

On T+1Y, prevailing (par) swap rate drops to 5%. Bad for the fixed payer as she has commitment to pay 5.5%. She wants out, and she doesn’t need any more loan. You can assume she has cancelled her project altogether. So she would hedge out her floating exposure and realize any loss on the fixed leg.

Specifically, she enters a new swap as a fixed Receiver this time, receiving (the lower) 5%. The new floating leg perfectly cancels the existing floating leg, with identical payment dates.

As a result, for the next 4 semi-annual payments, she would receive 2.5% and pay 2.75% every time. This is the kind of loss she must accept when closing the swap in an unfavorable market. If you sum up the present value of these 4 negative cashflows, you see the (negative) present MV of the fixed position. (Note each swap deal has a \$0 market value at inception.)

(The “fixed position” means the position of the fixed Payer.)

As of  T+1Y, the fixed position has a negative mark-to-market value given on P60, -\$94,049 on a \$10m notional.

It follows that to the original fixed Receiver, this existing swap deal now has a positive market value. Intuitively, this receiver is paying a below-market rate (5%/year) to receive the stream of floating coupons (i.e. the silver). The same stream is currently selling at 5.5%.

Yes it’s confusing! I feel the keys are
1) how to cancel out the floating leg exposure. You will then figure out that to close the swap, you need to take up a new fixed leg.
2) That would tell you the upcoming cashflows are positive or negative.
3) By summing up the PV of those cash flows you get the current MV.

Final MV formula is on P70.

# ##HFT: some defining features relative to similar systems

I learned from a seminar. I didn’t do any research. Just some personal observations.

• HFT is different from a broker execution algo in terms of holding period. HFT never holds a position overnight.
• HFT is alpha-driven. In contrast, a strictly sell-side trading engine is driven by customer flow.
• however, HFT doesn’t use market orders as much as limit orders, so it may appear to be market-making.
• an HFT engine makes many, many trades in a day, but so does an execution algo.
• HFT usually makes no directional bet. In contrast, fundamental strategies have a view. I know many sell-side traders have a view and may hold inventory overnight.

I think the distinction can become unclear between HFT and execution algos.

# plowback for zbs(+GTD)@@

For many years I was deeply convinced and motivated by the “Shanyou” notion that I ought to “plowback” for zbs and, to a lesser extent, GTD, not just aim at IV as the Mithuns would.

After working for 20 years, I now believe ANY tech knowledge, accu, deepening/stack-up, sustained focus … has extremely low leverage and basically worthless if not relevant to IV

• GTD skills? dominated by localSys. Tool knowledge can help but localSys is 10x more important.
• localSys xx is almost always cursory, rather than in-depth since unnecessary digging (pwm-comm bottom-up xx plan) is invariably unsustainable — The local systems are patchworks , destined for rewrite, illustrating few best practices
• BestPractice design? Almost never mattered in my career. After EMPWorld, I have never risen to decision-maker level. This zbs is overrated by 10 times.
• BestPractice implementation? What’s “best” is mostly a matter of taste (personal preference) of the manager
• zbs? Consider the most practical books like [[Pearls]] — the classics. If not relevant to IV then this zbs is only for self-satisfaction

### This is one reason why my reinforcement loop completely broke down in Singapore.

… In contrast, my NY years were filled with joys of self improvement, driven by … interviews.

# slippage: several related meanings

–definition 1

slippage = difference between 2 prices — the earlier quoted by an OTC dealer (FX, bond, swap…) vs the requote when you take that quote. In many quote-driven markets, all public quotes are always indicative.

–definition 2

slippage = difference between 2 prices — the EOD benchmark vwap vs your block order’s /implementation/realized/ vwap, assuming order filled within a day. If order is to be executed from 2pm to 4pm, then the benchmark vwap should be calculated accordingly.

As an execution benchmark, VWAP has remained the most common benchmark. TWAP is an alternative benchmark. There are two other related and simpler benchmarks — arrival Price and decision Price

• Decision price = the live price number (as a snapshot) that triggered decision to trade. Trading signal price. see http://en.wikipedia.org/wiki/Implementation_shortfall
• Arrival price = the live price number (as a snapshot) when order received by execution engine.

Nomura algo spec defines arrival price as the snapshot mid price between bid/ask at arrival time. So this arrival price is the benchmark, and the average execution price of your order should end up very close.

=== 3 execution algorithms to minimize 3 slippages

1. Implementation Shortfall — Minimize slippage relative to arrival price. Note decisionPrice is Not used by the implementation guys,
2. VWAP – Minimize slippage relative to the Volume-Weighted Average Price (VWAP) in the market
3. TWAP — Minimize slippage relative to the Time-Weighted Average Price (TWAP) in the market

# Matlab | clear all except breakpoint

tmp = dbstatus;

save('tmp.mat','tmp')

clear classes % clears even more than clear all

dbstop(tmp)

% clean up

clear tmp

delete('tmp.mat')

# your compiler ^ the c++ standard

C++ has many compilers offering extensions.

Many developers write code based on the c++ standard. You could decide “if this operation fails, I would get this particular error according to the standard.”

Well, unless you are aiming for portability, you had better respect your local compiler more than the language standard. Your local compiler could add a “feature” and avoid raising that error. Side effect – you don't get “reminded” and you assume everything worked as expected – dangerous. There could be a compile-time warning but then it's often drowned in the noise. Poor signal/noise ratio.

My stance — know your compiler. Whenever the standard says some unusual condition should end in a certain way (or one of several ways), check your compiler's conformance.

It's also possible that the standard says this condition should return a null pointer or silently return, but a compiler adds a much-needed diagnostic feature to catch it. Sounds too good, but then the problem is, if you tweak some debug-build settings (or when you port your code to another compiler) you could lose the “reminders” that you depend on. Your code may appear to work in UAT but fail in production.

# the "stream" concept in c++/c#/java

C had ascii/binary read/write functions. C++ introduced a family of “stream” classes as a complete replacement.

java and c# embraced and expanded the stream concepts and kissed goodby to the C legacy. I guess stream must be an immensely successful invention. Before we look at all the new stream classes like MemoryStream, GzipStream, StringStream… it’s good to understand the fundamental innovation. See http://www.cprogramming.com/tutorial/c++-iostreams.html.

I feel streams have become more versatile over the decades. Initially IO constructs for file and socket only. Then IPC. Then serialization. Then …

I particularly like the ostringstream — the “string builder” in c++.

Can we say the producer-consumer pattern is also stream-based? Probably not. Streams usually hold bytes or characters, not commands/tasks.

# VWAP: market impact = slippage @@

Suppose we have a 5000 IBM buy-order. VWAP is the benchmark chosen. Our goal is to predicted market impact. If the predicted MI is too large, then we should either be very careful, or decline the block order.

The predicted market impact is also the predicted slippage.

Let's put in some fake but concrete numbers. Suppose we estimate that submitting this block buy would raise today's eod_vwap by 100 bps. That means whatever today's eod_vwap happens to be, our execution_vwap will be higher by 1%.

If eod_vwap is \$70 then our market impact is about \$0.70

If eod_vwap is \$75 then our market impact is about \$0.75

I think we should inform our client that we can execute the block order at the benchmark eod_vwap + some spread. I would quote a spread like \$1 given spot is \$69 and I estimate today's eod_vwap to be \$69.50.

Suppose client accepts and we execute the order and execution_vwap = \$69.9. What's the realized market impact? We can only imagine “what if I had not done this big order”. However, we can observe the benchmark eod_vwap = \$69.10. We performed better than quoted. Slippage = execution_vwap – eod_vwap, so our slippage is smaller than our quote!

# 100-gunmen puzzle

Q: Suppose 100 gunmen stand in a big circle arranged by height, clockwise from #1 (lowest) to #100 (highest). In first shooting round, #1 starts off by shooting clockwise, so #2 gone. Then #3 shoots clockwise at #4, and so on.  How many rounds will there be and who will be the last standing?

Q2 (adapted from Q1): Before #1 gets shot or shoots again, first round ends, and the lowest among the remaining gunmen continues to shoot clockwise. In this case #1 will never die. No puzzle to solve.

Assume each gunmen stays in his spot, and his spot has his name.

Analysis –
Let me first clarify the terminology.
* Each round has a “starter” shooter. The round ends immediately before he shoots again or immediately before he gets shot.
* Each round has a InitialCount := number of gunmen at start of that round.

— my Solution —
Round 1: starter is #1. InitialCount=100. This is an even round, so the starter remains.
Round 2: starter is #1. InitialCount=50. This is an even round, so the starter remains.

End of Round 2 the remaining shooters are #1 #5 #9… #97. They are 4 (i.e. 2^2) stops apart.
Round 3: starter is #1. InitialCount = 25. This is an odd round, so starter will shift anticlockwise by 2^2 to #97. Why am I so sure? Since InitialCount is odd, the highest (among the 25) gunmen will NOT die and will become the next round’s starter.

End of Round 3 the remaining gunmen are 8 (i.e. 2^3) stops apart. Therefore, highest two are #89 #97.
Round 4: starter is #97. InitialCount = 13. This is an odd round, so starter will shift anticlockwise by 2^3 to #89.

End of Round 4, the starter (#97) is a “sitting duck” to be shot soon.
Round 5: starter is #89. InitialCount = 7. This is an odd round, so starter will shift anticlockwise by 2^4 to #73.

End of Round 5, #89 is a “sitting duck” to be shot soon.
Round 6: starter is #73. InitialCount = 4, which is a power of 2, so #73 will remain the starter for all subsequent rounds and therefore the last standing.

# For YuJia – trade at market close

My strategy assuems we could buy or sell at exactly the daily close price. There’s no bid/ask to worry about.

Although a stock market may close at 4:00 PM, many stocks continue to trade for at least 20 minutes after the close. We wait for the actual close price, and make our trading decision. There are risks to this practice.

* Trading volume typically plummets when the market closes. This causes market orders to become very risky. Therefore we use limit orders.

* Limit orders may not get filled, therefore we use total daily volume to throttle our trade size.

# For YuJia – pair trading details

Given the thin profit margin, the strategy needs to trade large volumes. However, there are 2 upper limits on the trade size. The engine computes both limits and adopt the lower.

1) First limit is market impact. The trading engine has a parameter known as participation rate. It’s set to a value below 1%. If on a thin day ES total daily volume is, say, 4320 contracts, then the engine won’t trade more than 1% of that, otherwise the ensuing market impact would be too large — we risk getting filled at a worse price than planned.

Using the participation rate, the strategy determines how many futures contracts to sell. If that quantity turns out to be 0 then the engine won’t enter the market.

2) The other upper limit is post-trade market risk.

Prior to market entry, if our cash balance is worth, say, 44 futures contracts, then the strategy would trade up to 10x. If we ignore this limit and recklessly trade a gigantic quantity (like 700 x 44 contracts), then over the holding period a ES price surge, magnified by our large position, could wipe out the entire portfolio i.e. unrealized loss exceeding the cash balance. (Note even though our equal-dollar ETF position should in theory hedge our futures position and insulate us from broad market move, the two prices could go out of sync by a significant margin for a short period.)

(In fact, when we ignore this limit, our StopLoss would get hit.)

There’s no separate limit for the ETF trade size. The ETF trade size is always equal to the futures trade size in dollars. For example, if I short 5 futures contracts worth \$900 x 5, then I would long 50 ETF shares worth \$90 x 50. (Note the ETF unit price is 10% of the Futures contract.)

Using equal dollar value on both the long and short legs provides a nearly perfect hedge against broad market movement. When the overall market moves down (or up), one leg loses \$x and the other leg gains \$y which is very close to \$x. However, as stated earlier, “very close to” doesn’t mean \$x = \$y, and the difference (x-y) would be magnified by our position size. It could be a very large unrealized loss and could force close the entire account.

— leverage and borrowing cost —
Graph above shows the interest paid on each trade. We only borrow money when we enter the market and immediate stop the borrowing when we exit the market. We basically roll the loan over night. If we hold a position for 9 days, we would pay 9 day’s of interest, no more no less.

The daily interest rate is based on the US Fed Fund rate. We don’t assume to be a top-rated bank, so we pay a 100 bps premium over the FF rate.

Without borrowing, futures contract margin requirement is hard. We start with only \$1000 and need to leverage 5 times by borrowing \$4000. In a sense, borrowing is needed in the early phase when our initial capital is small.  It’s possible to make do without the loan when our realized profits boost our cash position to beyond \$100,000. However, we actually implemented an yearly reset whereby all realized profits are taken out of the trading account, so at start of each year capital is reset to \$1000. We always need to borrow \$4000.

— dividend collection —
Graph above shows the dividends collected over the years.

The ETF actually generates quarterly dividends. It can be profitable to trade for dividend capture, but it requires market timing and luck. In our strategy, we collect dividend by chance not by design. Benefit is lower risk and extra return, depending how we look at it.

If on a dividend date, we happen to hold the ETF, we would recieve the dividend as a ‘bonus’, which boosts our investment return. Nevertheless we don’t rely on such bonus dividends to enter/exit the market. In other words, the strategy is designed to be robust even with zero dividend each time. A strategy that relies on dividend capture is sensitive and could potentially be hit by unexpected low dividend or adverse price movement, which is a potential risk factor. Our strategy sidesteps those tricky questions because we treat any dividend received as a bonus.

Given the thin margin in our strategy, the bonus dividend income is small but helpful.

— exchange fee (including commission) —
Graph above shows the fees incurred over the years. Given the thin margin in our strategy and the relatively large trade size, exchange fee is rather significant. When commission rate doubles, the profit drops by at least a third.

Higher fees also lead to more stop-loss triggers. Each trigger leads to a major realized loss.

It’s not easy to find exact commission rate. I assume the 2 instruments are very liquid and high-volume, so commission should be lower.

# variable assignment in python, c#, c++ #key difference

Java has the cleanest design —
V) java _primitive_ type assignment is like Spreadsheet cell editing in-place. Saves new value into memory cell directly. Not following-the-pointer. (no pointer at all)
R) java _reference_ type assignment re-seats/rebinds a pointer with reference-counting — one increment + one decrement

Python assignment is always(?) R ? . I have not seen a “primitive” or “nonref” variable in python.

C# value type assignment is always V, even if the object is a big struct — eg 64 [[c#precisely]]

C++ is similar to java —
– Nonref assignment follows V, though classes often customize assignment operator.
– Pointer assignment follows R.
– However, For a reference type variable, initialization is R, but subsequent assignment is V, since a reference never rebinds.

To view the hidden scheduler log, use DOS to list the files in c:windowstasks folder. Or use notepad++ on c:WINDOWSTasksSchedLgU.Txt

To increase the log size limit, follow http://support.microsoft.com/kb/169443

This will block subsequent reruns.

Fix: try the max run time (default 72 hours)

Some reasons for a forever-running task

* vbs may need to use wscript.quit

# win service ^ once-a-minute scheduled task

If an operation is likely to hit various failures, then a service is troublesome as it would need restarts.

Under a service, the operation should take a few seconds only.

Service can have higher frequency than once a minute.

Service can run under LocalSystem without any password.