Showing posts with label Execution. Show all posts
Showing posts with label Execution. Show all posts

Wednesday, 15 April 2026

Annual performance update- year 12

 This is how I started last years update: "Mad out there isn't it? Tarrifs on/off/on/partially off/on... USD/SP500/Gold/US10/Bitcoin all yoyoing like crazy."

Well the orange peril is still at it, and as I write this the global supply of oil has been severly curtailed for several weeks now; with a certain amount of reaction in oil futures (which some of it perhaps supressed since apparently "cash on the nail" prices for physical oil are much higher in some delivery ports), but net-net almost none in US stocks. 

As always I do these updates on the basis of the UK tax year, 6th April to 5th April; and as I did last year I'm going to focus almost entirely on my futures trading.


Overall figures 

My total portfolio performance was 6.4%. Almost all of that is down to futures; without it I would have earned just 0.2%. This is not surprise since my long only portfolio has been very low risk, consisting almost entirely of short term bond futures, after I went 100% cash during the taper tantrum (yes, bad move in retrospect, and another failure of discretionary trading on my part). I did start to selectively buy back into equities in the last month or so. Whilst 6.4% is better than nothing, and better than last year, it pales when compared to my Vanguard 80:20 benchmark which was up 23.7% during the tax year. My plan is to refill my equities portfolio over the next couple of years, hopefully using the short term panics which are helpfully generated by the White House every few weeks.

Everything else in this post just relates to futures.


Futures: Headline numbers

Last year in brackets

MTM:        21.9%   (-17.8%)

Interest:    2.7%   (2.4%)

Fees:       -0.04%  (-0.05%)

Commissions:-0.33%  (-0.29%)

Slippage:   -0.55%  (-0.56%)

Net :       23.7%   (-16.3%)


Well first let's note that it is a positive number, and it's also my best performance since 2022 (when another significant conflict started, and I made 27%). Curiosly this is identical to the 80:20 benchmark, at least to one decimal place, but of course that is a silly comparision and a better benchmark is coming later. 

'Interest' includes dividends on 'cash like' short bond ETFs I hold to make a slightly more efficient use of my cash. MTM - mark to market - also includes gains or losses on FX positions held to meet margin, and on the cash like ETFs. MTM breakdown:

Pure futures:    21.7%

Cash like ETFs:  -0.77%

FX:               1.1%


As I did last year then, let's lump together all the interest, FX and ETF MTM and interest, and call those 'cost/benefit of margin':


Futures MTM: 21.7%   (-14.5%)

Fees:        -0.04%  (-0.05%)

Commissions: -0.33%  (-0.29%)

Slippage:    -0.55%  (-0.56%)


SUBTOTAL - PURE FUTURES: 20.7% (-15.3%)

Cost of margin: 2.9% (-1.0%)

Net :       23.7%  (-16.3%)


Time series


You can see that about half the profits were made quite slowly from June to November; and then the other half made very quickly in December and January (we will return to that later). After that things got quite volatile with the whole war thing happening, and risk is currently quite low.

And for the longer term you can see we are pretty much at the HWM set in April 2024, although I never quite got there:


(Note as for all my plots these are non compounded account curves)


Benchmarks


My two traditional benchmarks are the SG CTA index, and an AHL fund which like me is denominated in GBP. A big thanks to Neils from TTU for sharing his SG data as my previous free source stopped working (SG if you are reading this, come on guys, please share!).

First meaningless raw performance:





                AHL       SG           ROB

Mean       5.6%      4.9%         13.8%

Stdev     10.7%      9.0%         17.3%

SR (rf=0)  0.52      0.54          0.80        


Those Sharpes would be lower, especially in the last couple of years, if a risk free rate was deducted.

My correlation is 0.68 with SG CTA, and 0.56 with AHL. Their joint correlation is 0.79.

Now for vol adjusted:





          AHL   SG     Me

30/03/15 68.4% 51.2% 59.5%

30/03/16 -6.4% -3.7% 28.1%

30/03/17 -3.8% -12.6% 2.4%

30/03/18 9.0% -1.7% 2.0%

30/03/19 5.4% -2.7% 4.5%

30/03/20 22.6% 6.5% 33.8%

30/03/21 0.9% 11.9% -1.7%

30/03/22 -12.4% 33.1% 25.8%

30/03/23 8.3% 0.6% -7.6%

30/03/24 14.9% 24.3% 20.6%

30/04/25 -18.7% -18.0% -15.4%

30/04/26 30.3%  29.9%   25.9%


Note: The reason I'm showing 25.9% here and 23.7% earlier, is that these figures are to the end of the relevant month (i.e. March 31st to March 31st), rather than the UK tax year; as I can only get monthly figures for the AHL fund. I've highlighted in green the best performer in each year, red is the worst. 

I've highlighted in green the best performer in each year, red is the worst. A great performance from AHL; their fund was up 18.1% before vol adjustment and as they run at significantly less vol than me this was fantastic. SG CTA also did very well, with raw performance of 15.3%. As a result I was actually the worse of the three for this year at least. 

The CAGR based on monthly vol adjusted figures are 7.7% (AHL), 8.2% (SG) and 13.0% for me.


Market by market



Here is the asset class story:

==================
P&L by asset class
==================

    codes  pandl
    Bond  -2.84
     Vol   0.00
  Sector   0.39
  OilGas   2.21
      FX   2.24
     Ags   3.89
  Metals   5.49
  Equity   5.49
Market wise, the rogues gallery were CAD10 year bonds, plus a few equity markets (SPI200, DOW, DAX) and the US dollar index. I lost between 1% and 1.2% in each of those. The markets where I made more than 1% are quire varied:
          TOPIX    1.0
           PLAT    1.0
            AEX    1.0
        BITCOIN    1.1
            JPY    1.2
       MSCIEAFA    1.7
         YENEUR    2.0
     BRENT-LAST    2.3
            MIB    2.7
     MSCITAIWAN    3.6
        FEEDCOW    4.0
         SILVER    4.2

Silver in particular was quite famous earlier in the year and shows a classic TF curve (price, position, p&l):

Rather overlooked by the legacy media; Feeder Cattle was one of the nicest runs:



Trading rules


Last year almost none of my trading rules made money, all of which contributed to my worst ever year trading futures with my first double digit loss. 









Overall then a much nicer picture for the divergent rules, with convergent less nice except for skew. The best performing model this year at least was the most traditional, the 'momentum' model which is a bunch of moving average crossovers. This probably explains my relative underperformance this year. Also worth nothing that the slowest trend models did the best in almost all categories.



Costs and slippage


My total slippage (diff between mid market price when I come to place an order, and where I get filled) was 0.55% of my starting capital; and commissions were 0.33%. That's an all in cost of 0.88%, very much in line with last year and previous years. Since I switched to dynamic optimisation, my costs have been extremely consistent.

