Algorithmic Trading: A Practitioner’s Guide
henrikwarne.com
henrikwarne.com
The book is kind of old now, but it was written by Barry Johnson, who worked at Morgan Stanley on their algo trading team.
The book is kind of dry, but very thorough and clear on its concepts. It reads more like a university text book than anything else. It just goes through concepts one by one, chapter by chapter.
[0]: https://www.amazon.co.uk/Algorithmic-Trading-DMA-introductio...
I am currently into the April programming language, Array Programming Reimagined In Lisp[1], and I may try to implement the mathy parts of the book's code in APL and the remainder in Lisp as presented with some improvements. April is very flexible and takes advantage of the libraries and symbolic processing of Lisp. The creator of April just switched it to lazy evaluation from eager evaluation last month.
Clojure is a lot of fun too, and opens up a lot of libraries to use. Dragan Rocks[2] has some great libs for ML/DL
Mark Watson is the main culprit for writing his book and having the nerve to publish it: Common LISP Modules: Artificial Intelligence in the Era of Neural Networks and Chaos Theory[3] I had been superficially studying AI then - GAs, ANNS, chaos and complexity - back in the late 80s, and this book introduced me to Lisp. Mark is sometimes on here, so Mark, thank you!
[1] https://github.com/xahlee/xah-fly-keys
[3] https://www.amazon.com/Common-LISP-Modules-Artificial-Intell...
A couple years ago I read all I could on this and started systematic trading on crypto. Ended up with the best results on a public platform and ran a small trading operation with a few clients, one a crypto market maker. It's really hard due to all the market unknowns, stress and psychology/emotion. After the FTX debacle I lost ~35% of capital. Currently put it on pause and back software engineering.
Had to rebuild my asset allocation system which was based on FTX api. Improved it to be realtime and using Binance api. There's still the counter party risk-Binance could get busted or USDT fraud.
I hope to learn more about this topic!
The hard part is the backtesting and design of strategies talking into account the science and art of it. And the absolute truth that past performance does not dictate future results.
I haven't tried non-crypto, I think I will just leave that to simple investments in tracker funds or etfs.
I've come across many profitable traders in Crypto who only measure in USD and when you compare their results to just buying and holding ETH/BTC at the start of the cycle they come out behind. Everyone feels like a great trader in a bull market.
I'm talking about people who write their own software rather than working for a company that does it professionally.
I'd be interested to hear any tips or pointers on what strategies you've found that work.
I have worked on multiple strategies. - Strategies using technical indicators do work, but you have to reasonable. If you find these giving higher than expected returns, or too many consecutive wins - take the money. Stop live trading and continue dummy trading - eventually there is a point where you can start live trading again. The thresholds will be determined from backtests.
- Statistical strategies work for swing trading. However, these are very difficult to figure out. Need a lot of data (for backtesting). These work consistently over a longer period and might look loss making over a small period.
- Scalping within 5-10 minutes works pretty consistently, signals based on options data.
- Understand and realise the law of large numbers, and use that to your advantage.
- Give importance to understanding the concept of Time. There is a whole lot of weird and scammy pseudo-science around it. Therefore do not blindly rely on one theory.
The only other thing I'd say is that if you're in a bull market you may have easy wins. Then after -- when the market turns against you -- these will evaporate.
So long term you have to ask yourself if you are REALLY beating the market. If you'd bought Amazon or Microsoft instead, over 20 years you'd probably be far ahead.
And if you'd bought pets.com, or webvan, you'd be far behind. Survivor bias at work.
https://en.wikipedia.org/wiki/Registered_retirement_savings_...
If your algotrading profits depend on market being bull or bear, you're doing it wrong. Volatility matters, not the direction.
Mine work in either market. But I trade on the millisecond lines to avoid market bias. And yes volatility is key. As if confirmation of this approach I see Binance has just recently introduced a 1s chart (effectively 1000ms).
However most retail algo traders using indicators use larger time frames that are more susceptible to market trendiness.
So yes, I made a 3-5% profit over roughly 18 months, but it took a lot of time, stress, and in the end I ended up with less money.
Is your experience the same?
As far as strategies go, I've said it here before, but all my strategies are quite simple and straight forward. The difficulty is almost always the execution. Almost all of my strategies are arbitrage or market making, and some of them trade off of events, like earnings, interest rate announcements, the weekly petroleum status report, and things you'd find on an economic calendar.
None of my strategies are speculative, that is I have no idea what company will perform well over a long period of time and in fact in many cases I don't even know what the company I'm trading even does. I also don't make use of any so called technical indicators, like relative strength, or fibonacci this/fibonacci that.
For the vast majority of my activity, my algos only enter into a trade if it's guaranteed to make money.
To give a vague idea of what the process looks like, every strategy starts from the premise that the market is perfectly efficient and there is no opportunity to make money. We then construct a model of what a perfectly efficient market should look like. We then backtest this model to determine whether the market is actually perfectly efficient. In most cases it will turn out to be either very close to efficient, or inefficient but in a way that cannot be profited from after taking into account fees, latency, and other factors. But sometimes you find areas where the model predicts certain behavior and the backtesting shows that the real world doesn't follow that model. In that case we then proceed to investigate very carefully what is going on. Did we make a faulty assumption? Is our model not seeing the whole picture so that there are factors we did not take into account? This happens A LOT and in fact we are very skeptical when our backtesting deviates from our model. But if after scrutiny we find no reason to doubt out model, then go from backtesting to running it in a simulator, and then from simulator to running it live on a very small scale, and then over time increasing the scale.
Our backtesting and simulating is incredibly sophisticated and precise. Almost all publicly available backtesters just look at trade activity or very low resolution data, and never accounts for things like market impact. Our backtester takes into account individual orders and simulates the entire order book, taking into account where our order would be placed within the order book. We also simulate potential market impact as well, which requires us to run simulations in parallel with different potential market impacts so we can see what the worst case scenarios are and there's a host of other factors a good simulator and backtester will take into account.
Success rate for newly formed hedge funds is probably something like 50% over a 5 year horizon. For solo traders, it's probably closer to 1%.
There is WAY too much stuff you need to be on top of, if you want to be successful, than a single person can manage. It's about as feasible as starting a one man (coal) mining operation, where you must dig the tunnel, extract the coal, process it, sell it, manage the business operation and retain your sanity. You need at least a handful of people to be effective, all with different specialties.
...not to mention that if you're successful as a solo trader, you could be making 10x more with proper financial backing. If your strategy is returning 25% annually on a personal 1 mil investment, there's a good chance it'll still be returning >20% on a 10 mil investment (once you get to 100 mil or into the billions, your returns start to diminish due to market impact). Find a good backer, they'll literally give you money and a support team for a piece of the profit.
No, citadel securities just had a record year internalizing retail flow.
I'm not doing any order book or HFT stuff. It's mostly mean reversion < 15 minute trades. I have a considerable amount of options trading experience and that's what my main strategy revolves around. I don't have a killer strategy that some of these algorithmic firms are capable of, but the current one is promising. I also have a fairly rudimentary form of backtesting, which is a Jupyter Notebook crunching data I've collected over the years. I use some ML python libraries as a bonus, but I haven't created any strong enough attributes yet to achieve a high amount of predictive accuracy in that sense. My strategies mostly revolve around simple statistics.
My stack is a Linux VM with MySQL, running a suite of python scripts that collect data in real time and make the automated trades through TD Ameritrade's API.
By the way, I wouldn't consider myself smart or gifted - my strength relies solely on my determination. If you were to ask me if it's worth it, I would say "mostly." At the very least I've come away with a much higher understanding of the equity/option markets, and I know much more about MySQL, Python and data mining. At this point though I'd take a job with an algorithmic firm in a heartbeat.
HFT is, more or less... but algo trading in general can be as simple as executing strategies you would otherwise manually perform. I believe there's still enough alpha out there.
This is both absolutely correct, and entirely in-actionable since it uses hindsight. The question would be...what are the two stocks to buy to beat the market for the next 13yrs.
How do you come to believe something so blatantly false and naive? Is this due to the proliferation of the (good) advice that most Americans are best off saving for retirement in index funds?
Apple has a huge problem now: it's eating it's own market. Believing there is an endless belt of profit owning Apple shares is to ignore the risks of consumers changing their minds about "I need this years iPhone" and sales tanking. I read more people saying "my iPhone 12/13 is still fine" than I read people saying "I want to spend $1500 on an iPhone 15"
The cost of being Apple never gets better. They now have exposure to costs they didn't have in 2009. They will have exposure to more costs (s/w complexity, VLSI in-house) and they will have exposure to more market entrants. They are also at risk of supply chain dynamics which could erode profits multi-year if bad enough: imagine if TSMC's yield drops on complex must-have chips? It's force majeure stuff.
I certainly wish I'd bought apple in the 2000s or before. I would hesitate to assume its worth owning FAANG stock now, rather than other things (including EFT)
The long-term rate of return on investment across markets is 6-7% and being above that for periods is unusual and begs questions.
Maybe Apple will come up wih the next revolution in human-machine interface. Who knows?
This is a common misconception or a poorly phrased statement. It's not true that someone who bought/held tech stocks, or an ETF beat virtually all managed funds or that holding on to ETFs beats virtually every managed fund. It's true that passive investing, in tech or ETFs would have beat the average managed fund, and it's also true that an investor is better off investing in an ETF/diversified portfolio, but there are exceptional managed funds that significantly outperform the market.
The problem is that you are no more likely to know which managed fund will outperform the market than you are to know which stock will outperform the market. Picking a fund that will outperform the market, especially after fees, is just as hard as picking stocks, and in fact it might be even harder due to the fees.
But this does not mean that all, or virtually all funds perform worse than the market or even a segment of it.
One of the advantages of hedge funds in particular is that they can employ leverage in a way that provides almost all of the upside of leverage while protecting an investor from some of the downside. For example if I, as an individual, used leverage to trade on the market and some black swan even happens, not only would I lose the amount I invested, I could also end up in debt and have to sell my house or other assets to cover my obligations.
If I use leverage through a hedge fund, then I still get almost all of the benefits if the market moves in my favor, but if the market moves heavily against me the most I can lose is my investment.
This is not true. The broker would try to liquidate your positions well before that happens. Failure to put up collateral means your position will be forcibly closed. It's called Maintenance Margin. The last thing the broker is going to allow is for its clients to incur a debt and be on the hook. The hedge fund instead will send you a letter that your money is gone. Same thing.
Brokers have no ability to liquidate a position on a company that declares bankruptcy after market hours. In fact, most major events happen during times when trading is either halted or the market is closed.
As sad as it is, there are people who have committed suicide over having a negative balance including this individual who carried a -$730,000 balance:
https://www.nytimes.com/2020/07/08/technology/robinhood-risk...
It's all tradeoffs - the broader the conditions at which a bank can recall your margin, the cheaper the interest and lower personal guarantee requirements (some may not hold you personally liable for negative balances - check your T&Cs). Funds can obviously borrow more, and at lower interest rates because of that though. Obviously their loans will be wound up on the way down no matter what, because the bank can't get money out of a negative balance like they would an individual.
Funds also don't tend to all-in on three tech stocks, so the fact they are very exposed to volatility with that type of leverage is less of an issue.
As for your other comment trying to be pedantic about funds owning three stocks, there are numerous publicly traded leveraged funds that trade just a single stock, one single stock [1]. They are known as single-stock ETFs and the purpose of these funds is specifically to provide an indirect form of leverage to investors. For example, IRA accounts are forbidden from using leverage, but someone can use an IRA account to purchase a leveraged ETF including a single stock ETF.
The point is it's not cut and dry that the market geared equity solution is superior (though, IMO, the individual advantage lays on the side of things without margin calls, but full recourse - you can ride through a downturn without being forced to sell, assuming you keep your job and other risks etc etc).
Those single stock ETFs are significantly more limited than full-market geared funds (1.5x rather than more typical 2-3x). Equity geared ETFs are definitely just straight up more convenient (and safer) for the vast majority of people and situations though, I agree with you on that.
I don't want a fancy explanation of how it works, I would like to know the name of a single brokerage that offers this product because as I said, I don't think it exists as it is frankly a pretty basic violation.
I did end up finding the specific agreement - it pertains to Australian retail clients (https://gdcdyn.interactivebrokers.com/Universal/servlet/Regi...), and clauses 3 and 7 lay out that retail clients are not liable for a negative balance arising from a margin liquidation. Retail clients for Australia have pretty limited margin (25 or 50k iirc), so this isn't super high risk for most people regardless (can't lose that much money).
The other stuff I talk about arises from other products in Australia as well - it's possible to borrow money and buy shares without being exposed to margin calls, so long as you make repayments on the loan. It's pretty different to a traditional margin account though, and only really applies to ETFs (NAB Equity Builder). I also imagined that existed elsewhere, but really I'm only speaking from what I've seen available in Australia.
Clause 3.A.e specifically states that trading on margin can result in a loss of funds greater than that deposited into your account and that you accept that risk.
In conjunction with Clause 7.K which states that you must reimburse the broker for any liabilities as a result of the liquidation undertaken by the broker.
You are always on the hook for the full amount of losses on margin.
Did you perhaps intend to reply to someone else?
the poster you're replying to implies that this might not be possible at all if the successful funds only are so because of random chance.
I still think theres alpha, but I don't think it would be from off the shelf methods that some random youtube trading guru talks about.
I'd argue that an order that'd immediately be filled does provide liquidity to the market overall.
One reason to use "post-only" is explained in TFA:
> Many markets use the maker-taker fee structure. Traders that place orders that rest on the exchange earn a maker fee, and traders that “take” liquidity, that is execute orders against the existing resting orders, pay a taker fee. The taker fee is higher than the maker fee
If you do post-only, you'll get maker fees.
Crossing orders are considered liquidity taking rather than providing since they're interacting with another market maker's resting (providing) orders.
Ah that's interesting!
No, it takes liquidity, by definition.
- "taking liquidity" is taking existing orders off the orderbook and
- "making [liquidity]" is opening new orders that rest on the orderbook
It's the terminology of the industry.
At the end of the day, what counts as the truth is how much fees you pay when sending a limit order that immediately crosses.
And the answer, for every single market on the planet, is "you pay taker fees". Period.
Some equity venues are pay both sides. Others are “reverse” provider pays.
CME worlds largest futures exchange symmetrical fees
https://www.cmegroup.com/company/files/cme-fee-schedule-2023...
I don't buy the argument.
Removing tick (or at least reducing it 100x) would put more emphasis on price discovery instead of speed.
To practitioners it refers to the use of algorithms to trade large quantities of stocks or futures or whatever. The goal is to reduce trading costs by executing small trades at the right time. This is distinct from and rather more common than quant trading where an algorithm actually decides what bet to make.
Are you perhaps referring to a locked market?
Anyway, it sounds like your colleague was just an idiot who didn't understand the basics of professional trading and got in over his head. He should have stuck with buying index funds on a Vanguard account.
I don't know why you are so quick to assume that.. that guy did a year with some large firm before breaking out on his own.. a YEAR of full time I think
> it sounds like your colleague was just an idiot
oh I see, you want to call people that name.. got it
I can do a lot more math than the guy I knew in that story, but I would not call him an idiot lightly
“Stupid is as stupid does.”
- Forrest Gump, 1994
as for has anyone, well, there's the infamous wallstbets on reddit but also the less infamous /r/algotrading where you may have better luck with the question
For (2), there are zero-fee brokers (e.g. those mentioned by downvoteme1 earlier) that you can use, so you don't have to keep feeding the broker.
Well, everything has a non 0 chance but you can code certain conditions that have to be met before an order goes through.
IMO, you would have to have significant capital to even end up in a situation where a bug causes lots of loss.
Here is an example of something you might be thinking of.
https://www.henricodolfing.com/2019/06/project-failure-case-...
> Not get lose all their money to some company's API fees
It's not too bad these days. A lot of brokers offer "zero-fees" which really just means you only have to pay the SEC ones which aren't too bad.
Which leads in to 2. The idea is that you are aiming for algorithms that take into account the API fees. If you didn't account for that in the price of business, than this is the same as not accounting for taxes in how you pay for things. That is, you did it wrong.
Thing is, one will be hard pressed to find solid, relevant, detailed and current information about legitimately profitable trading strategy. Once a strategy becomes widely used, the 'market inefficiencies' being exploited cease to be readily available, so there is a strong incentive to keep a good strategy private. I vaguely remember reading about HFT firms obscuring their trading activity for this reason. Additionally you will find the online world absolutely saturated with the grifter types. So good info is hard to come by. Be prepared to learn at least the fundamentals of both trading and statistics, do lots of testing, and basically figure it out on your own because nobody successful (and smart) is sharing their reliable, profitable strategies (that doesn't mean you can't learn from them - just don't copy paste).
It is a very interesting domain though and I thoroughly enjoyed learning about it all and building mine.
You basically want alpha but alpha decays over time.
Think of alpha as being some insight no matter how slight that a coin will land heads as apposed to tails more times than not.
Now comibine this with a risk management system that involves you only risking 1% of capital (avoiding gamblers ruin) and you are off to the races.
Once you got that part setup, try to write a simple program that buys or sells an equity from the command line .
From their own you can start exploring trading algorithms. Some are pretty basic, like when the price crosses above a 200 DMA, then buy a stock as that usually signifies an upward run, while selling if the price falls below the 200DMA as that is bearish.
Then you can read some books on price action, fundamental or technical analysis and build your own algos.
You can try some trading using algorithms to identify profitable trading opportunities. That would normally fall under "prop trading" instead. There are definitely people doing this in ways achievable by a home hobbyist, but don't expect any low hanging fruit. Find some niche in some less liquid instruments. Don't look for anything that relies on being fast - someone else will be there who measures latency in nanoseconds.
I made a python framework to try to help with this: https://github.com/robswc/stratis
However, it became hard to maintain an opensource version. I would say its still not a bad way to get a head start (bias there, ofc)
I will say, its not something that can be done "on the side." I originally made a decent amount of $ by getting lucky in crypto. I figured I'd "just become a algo trader" and it was much more difficult than I could have imagined.
I actually _just_ started a series on how to build an equity trading system from scratch. I planned to put part 1 out later this week but eh, I'll post it now, it touches on it better than my comment here can :)
https://robswc.substack.com/p/building-an-equity-trading-sys...
* the post assumes you already have alpha (a profitable strategy)
> Has anyone done this successfully?
Regarding this, I actually originally talked a bit with the (now infamous) SBF of FTX about this. I originally wanted to join Alameda Research... but at the time, I didn't want to move across the world. For years I regretted that decision (not so much now, lol) I started my own firm though and I have made a decent amount of $. Truth be told though, knowing what I know now, I might have put more energy into a start up. I enjoy the challenges of algotrading but doing some consulting work, I think I enjoy "building" more than running statistical tests, cleaning data, etc etc.
To sum up this comment though, _if_ you had a profitable strategy and _if_ you built a system that could reliably execute trades, you certainly could be successful. It is very difficult though.
Is a platform I experimented with and found pretty solid. I definitely learned some things however, I realised the amount of effort I needed to put in would be better used elsewhere.
I do raw api calls, but you have to be so very careful. You can do something wrong and totally, absolutely jack yourself up, so this way is only for the very brave, but I think it offers good opportunities to understand the markets better if you can stomach the extreme risk profile.
Check out https://algotrading101.com/learn/ for a good set of practical articles to give you some context. I wish I could still point to Quantopian, which is where I started my learning process on this, but it died.
Anyone claiming that is not the case is just misinterpreting his PnL.
The internet is full of people thinking they are market wizards just because they cannot residualize their idiosyncratic returns properly against beta, sector, country, size properly.
Once such simple method, which still works, is to short BTC and go long QQQ/SPY during market hours if there is relative weakness of BTC before the market open, whilst going long QQQ/SPY. Both legs are exited at the market close.
This has been very profitable. Even the most advanced firms are bound to miss easy strategies. Pattern recognition, intuition are more valuable when to comes to trading than having more data or better tools.
Dennis reasoned that even though he could publish all the rules in a newspaper, only a few traders would heed them since most traders tend to avoid following rules rigidly. He mentioned that most people only follow the trading rules as a method of improvising when they deem it necessary and that deviating from the rules can affect the performance of the trade.
I have a few friends in the equities business and this topic always comes up over drinks. It would seem that in the age of GPU farms and open source ML tools, are we to a point where patterns are so subtle or short-lived that only a machine could pick up on them?
Originally it used to mean "quantitative", as opposed to "qualitative". It is a type of investment strategies where you target to be right "on average". Once you are right, say, 51% of the times, you aim to reach this asymptotic behavior by trading more and more. Either horizontally (trading more stocks) or vertically (trading more often). You want to keep the law of large numbers on your side to consistently earn that 1% edge that you found.
This contrasts with qualitative investment strategies (sometimes called "discretionary") where you target very precise and punctual events on which you have a very high (say 90%) chance of being correct.
You can imagine both these strategies with a coin toss game.
With a quantitative approach, you would try to find something that allows you to have just even barely more than a 50% chance of winning. Once you find that, you want to bet as much as possible. This is close to the strategy of a casino: they have games which all have an ever so slightly positive expected value, then they just have to make a lot of people play these games.
With a qualitative strategy, you would study very hard to find an event when you can predict at 90% chance the result of the coin toss. You don't play the game until this event is about to happen, and you bet big once it is about to happen.
Nowadays, the term "quant" has a broader meaning, which roughly encompass any kind of financial work which is heavy on math, or sophisticated. You can even find "back office quants", "pricing quants", etc
Parasites indeed
But here we are with 26 letters complaining on perhaps the most advanced thing humans have made because you don’t see the value of saving some money while trading.
People don’t exist to give things a way, expecting people to pay more is parasitic.
What direct suffering does algorithmic trading cause? It would take quite the narrative spin to argue that it's as bad or worse as one of the above industries.
They won't, but they could. They totally could, and you are ruining that possibility.
The socially useful idea behind trading is allocation of capital. How do we determine which sectors get capital and which don't? How do we determine a price of something?
This is in theory. In practice of course... BitConnect!
We're building Invsto (https://invsto.com) to make algorithmic trading easier for individuals. Happy to chat with anyone interested in the space.