Without my execution algo, if I had just traded at the market, I would have paid 1.34% in slippage; my simple algo earned 78bp and cut my slippage bill by around 40%. 


Coming up


As I noted above I plan to rebuild my long only portfolio out of the smoking ruins of my cash pile over the next couple of years. I also have some interesting things planned in the research and production space this year; you can find more details here.



Tuesday, 4 March 2025

Very.... slow... mean reversion .... and some thoughts on trading at different speeds

 Bit of a mixed bag post today. The golden thread connecting them is the idea that markets trend and mean revert at different frequencies.

- A review of the discussion around timeframes for momentum and mean reversion in 'Advanced Futures Trading Strategies', in light of this excellent recent paper (which I also discussed on the TTU podcast, here from 1:02:12 onwards).

- A mea culpa on the mean reversion strategies in 'Advanced Futures Trading Strategies'. TLDR - there is an error in the backtest and they don't work at least in the specified form.

- A new slow.... absolute mean reversion strategy inspired by a question from Paul Calluzzo on the aforementioned podcast episode.

Note: in this article I use the terms momentum and trend following interchangeably to both mean absolute momentum - not relative.


When do markets trend and mean revert?

When do markets trend? When do they not trend... perhaps even mean reverting? This is a very important question! 

You might think it would depend on the market, but actually there seem to be some fairly common patterns across many different instruments. Here is how I summarised by thoughts in my most recent book, Advanced Futures Trading Strategies (AFTS):

Multi-year horizons: Mean reversion sort of works (although the results are not statistically significant, as the value strategy in part three attests). Note: this value strategy is a relative value strategy that looks for mean reversion within asset classes. Such strategies are common in academic equity research.

Several months to one year horizon: Trend following works, but is not at it’s best (consider the slightly poorer results we get for EWMAC64 versus faster trend variations).

Several weeks to several month horizon: Trend works extremely well (consider the excellent performance of EWMAC8, EWMAC16 and EWMAC32).

Several days to one week: Trend is starting to work less well (EWMAC4 and especially EWMAC2 perform somewhat worse than slower variations, even before costs are deducted).

A few days: We might expect mean reversion to work?

Less than a day: We might expect trend to work?

Less than a second: Mean reversion works well (high frequency trading - HFT - is very profitable).      

Note that 'momentum works for months or years' and 'mean reversion / value works for years' is a very well known stylised fact which has been established in the literature for many decades; see for example this seminal paper. And given the existence of profitable CTAs with holding periods in the weekly to monthly range, it's hardly surprising that momentum works for shorter holding periods. Nor is the fact that HFT firms make a ton of money a secret.

However, in the region between high frequency trading and a horizon of a week or so I wasn't sure exactly what to expect, but I speculated that there would be a region where mean reversion would start to work (more on that later!), and I also thought trend following with holding periods in the 'few hours' range (mainly because there has been some sell side research on that). Note that since my own data is hourly at best, I couldn't really test anything with a horizon of less than about one day.

Fortunately someone came along to fill in this gap in our understanding, with this excellent paper:

"Trends and Reversion in Financial Markets on Time Scales from Minutes to Decades" by Sara A. Safari and Christof Schmidhuber

I won't summarise the paper in much detail (for example it has some interesting results around the relationship between trend strength and reversal), but they have the following pattern of results (from figure 10 in the paper):


Horizon over two years: Mean reversion works, becoming more effective at longer horizons. They used literally centuries of data to check this result. 

One week to two year horizon: Trend following works, but it's effectiveness peaks at around one year

One hour to one week horizon: Trend following works, getting gradually less effective as the time horizon shortens.

Two minute to 30 minute horizon: Mean reversion works, and is most effective at the 4-8 minute horizon


The key differences between my results and theirs only occur in my 'zone of speculation', where I was only guessing and they had actual evidence so let's go with them :-) In particular they have two 'crossing points' from when mean reversion stops working and momentum starts working (at just over two years, and somewhere between 30 minutes and one hour), giving the following broad ranges:

Horizon over two years: Mean reversion works.

One hour to two year horizon: Trend following works.

Two minute to 30 minute horizon: Mean reversion works

Whilst I had speculated that there was something more complicated going on. Even without evidence, Occams razor would suggest you should prefer their results to mine.

Another difference is that when I looked 'optimal points' for eg momentum I was concerned with Sharpe Ratio, but they are instead fitting a response function and seeing when it has the best statistical fitness. Because of the Law Of Active Management, Sharpe Ratio (loosely) scales inversely with the square root of time for a given level of prediction accuracy. So you if you are equally good at predicting one year trends, and 3 month trends, the latter will have twice the Sharpe Ratio of the former. Hence there are good reasons why my optimal SR point is different from their optimal response point; all other things being equal the optimal SR is going to be at a shorter horizon.

Combining the two pieces of research together, and thinking about what sorts of strategies we could be trading, we get this:

Horizon over two years: Mean reversion works. The optimal SR is probably quite flat for anything between three and ten years. Equity value, relative value within asset classes, and absolute mean reversion (of which more in a moment) are all nice strategies. But given their holding period you shouldn't expect high Sharpe Ratios unless you are Warren Buffett (hi Warren!). 

One to two years: Momentum will work but will be getting steadily worse as the timescale gets longer, both from a predictability perspective and a Sharpe Ratio viewpoint. Avoid.

Three months to one year horizon: Trend following works with high predictability, but is not at it’s highest Sharpe ratio due to the slow turnover. However, the advantage here is that this is a playing field that even retail punters with expensive trading costs can play in. Slower momentum strategies are all good.

Three weeks to three months horizon: Trend following probably has it's optimal Sharpe Ratio somewhere in this region, depending on the asset class. Any medium speed momentum strategies are good, and nearly all futures traders can play in this area if they avoid a few very expensive instruments.

Several days to three weeks: Trend is starting to work less well (because the improvement from trading faster is being overwhelmed by the deficit in response) and trading costs will start to bite except for the very cheapest futures (see calculation below), traded with exemplary execution. On the upside, trend following models at this speed will have the highest positive skew. Trade selectively.

A few hours to several days: Trend still just about works but but there are probably only a small number of futures where  you can overcome the bid/offer costs (although I hear costs are very low in Crypto, and there might be US traders who get zero commission able to trade highly liquid ETFs like SPY); I'd doubt though it would be worth doing. As the authors note, strong trends also tend to reverse strongly in this region (see AFTS for my own confirmation of this effect). Against that there have been the sell side papers on this subject, but they seem to rely on gamma hedging effects which may not persist. Avoid.

1 hour to a few hours: The authors in the paper note that the very weak trend effect here can't overcome the tick size effect. Avoid.

Two minute to 30 minute horizon: Mean reversion works, and is most effective at the 4-8 minute horizon from a predictive perspective; although from a Sharpe Ratio angle it's likely the benefits of speeding up to a two minute trade window would overcome the slight loss in predictability. There is no possibility that you would be able to overcome trading costs unless you were passively filled, with all that implies (see below). Automating trading strategies at this latency - as you would inevitably want to do - requires some careful handling (although I guess consistently profitable manual scalpers do exist that aren't just roleplaying instagram content creators, I've never met one). Fast mean reversion is also of course a negatively skewed strategy so you will need deep pockets to cope with sharp drawdowns. Trade mean reversion but proceed with great care.

Less than a second to two minutes: Not covered in the paper, but I would speculate that mean reversion continues to work, and the pre-cost Sharpe Ratio would also continue to improve as the horizon falls. Proceed with even more care.

Less than a second: High frequency trading works, and clearly has a very high Sharpe Ratio, but this is not for the amateur.


Notes on costs: 

The very cheapest equity index future I trade has a cost of around 0.2bp assuming we execute market orders; and vol of around 20% a year, for a SR cost of  about 1bp. Median single instrument SR on the optimal trend strategy (holding period around 3 weeks) is around 0.30. Predictability, as a regression coefficient, from the linked paper is around 6.5% at 3 weeks; and around 1.8% at 2 days (a reduction of 3.6x). Time scaling would improve the SR by 2.7x so the net effect is a 25% fall in SR to around 0.22 for a two day forecast horizon. 

If we take a third of that (my 'speed limit') or 0.22 SR for costs, then our annual cost budget is 0.07 SR or 700bp; implying we could perhaps safely trade a couple of times a day implying a two day forecast horizon (which means trading once a day) is possible. 

But the median future I get data for has a cost of around twenty times that, meaning a holding period of around two weeks is required to meet the 'speed limit'.

Do we have to pay the spread? Broadly speaking, if you are trading slowly, then you can afford to be more patient in your execution, using passive fills where possible (as I do myself). But as a fast trend follower who thinks the price is going to move away from you in the near future, it's probably harder to sit on your hands and wait. 

Alternatively if we are fast mean reverting traders then we can use passive fills by setting limits around where we think the equilibrium is. That of course runs the risk of adverse selection, but without doing this we are never going to make enough money to overcome the bid/offer if we're trading dozens of times a day. You may also be still liable to commissions unless you received exchange rebates from providing liquidity. Note since we earn the bid/offer spread from passive fills, it might be that the best instruments for this strategy are those with wider rather than narrower bid/offers.



Forgive my father, for I have sinned against the gods of backtesting...

Now in AFTS I introduce two strategies which trade mean reversion, with horizons of around a week (since I'd speculated that would work). It included a very elegant way of including limit orders to passively execute, and the second strategy introduced a very nice trend following overlay. And it looked great! But that obviously isn't consistent with the findings above.

Well gentle reader, I screwed up. As I said in my book:

"But what jumps out from this table is the Sharpe ratio. It is impressively large, and the first we have seen in this book that is over two. In my career as a quantitative trader I have always had a long standing policy: I do not trust a back tested Sharpe ratio over two. There are certainly plenty of reasons not to trust this one. 

Firstly, the historical back test period, just over ten years, is shorter than I would like. There are good reasons to suppose that the last ten years included unusual market conditions that might just have favored this strategy. Secondly, it is hard to back test a strategy deploying limit orders that effectively trades continuously using hourly data. There may well be assumptions or errors in my code that make the results look better than they really would have been."

The underlined section (not underlined in the book!) is key here; basically there was an implicit forward fill in my backtest as I calculated the equilibrium price including todays closing price (which of course I wouldn't have known in the morning). The real backtest shows basically no statistically significant return at all.

The good news is that the basic technology of this strategy should work well, at least pre-costs, with a much shorter time horizon; although for all the reasons above I haven't tried it myself (though I know others that have).




A new slow absolute mean reversion strategy

Since I'm taking away one strategy, let me replace it with another. In AFTS strategy twenty two is a 'value' strategy, which bets on mean reversion over five year periods in relative terms against an asset class index. It has crappy SR (basically zero), but positive alpha and improved overall SR when added to trend and carry strategies. 

But on a recent TTU podcast, here, Paul Calluzzo asked me if I'd ever tested absolute mean reversion. Certainly I haven't on this blog. So let's do that.

I'll use a three year return for my forecast, which is slow enough to avoid the two year point where we know momentum probably still works; whilst being quick enough to avoid the death by sqrt(T) that will reduce my SR. We go long if the return is negative so:

Forecast = Price_t-3yrs - Price_t

To avoid the turnover being excessive (this is a slow forecast!), and because we should always vol scale:

Smoothed vol scaled Forecast = EWM_64(Forecast/ EW_std_dev(returns))

Drumroll...

It's not..... great (SR -0.48), apart from perhaps a recent pickup. You could argue that as a lot of my data starts in 2013, and the first five year return occurs in 2018, that it's actually profitable for many instruments and we've just been unlucky in the instruments we've traded before. The median SR is -0.06 though which doesn't completely support that argument. 

But really it would appear that at least with this construction absolute mean reversion isn't as good as the relative mean reversion I tested in AFTS.

OK so we've dropped a strategy with an unfeasibly high backtested SR, and I've replaced it with one that has a very poor backtested SR. Unfair? Well, life isn't fair.


Summary

Good things to trade:

Horizon over two years:  Cross sectional mean reversion, but possibly not absolute mean reversion. And similar type things like equity relative value.

One to two years: Nothing*

Three months to one year horizon: Trend following of pretty much anything

Three weeks to three months horizon: Trend following; avoiding very expensive instruments.

Several days to three weeks: Trend following; only the very cheapest instruments.

One hour to several days: Nothing*

Less than a 30 minute horizon: Mean reversion - the faster the better, but only with limit orders and with great care (the faster you are, the more care needs to be taken).

* or at least not outright momentum or mean reversion

Thursday, 7 April 2016

Futures trading performance - year two

Well time flies. It's a year since I wrote this post:

http://qoppac.blogspot.co.uk/2015/04/futures-trading-performance-year-one.html

... which means it's time I reviewed my second year of systematic futures trading.

Executive summary: Last year was amazing, this year was just excellent.


The money shot




Or to put it in the context of the full period:

So basically a 40% increase, on top of the 57% last year (I don't compound my returns). Unlike last year I didn't change my risk weighting.

As I've stated before the p&l in my account comes from two main sources; a hedged stock portfolio (you can think of this as a long:short equity hedge fund), and some futures trading.

Here's the full breakdown

Stocks
Mark to market: -5.06%
Dividends 4.63%
Commissions: -0.02%

Subtotal: -0.45%

Hedge
Mark to market: 16.79%
Commissions: -0.03%

Subtotal: 16.73%

Total for stocks and hedge: 16.31%

Futures
Gross profit: 21.48%
Commissions: -0.76%
Slippage: -0.63% (Bid ask -1.2%, less execution algo profit 0.56%)
Data fees: -0.03%
FX trading: 3.22%
Interest: -0.04%

Total for futures: 23.24%

Grand total: 39.55%

The hedged equity portfolio made a lot more money than last year. It's important to bear this in mind when comparing against pure futures managers as I will do later on in the post.

My futures trading was still very good (a SR of just over 1.0; better than expected in the back test at around 0.88) though not as amazing as last years 57%.

Slippage was about half the level of the prior year; probably because my execution algo was doing a wonderful job for the whole year rather than just part of the year as before. I'll be analysing my execution costs in more detail in another post.

Total trading costs then come in at 1.39% versus a backtested 1.5%. Once again slippage was lower than expected (1.0% in backtest versus 0.63% this year) and commissions were higher (0.5% in backtest versus 0.76%).

The back test doesn't include futures rolls; I can't be precise but eyeballing the data they account for around a third of commissions and a similar chunk of bid-ask so in reality I'm probably doing okay. This will be something I'll be implementing in my new system, pysystemtrade.


Fun facts and figures


Realised standard deviation (based on weekly returns) 24.6% versus target 25%
41.4% of trades were winners
Avg profit:avg loss ratio: 1.841
Best day +7.6%
Worst day -5.4%
Worst drawdown -18%


Benchmarking


As I noted above it's probably unfair to compare my performance to a pure futures CTA like AHL, but for consistency I did it anyway. As with last year I used the AHL diversity GBP class as my benchmark. The correlation of monthly returns for the last 12 months was 0.80, a little lower than before, but still relatively high.

Because AHL runs at a lower vol than me to graph our returns I first need to adjust AHL's for this effect. This gives me the following cumulated returns for the two year period:


The Sharpe ratios for the last 12 months were 1.33 (me), -0.59 (AHL). If I take out the additional performance of equity neutral then my Sharpe is around 1.0. So just on pure futures trading I've still done much better this year. It isn't just AHL eithier. Of the big European CTA names only Aspect (+8%) and ISAM (+15%) made anything like a SR of 1.0 (Winton was up slightly).

I'd guess this is probably due to having more carry in my system (I underperformed in the first year, when pure trend following kicked butt). It could also be a lower allocation to under performing asset classes like equities (of which more in a second).

For the whole period the Sharpes are 1.65 (me) and 1.38 (AHL) respectively. Again without the equity neutral component we'd have very similar performance over the two years.

There is a longer discussion of the "big versus small" argument here.


Performance by instrument


 Last year was the year of the bond. This year, with twisting and turning in the Fed's policy causing ructions and sharp reversals in financial assets, has been the year of non financial assets.

Metals 13.4%
Oil and gas 12.5%
STIR 4.5%
Bonds 2.2%
Vol 0.1%
FX -0.1%
Ags -1.3%
Equities (ex hedge) -5.8%

The trend in all the precious metals (Gold, Platinum and Palladium) was strong, with Copper helping as well.

Let's look at Gold since most people know the chart:

Not a single one off trend; rather two down trends and one up trend on which serious profit was made; interspersed with gradual leakage. Gold actually ended up the year unchanged (with rolldown included), yet we made money. Lovely.

Crude was a winner last year, but Gas actually contributed more this year:

A more straightforward strategy here; short, short and keep on shorting...

Although bonds didn't do very much, Eurodollar's (now the only market in the STIR asset class) were a stand out:

Despite Ms Yellen's best efforts the overall direction was up; and this basically translated into profits (though I was a little flatter in the trend less periods as you'd expect).

One of the worst markets was CAC; very typical of stock markets generally:

What an ugly chart. Most of the time there wasn't a trend strong enough to justify a position; then when one was put on it was immediately whipsawed out, resulting in gradual bleeding.

However cable IMM futures were the worst market of all

Almost a year of perfectly awful rangebound behaviour; with one decent trend saving my bacon a little.


Fin


As I have noted before, and will note again, and again, and again; even a few years worth of live trading performance may not tell you with much statistical significance whether you are good or just lucky (or both). I've definitely been lucky with my equity neutral strategy this year; whilst my futures trading is in line with expectations.

At best I can say it's becoming less likely that I'm doing something stupid and have just been lucky. So if markets continue to behave as they have for hundreds of years, then I should continue to make a little money.

If you're interested in building your own systematic trading engine, then have a look at my other blog posts on the subject, or of course you can also buy my book.

Friday, 29 January 2016

Computers vs Humans - considering the median


Or why you aren't, and will never be, John Paulson


The systematic versus discretionary trading argument is alive and well; or if you prefer, computers versus humans*. In this post I pose the question - who is better the average systematic trader, or the average discretionary human?

* Though even fully discretionary traders will be relying on a computer at some point; fully manual trading and back office settlement systems not available in modern market.

My new hedge fund will completely eschew computers... and casual dress (source: http://www.officemuseum.com)


I've thought, and spoken, about this quite a lot. Upfront I should say that there is no simple answer to this question. There are some extraordinary human traders; celebrities like Soros and Paulson. At the same time there are some incredibly successful systematic funds: high frequency firms like IMC and Virtu; also the likes of Renaissance and DE Shaw; and of course the systematic CTA business that I cut my teeth in of which Winton and AHL are just two examples.

But reciting this diverse group of household names is of no real help. It's the median that fascinates me.

Firstly as an individual trader reading this and trying to decide which route to go down, it's unlikely you are the next Soros or Paulson; or for that matter someone with the resources of Jim Simons. As a journalist, you don't know if this group is really representative of all the systematic and non systematic traders and fund managers that are out there. As an asset allocator you may struggle to identify the stars of the future (who may not be the stars of the past); you'll have to allocate to at least some ex-post average managers.

To put in geeky terms if we're trying to work out if the mean or median of a distribution is larger than another, just looking at the outliers isn't going to help and may even be misleading.

We need to think a little more deeply.


What are computers good at?

Source: cartoonstock.com

  •  speed. Duh.
  •  sticking to a plan, and not being freaked out by losses or annoying clients
  •  repeatability - doing the same thing given the same inputs
  •  getting their position scaling correct
  •  managing large portfolios
  •  not being hit by the proverbial bus, or leaving the firm
  • teaching other computers how to do exactly what they do

Researchers using computers can also be good at:
  •  identifying persistent patterns
  •  identifying unusual, non intuitive, patterns 


What are humans good at?



It might be more accurate to say "What are humans who are good at trading good at". Not everyone can do these things.
  • "deep dive" analysis on a small number of assets
  •  processing complex, novel, information
  •  interpreting non quantifiable information
  • adapting to novel, changing, environments
  •  genuine forecasting (rather than extrapolating the past, or assuming it will repeat)
On the last point, it's worth elucidating. We could never write a computer system that would put a CDS short on in 2006, based on the sort of fundamental analysis that Paulson and the rest of the cast of "Big Short" did*. Asset bubbles, backed by novel securitisation techniques, do not happen every month.

* I suppose it's plausible that you'd put on a credit short based on a simple technical model which assumed that CDS prices mean revert from extremes. Nevertheless there would probably be insufficient data to fit such a model, given the relatively short history of CDS as an asset.


If Paulson had been in the Big Short film, Kevin Spacey would have played him. (source digitaltrends.com) (....and why wasn't he? Answers on a postcard, or via twitter)


Which trading arenas are computers likely to be good at?


  •  High Frequency Trading (Duh, again)
  •  Scalping (sure humans can do this, but you'd die of boredom, wouldn't you?)
  •  Systematic technical analysis (persistent patterns)
  •  Equity neutral - where the portfolio is too large for humans but requires only quantifiable factors
  •  Stat arb (finding the weird non intuitive relationships)
  •  Passive index tracking, and 'smart' beta
  •  "Vanilla" arbitrage or near arbitrage eg index vs constituents, on the run vs off the run treasuries
  •  any other strategy that boils down to smart or alternative beta, where a simple set of rules does the trick



Which trading arenas are humans likely to be better at?


  •  Fundamental economic analysis, eg global macro type bets (Soros and Paulson again)
  •  Subjective technical analysis (which, frankly, I am personally very skeptical of)
  •  Weird, one-off, pure or near pure arbitrage trades (eg cash-CDS in 2009, French Gold linked bond in Bonfire of the vanities...)
  •  Special situations / event driven, eg merger arbitrage
  •  Activist investing (computers can't harass the board into doing what you want)
  •  'Deep dive' stock analysis, on the long or short side, where you go right into the nitty gritty of the business
  •  Anything where every trade is different and or relies on analysing a lot of non quantifiable information 
  • Illiquid, and "real" assets, or anything for which data is sparse, unreliable  unavailable


Note that the human edge in the later arena will be reduced or depleted if they don't have the discipline and the knowledge to set up their position sizing and management correctly and stick to it. Imagine if Paulson had put on too large a position in 2005*; and then had to close it in late 2006 due to investor pressure (which was starting to heat up). All his analysis would have been for naught.

* Yes I know he pretty much couldn't have put on a bigger position, and had to scratch around for ways to increase it by doing stuff like this, but please don't spoil my example with the facts.


Average Computer versus Average Human


So, I think we have a small number of instances where humans can't compete with computers:

  •  High Frequency Trading
  •  Scalping
  •  Equity neutral
  •  Stat arb
We then have some situations where humans could compete, but it would be pointless and labour intensive:

  •  Systematic technical analysis
  •  Passive index tracking, and 'smart' beta
  •  "Vanilla" arbitrage or near arbitrage (not high frequency)
  •  Alternative beta

Then there's a group of strategies that computers will really struggle with:
  •  Fundamental economic analysis
  •  One-off, pure or near pure arbitrage trades
  •  Special situations / event driven / activist investing
  •  'Deep dive' stock analysis
  • Illiquid, and "real" assets


We can split the investing and trading population into four groups depending on whether they have the skills to do the kind of 'human only' strategies in the last group, plus the discipline to implement and stick to the correct risk and position management.

  • Super Traders with both the skills and the discipline
  • Committed and useless; with the discipline but not the skill
  • Clever and Chaotic, skills but no discipline
  • Useless and Chaotic, no skills or discipline.
 In the interests of full disclosure I probably fall into either the second or fourth category; with very occasional visits to the third category.

Clearly only those in the first category should contemplate discretionary trading. The rest of us should trade using a system.

Let's assume that a quarter of the investing population are in each category; even though this is a gross exaggeration*. We'll also assume that, generally speaking, people don't realise which category they are in.

* In fact I would say the proportions are more like 0.01%, 10%, 10% and 79.99%

Firstly, in terms of deciding whether to trade with a system or not, you only have a 25% chance of being in the first group for which discretionary trading is the way to go. This isn't great odds. Unless you're an idiot, a gambler, or incredibly over confident you should trade systematically.

Secondly, to answer the original question, we know that the world is split between people managing money with computers, and people not doing so. From the above analysis only 25% of those in the discretionary group should be doing it. They'll be making great returns, especially if they focus on the stuff computers can't do.

The rest will be making a terrible job of it, either because they lack the skill or the discipline. The median will sit in the middle of this group. The mean will be a little higher.

For those that are a bit slow, yes, that's why I chose the median right at the start of this post!

Meanwhile in the computer group there will be much less dispersion; a much narrower distribution. It's true that in many fields of investing and trading the very best computers will be not quite as good as the very best humans.

But the average (both mean and median) of this group will be lower than the top 25% of the human group, but higher than the overall human average.

I would argue that this simple model is pretty close to the truth, especially if you pull in all the amateur traders, many of whom are making a pretty terrible fist of discretionary trading, and fall mainly into the "useless/chaotic" bracket. In the professionalised segment of the business things may be slightly better; as even discretionary managers will be using some systematic rules (which I discuss more below).


The best of both worlds?


source: Dilbert.com


Is there some way we can get the best of both worlds? After all pilots of planes manage it. Autopilot does the boring stuff, but in an emergency humans are able to interpret the situation and act on it much better. I can think of two main routes:


Mechanical system - human override and scaling


Quite a few so called systematic managers seem to operate on the basis of "Yeah, we have all these systems, but we decide when to turn them on and off depending on our judgement". Even firmly committed managers do, occasionally tinker (meddle, risk manage, refit or improve - pick your verb).

Is there a back testable systematic way of switching models on and off that works? If so (and I doubt it) then you're firmly back in the systematic camp.

If not... well it strikes me as just plain stupid that people who know they can't predict market movements think they can predict trading system performance in the same markets.


Discretionary calls - human


This is a much nicer idea. Use your human judgement to decide that Apple is a good bet. Then use a system to decide how much of Apple you should buy, how you should adjust the position as market conditions change, and when you should close. Stick to the system, even when it hurts.

I liked this so much I even put it into my book, where it appears as the the "Semi Automatic Trader" character.

It's also tailor made for the clever and chaotic. Sadly for the committed / useless and useless / chaotic there is nothing that can be done. Use a system, please, for your own sake.


Conclusion


Most humans should trade with systems. Some,who have the skill but not the discipline, can use discretionary trading combined inside a systematic framework. The average human will not be as good as the average computer. Unless you know, for sure, that you'll be well above average as a human trader you should get out your keyboard and start coding.


Wednesday, 2 September 2015

Systems building - Checks and balances


Driverless cars are, apparently, very close to commercial reality. I don't know about you but there is something pretty scary about a computer being completely in control of a complex process, which could have catastrophic consequences if it went wrong.

Ah it was nothing. You should have seen the other guy...  (From autospies.com)

That might seem a strange attitude. After all I run a fully automated systematic trading strategy. True if it goes wrong the consequences are 'just' losing money, rather than death and dismemberment; but I am pretty comfortable with letting the computer trade my money for me. Partly might be because I wrote the software myself; but given I am a competent amateur rather than a professional programmer this shouldn't be that reassuring.

No - what gives me comfort is having information about my system. Because I have a series of ways to automatically monitor my system; to understand if it's behaving properly and if anything is going wrong.

This post will tell you how I keep a close eye on my automated trading computer. It is the sixth, and final post, in a series on the nuts and bolts of building systematic trading systems. Warning: there are a few python and linux commands sprinkled here. However you don't need to be familiar with these environments to follow the post.


I like driving in my car


Let's return to the car analogy. In my car I have a dashboard with various lights and dials. If I had a nicer car, I'd probably have a built in touch screen interface as well.

Now that is what I call a dashboard ... (knightrideronline.com)

Leaving the specifics aside these various components can be classified as one of:

  • Indication lights. Binary (on/off), and which show if something is happening or not. Example - Turn signal / indicator light.
  • Warning lights. Binary (on/off), and show if something is wrong if lit. Example - low fuel warning.
  • Informative dials and displays.  Variable, show to what degree something is happening. Example - speedometer.
  • Interactive reporting. Can be interrogated to give different information. Example - satellite navigation or in car computer touchscreen.
I'll use the same keywords here to classify the different types of monitors and reports I generate. Note that a warning light ought always to be off, but an indication light could 'legally' be on, or off. If you saw your turn signal blinking when you hadn't selected it that would be a problem.

 Note that with all diagnostics the actual reporting component might be broken. So you can get false errors when all is well, or a report that all is well when it really isn't (those with some statistical training might think about type 1 and type 2 errors: usually I'd prefer to get a false error, than miss a real error).

This means there is a flaw in having warning lights. If a warning light isn't on, then it might indicate there is no problem. Or it could indicate the warning light itself isn't working, but there is an underlying problem. It's perhaps better to have a light which is green if there is no problem, then goes red when there is.

That's the analogy; so how do we actually do this in practice? We need some way of getting the underlying raw information, and then we need to report it to the user.


Sources of raw information


There are three different underlying sources of information that can be used for system status reporting: logs/echoes, diagnostics and existing data.

Logs and echoes


The most basic information you can use are echoes and logs. Echoes are my name for the trace output from a process (everything that is printed to screen, or stdout if you want to be pedantic). So my unix crontab* begins like this:

run@bilbo ~/echos $ crontab -l
#
# Daily sample FX Prices
#
0 6  * * 1-5 $HOME/workspace/systematic_engine/syscontrol/scripts/samplefx  LIVE >> $HOME/echos/samplefxpricesLIVE 2>&1


* Note for non unix users - a crontab is a schedule of processes that get kicked off on a regular basis. It's one reason why linux / unix is better for automated processes.

The part after >> means that the trace output from calling the script samplefx LIVE will be dumped into the file samplefxpricesLIVE. This is the 'echo' file for this process. Good things about echo files are that they are simple, and that without any explicit error handling they'll always dump the trace of an error failure when it happens. Bad things are that they include everything that a process writes to stdout, and unless you truncate them regularly they just get larger every day; so it can be hard to find stuff.

Logging is a bit more sophisticated. It requires software to say 'I want to log this please' rather than just printing.


run@bilbo ~/logs $ cat fx.log
2015-08-31 06:00:04 INFO    : fx           : sample all fx running  (sample_all_fx)
2015-08-31 06:00:04 INFO    : fx           : Running in AUTO mode (sample_all_fx)
2015-08-31 06:00:04 INFO    : fx           : sampling USD (sample_all_fx)
2015-08-31 06:00:04 INFO    : fx           : sampling AUD (sample_all_fx)
2015-08-31 06:00:04 INFO    : fx           : sampling AUD: getting quandl price (sample_all_fx)
2015-08-31 06:00:11 INFO    : fx           : Added fxprice AUD 2015-08-31 00:00:00 0.716025 ok (add_price_row)


In my system this is produced my simple commands like this:

    log=logger()
    log.info("sample all fx running ")
    log.info("Running in %s mode" % entrymode)


My code:
  • Outputs everything in a nice way, with time stamps, and padding so it's easy to read
  • Handles different levels of log message differently - information, warning, error or critical error.
  • Recognises which module is writing the log, and which parent process it's come from (using the python function inspect.stack)
  • Directs messages to the appropriate log file, depending on what level of error we have and the parent process.
  • Sends me an email when a critical error is logged.

It's based on the python logging package. This package also allows a new log file each day, and the automatic archiving of old log files.

Note that both logs and echoes aren't much use for understanding what is going on. You can do basic monitoring by running tail logfilename -f in a unix terminal, which will show you a live updating file (and is all you can really do if people ask to see your 'system in action'), but there is nothing here like the dashboard of a car.

"Can I see your trading system?". What people expect to see.... (kevinonthestreet.com)

.... and what people actually get.

They also aren't much use as a data layer for a reporting application, since a big unstructured text file isn't the best way to store retrievable data.Normally you'd only go to these files if something had gone badly wrong, and you needed very detailed information about what happened.

Diagnostics


Unlike the free text of logs and echoes; diagnostics are a structured and usually quantified record of what a process has been up to. So rather than logging "Just got an ask price of 124.2 for US 10 year bonds" I'd store the value 124.2 in a place specifically for that purpose.

A diagnostic record is a value (or sometimes text string), for a given date, and for a given set of characteristics, eg if I store the ask price for 10 year bonds, then I could get the time series of such values with a python command like diagnostic(system="prices", instrument="US10", value="ask_price").read()

If you're interested I store my diagnostics in a mixture of database and hdf files, with the read/write methods figuring out what to write and where to read from based on the type of the value being stored.

As with logs/echoes I will rarely look at the naked raw data. But they are used as the data layer for reporting. About two thirds of the information that the 'user facing' reports that I discuss below ultimately comes from diagnostics.


Existing system data


Here I am referring to the data I actually use in my system, eg prices, intermediate calculations, positions and trades. This isn't data specifically stored for diagnostic purposes; it's needed anyway. About one third of the information in my reports is just pulled from existing databases. Since generating and storing diagnostics is costly (both in terms of processing power and disk space), it's better to use data you already have if you can.


Reporting

This isn't my trading dashboard. But it's cool though, isn't it? (dashboardspy.wordpress.com

No, I don't have a fancy GUI that displays an actual trading dashboard (although my former employees, AHL, have an amazing one displayed on giant touchscreens in their offices if you can talk your way into them); instead I have a mixture of:

  • text reports that are emailed to me each day, 
  • a series of scripts that I can run manually to give me different kinds of information, again text based; 
  • and an interactive method for visually reporting ad-hoc diagnostics.


Reports


All my reports are produced daily, and I produce two versions. The first is emailed to me, and contains only problems (the warning lights). The second is stored on disk, and is more verbose.

I can also run all my reports interactively on an ad hoc basis, perhaps with different arguments; so rather than getting just todays trades I could get them for the last two weeks. 

Monitor report


I run two kinds of reports that give indication and warning type information.

The first report is my monitor report. This is a very simple report that:

  • Check's when a particular process last happened (from explicit diagnostics for this purpose) or particular kind of data was last written (by examining the appropriate database tables).
  • Compares this to when we expected it to happen. Daily events are expected to happen.... yes every week day; other processes during market hours.
  • Reports anything that is delayed, where the definition of delayed for me is 12 hours (fine for a relatively low frequency).
A typical emailed monitor report might look like this:

Ran monitor report at 2015-08-31 12:08:11
 Following are delayed more than 12 hours


prices-fx                 HKD          504.0     2015-08-10 00:00:00



\ ***************  FINISHED  ******************



This is telling me that I have a delay on FX rates for HKD of 504 hours; more than the 12 hour delay cutoff (this is an extreme example as I've been on holiday - a wet camping holiday if you must know).

This is a picture of me on my holiday, whilst HKD was moving slightly more than usual. Well it's not actually me. But you get the idea. (http://www.bbc.co.uk/)

I'd then need to find the underlying cause; which could involve looking at other diagnostics, or log files (in this case it's because the FX rate - normally virtually fixed - moved more than expected, which requires a manual intervention on my part).

The full verbose version looks like this:

run@bilbo ~/reports $ cat monitor_report.txt | more
Monitor report at 2015-08-31 12:08:11


 prices-fx                HKD          504.0   2015-08-10 00:00:00
last_beat-samplerunner    PLAT         1.3     2015-08-28 18:31:50
last_beat-signalsrunner   PLAT         1.3     2015-08-28 18:31:53
prices-optimal            PLAT         1.3     2015-08-28 18:32:59
prices-adj                EDOLLAR      1.3     2015-08-28 18:36:16
last_beat-samplerunner    EDOLLAR      1.3     2015-08-28 18:36:34
last_beat-signalsrunner   EDOLLAR      1.3     2015-08-28 18:36:39
prices-optimal            EDOLLAR      1.3     2015-08-28 18:37:49
prices-adj                WHEAT        1.2     2015-08-28 18:43:48
last_beat-samplerunner    WHEAT        1.2     2015-08-28 18:43:56
last_beat-signalsrunner   WHEAT        1.2     2015-08-28 18:43:59
prices-optimal            WHEAT        1.1     2015-08-28 18:45:11 


.... and so on. Clearly everything is running smoothly. The delays of just over an hour are misleading; for simplicity I assume that everything 'should' have got a price exactly when the market 'closed' (and for these US markets, that is my system closing time of 8pm local time).

That is why I use a 12 hour threshold - I am happy if my system runs once a day for a given instrument. A different tolerance for delays would make sense for other people; or for those whose system always gets a price for a given instrument at specific times each day.


Reconcile report

 

My second report for indication and warning information is the reconcile report. This runs a series of cross checks to see if the various system states are properly aligned. This won't make any sense until I explain it.

An emailed reconcile report would look like this:

Reconcile report issues at 2015-08-31 13:00:03


 No issues with optimal vs actual positions

IB and my positions perfectly matched

IB and my fills perfectly matched

Roll status with action needed

       code                              msg  near_expiry_days  position price_contract  relative_volume rollstatus                 suggest
2   LIVECOW           Roll positions ongoing                 0        -1         201510         0.004920      ALLOW                CONTINUE
7      BOBL         Roll complete *ROLL ADJ*                 7         0         201509         0.012277      ALLOW                ROLL_ADJ


 Run rollinstrument as needed

Missing forecasts

Missing last value for  KR10 cryer
Missing last value for  KR3 cryer
Missing last value for  LIVECOW rushton
Missing last value for  KR10 rushton
Missing last value for  KR3 rushton
Missing last value for  BOBL rushton
Missing last value for  BTP rushton
Missing last value for  BUND rushton
Missing last value for  OAT rushton
Missing last value for  SHATZ rushton
Missing last value for  AEX rushton
Missing last value for  CAC rushton
Missing last value for  SMI rushton
Missing last value for  EUROSTX rushton


no instruments at limit

No stopped process


No instruments with trade controls
 

 
No instruments overrides


No issues with positions (locks, other contract trading, in forward when not rolling)



\ ***************  FINISHED  ******************



Clearly what we will want to see is lots of smiley faces (yes I really do have them in the report). These are the 'green' warning lights I mentioned in my original explanation of the dashboard metaphor. If there are is a missing smiley faces then I might need to investigate further.

Let me quickly explain each of the sections of the report:

  • Are the positions I have (according to my position database) in line with the optimal: what I want to have given current market prices and my trading rules?
  • Are the positions I have (according to my position database) in line with what my broker is reporting to me?
  • Are the fills I have for today (according to my trades database) in line with what my broker is reporting to me?
  • Are any of my futures contracts in a state where I need to think about rolling them forward?
  •  Am I missing the last forecast for a given trading rule variation (here shown with internal code names) and instrument? This might be for legitimate reasons, but I need to know about it.
  • Have I exceeded my self imposed trading limits - maximum number of contracts per day; or position limits - maximum number of contracts to hold?
  • Have I manually stopped any of my processes from running? This might be a valid thing to do, but I don't want to forget about this and leave it turned off.
  • Are any of my instruments in a trading state other than "OK TO TRADE"? Again I might want this, but I musn't forget I've done it.
  • Have I applied an override; eg cut positions by half in this instrument, to a given instrument?
  • Are any of my instruments locked (meaning a trade is taking place)
  • Do I hold positions in something other than the current, or next contract I want to roll into?
  • Do I hold positions in the next contract, when I am not in the right rolling state?

There is also a longer report on disk, but I won't reproduce it here. Again clearly there are some things here that are quite specific to a futures system, but you should be able to put together a checklist for your own system which reflects your own concerns.

 

Risk report


The remainder of my reports are for informative purposes. Probably the most important of these is my risk report. This is a complex report, so I'll go through section by section.

The first section shows instruments where 'stuff has happened' - eithier in the market, or my system, or both. It's those instruments where closer attention might be warranted if the system has started behaving weirdly.

In the first table I show the instruments for which my forecast has changed the most today. I also show the daily price change, normalised for volatility, and the current size of the forecast. If my intuition suggests that the forecast change is large, or unwarranted given market movements, I will delve deeper.

The next table shows instruments for which the absolute volatility normalised daily price change is bigger than 1. Again I also show the forecast, and the change in forecast. I have similar tables looking at changes in prices, and forecasts, over a 2 week horizon (given the speed of my system they are likely to be more meaningful).

Section two focuses on my biggest expected risks.

I list all instruments for which my forecast is larger than 15 (where the expected average absolute value of my forecasts is 10). I show the actual positions, and optimal positions, I have in each instrument and show all the numbers used to calculate them, such as instrument weight and diversification multipler.

Obligatory book plug: This part of the blog will make a little more sense if you read part three of "Systematic Trading".

I also have a table with all the instruments for which the monetary value of my risk exceeds a given amount. I compare the expected risk I'd have if I could hold fractional futures contracts with what I actually have given discrete integer positions.I compare actual versus expected risk (using 2 weeks of returns for the former) for the instruments with the largest risk.

Section three of the report looks at total portfolio risk. I calculate this in various ways, with different assumptions for volatility and correlations. I also include statistics on my cash holdings here (so I can see if I need to do any spot currency transactions).

The final section looks at my return, volatility, and Sharpe Ratio over various periods (from 2 weeks up to one year).

As usual the emailed version includes only the biggest positions and risks; a more verbose version gives values for every single instrument.


Trades report

 

This is simply a list of all the trades I've executed, and my calculation of execution costs - what I could have paid if I'd been able to execute at the mid, what I would have paid if I'd crossed the spread immediately, and what I actually paid (the difference between the latter two due to my simple execution algo). It also shows the time delay between getting a price, calculating the resulting optimal position, issuing the order, and getting filled.

Any trades with large costs (even if they're positive) or long delays might warrant further investigation.

The default emailed report will be of just todays trades (this is one occasion where there is no fuller verbose version), but I can also interactively run the report for a longer period.



Profit and loss report

 

You can easily imagine what this report is for. Read my detailed post on accounting data to see how I use various sources to work out p&l numbers. I default to running a p&l for a single day, at the close, but I can also get it for different periods interactively. The emailed report contains the highlights (biggest profits/losses), whilst the verbose version has every single position I've held during the reporting period.

Very large p&l would pique my interest, but I'd probably look at the risk report to see where it came from (an unusually risky position, or a very large move in price).

 

Scripts


Here is a list of the scripts I can run in a unix terminal to get various nuggets of useful information when required (with various additional arguments). The emphasis here is on small pieces of code to do one particular specific job. Note that most of these diagnostic functions are also used when I generate the emailed reports (the underlying code can be run eithier by a script and display output; or it can return the raw data to the reporting 'engine').

  • displaylimits: What are my positions, and trades, for each instrument and how do these compare to my self imposed limits on those?    
  • rollstatus: Present eithier a summary of futures roll status, or a detailed report for an individual instrument.     

  • displaydiag: Display the diagnostic values for a given set of characteristics.  
  • lastbeat: Show when each process was last run for each instrument  
  • orderdiags: Display all the diagnostics generated by my execution algo for a particular order.     
  • displayforecasts: Show a pandas data frame of the forecasts I have for each instrument.
  • missingforecasts: Print a list of instruments and trading rule variations for which the last forecast value was missing.

  • showorder: Give me information about a particular trade.
  • displaytickets: Show the orders (both filled and unfilled) for the last N days
  • recfills: Compare the fills data from my database, and from the broker      

  • displaypositions: Show a pandas data frame of the positions (summed up to instrument level).  
  • lastposition: Show me the current position in each futures contract
  • lastopt: Last optimal position for each instrument (the position my system wants to take)  
  • displayopt:          Show a pandas data frame of the optimal positions for each instrument.     
  • optvspos: Compare my optimal positions to what I actually have.   
  • recpositions: Compare the positions from my database, and from my broker.       

  • displayfx: Show me the time series of FX rates for a particular currency    
  • lastfx: Show me the last FX rates for all currencies.   
  • displayvolume: Show a time series of volume for a particular instrument and futures contract.   
  • displayraw: Show me the time series of raw futures prices for a given futures contract.      
  •  displayadj: Show a time series of prices, after futures back adjustment  
  • lastadj: Give me the last futures back adjusted price for each instrument  

  • findIB: Find the instrument which has a given brokers identity code.          
  •  showcontract: Give me all the static information about a particular futures contract.  
  • showinstrument: Give me all the static information about a particular instrument.

   

  

Interactive diagnostics


A picture is worth a thousand words. This is why your car dashboard has a little picture of a petrol pump as a fuel warning light, rather than LED lights spelling out "NEARLY OUT OF FUEL!". To find out what is causing some behaviour, like a particular trade, will often involve looking at a dozen or more individual diagnostic time series.

So I've written some stuff in python to allow me to understand visually what has been going on. Let me give you a quick demo. I usually don't run this on a trading machine to avoid loading it up or the remote chance of a file lock. The diagnostic data is copied every day to my NAS, and then pulled down to my laptop.

This is in a python session:

from syssignals.diags import diagsBlob
from matplotlib.pyplot import show
from sysdiag.picture_subfuncs.display import plot_it

data=diagsBlob("LIVE", "VIX")

This is quick since the class loads in diagnostics 'on demand'. To load all the diagnostics up for a given instrument would take a while, so it doesn't get something unless it has to. Now we're actually going to plot something; when we run this there will be a delay whilst the diagnostics that are needed are 'sucked' in.

ans=data.show_how_combined_signal_calc_dict()
plot_it(ans)


Example of a multiple plot. The dataBlob method returns a dict of pandas dataframes. plot_it is just a function to plot these.       

data.show_position_and_threshold().plot()
show()

Example of a single plot. The dataBlob method returns a single pandas dataframe, which can be plotted as normal.



The end


As it's the end of the series, what better picture to conclude than one of a tombstone? Or in this case a gravestone, apparently (forextradingstrategies4u.com) Warning: The author of this post does not endorse the use of candlestick analysis, and would go as far to say that it is at best scientifically unproven, and at worst complete nonsense.

Yes, this really is the final post in my series on the nuts and bolts of building systematic trading systems.

The first five posts are:

http://qoppac.blogspot.co.uk/2015/04/system-building-data-capture.html
http://qoppac.blogspot.co.uk/2015/05/systems-building-futures-rolling.html
http://qoppac.blogspot.co.uk/2015/06/systems-building-deciding-positions.html
http://qoppac.blogspot.co.uk/2015/07/systems-building-execution.html


If you need more help on coding up an automated system in python on the Interactive Brokers platform, check out this series of posts. If you want advice on designing trading systems then you really ought to buy, and read, my book.