The convenience of the investment market process has fostered irrational investing among people.
The hellish market from 2022 to 2024 turned my mindset, life, and account into a complete mess. Leaving aside external issues like fund managers playing dead, I also executed some irrational operations that resulted in losses.
Reflecting on these painful lessons, in order to avoid the continuous impact of market volatility on my mindset and daily life, I turned my focus toward quantitative automated trading.
As for investment, for someone like me who doesn’t have time to watch the market but wants to achieve returns exceeding index funds, I still trust the ultra-rational decision-making of computers.
Disclaimer: The following is my personal research content and does not represent any investment advice. Please invest with caution.
Quick Start
Register an Interactive Brokers account and download Gateway
Install the backtrader library (quantitative backtesting framework)
Install the ib_insync library (interfaces with Interactive Brokers Gateway; developer bro erdewit passed away on March 11, 2024, RIP)
Write a sample SMA strategy using the ib_insync documentation or GPT
Run it and observe the charts
Recommended Common Frameworks
backtrader Traditional strategy framework
qlib AI quantitative framework
Turtle Trading System
Essentially a trend-following strategy, the rules encompass every aspect of trading, leaving no room for subjective thinking by the trader.
It has some connection to quantitative trading and can serve as a method for setting relevant parameters. Of course, parameters can also be automatically found via programs.
Core Mindset
- View trading with a long-term perspective
- Avoid outcome bias
- Believe in the power of positive expectancy
Operational Level
- First, master an advantageous system and find a trading strategy with a positive expected value (at least producing positive returns in historical backtests)
- Manage risk and hold your ground
- Unswervingly execute the strategy
- Keep it simple and clear, and catch the trends. Most profits come from 2–3 trades; do not miss a single trend. Otherwise, the year’s hard work will vanish into thin air.
Steps
Markets: What to Buy or Sell?
Generally used in futures markets with sufficient liquidity: 30-year US Treasury bonds, 10-year US Treasury bonds, commodities, and currencies of developed countries.
Position Sizing: How Much to Buy or Sell?
Core idea: Hold smaller positions in high-volatility contracts and larger positions in low-volatility contracts.
Method: Dynamically build positions using volatility to control the intra-day loss to no more than 1% of total assets.
H: High price of the day
L: Low price of the day
C: Closing price of the day
TR: Daily True Range
TR = MAX(H-L, H-C, C-L)
Calculate N, the 20-day moving average of TR:
N = (19 * PDN + TR) / 20
PDN: Previous day’s N value
TR: Daily True Range
Calculation begins on day 21. For the preceding 20 days, the average value is calculated by summing the TR of the previous 20 days and dividing by 20.
(1% of Account / Unit Position Dollar Amount) = (N / Stock Price)
Unit Position Dollar Amount = (1% of Account / N) * Stock Price
Unit Position Share Count = (1% of Account / N)
The higher the stock’s volatility, the larger N is, and the smaller the position size.
The Turtle Trading System requires that positions in a single market cannot exceed 4 units of position size.
Entry: When to Buy or Sell?
System 1: Short-term system based on a 20-day breakout
System 2: Long-term system based on a 55-day breakout
For the long term, take action once the 55-day high or low point is breached:
If it exceeds the 55-day high, buy one unit position to start going long
If it breaks below the 55-day low, sell one unit position to start going short [If you are not familiar with shorting, you can only consider going long]
Building Positions: Establish a Unit Position at the Breakout Point
Then gradually expand the position step by step at price intervals of (1/2 N)
Add one unit position for every 1/2 N interval until reaching the maximum of 4 units
Gradual position adjustment is clever; if the stock price drops by 1 N, the total loss still remains at 1% of total assets
Stop-Loss: When to Abandon a Losing Position?
**No single trade can lose more than 2% of total assets**
A fluctuation of 1 N corresponds to a 1% fluctuation in total assets
Calculated at 2%, the stop-loss standard is 2 N
After the final buy order, if the stock price falls by 2 N, stop loss immediately
Exit: When to Exit a Profitable Position?
System 1: Uses the 10-day breakout exit rule
System 2: Uses the 20-day breakout exit rule
Exit when a 20-day new low is reached
Pros: Although somewhat counter-intuitive, it guarantees that position holders will not miss massive upward trends
Cons: Watching huge profits evaporate in an instant
Tactics: How to Buy and Sell?
If the capital is small, there’s no need to consider this.
M-Score Model for Detecting Financial Fraud
Filter stocks before selection to kick out fraud-tainted stocks.
M = -4.84 + 0.92 * DSRI + 0.528 * GMI + 0.404 * AQI + 0.892 * SGI + 0.115 * DEPI - 0.172 * SGAI + 4.679 * TATA - 0.327 * LVGI
A simple linear formula; just calculate the M-value.
Parameter Explanations
DSRI Days Sales in Receivables Index
DSRI = (Current Period Receivables / Current Period Revenue) / (Prior Period Receivables / Prior Period Revenue)
GMI Gross Margin Index
GMI = (Prior Period Gross Margin) / (Current Period Gross Margin)
Gross Margin = (Revenue - Cost of Goods Sold) / Revenue
AQI Asset Quality Index
AQI = (Current Period Non-Current Assets / Current Period Total Assets) / (Prior Period Non-Current Assets / Prior Period Total Assets)
Non-Current Assets = (Total Assets - Current Assets - Property, Plant & Equipment - Securities)
SGI Sales Growth Index
SGI = Current Period Revenue / Prior Period Revenue
DEPI Depreciation Index
DEPI = Prior Period Depreciation Rate / Current Period Depreciation Rate
Depreciation Rate = Accumulated Depreciation / (Property, Plant & Equipment + Accumulated Depreciation)
SGAI Sales, General, and Administrative Expenses Index
SGAI = (Current Period SGA Expenses / Current Period Revenue) / (Prior Period SGA Expenses / Prior Period Revenue)
TATA Total Accruals to Total Assets
TATA = Total Accruals / Total Assets
Accruals = Operating Income - Cash Flow from Operations
LVGI Leverage Index
LVGI = Current Period Leverage Ratio / Prior Period Leverage Ratio
Leverage Ratio = Total Liabilities / Total Assets
M Range → Likelihood of Financial Fraud
M < -2.22 Low
-2.22 <= M <= -1.78 Medium
-1.78 <= M High
Stock Volatility Prediction
Python implementation of the GARCH model (Generalized Autoregressive Conditional Heteroskedasticity model).
Calm periods often follow calm periods, and volatile periods often follow volatile periods → volatility clustering.
Fat tails and high peaks: the probability of extreme events occurring in financial assets is much higher than that in a normal distribution, which is why the Kelly Criterion should be divided by 2.
Good ideas are stitched together. Models and tools are component parts to be stitched, and you don’t need to understand every component deeply. A chef doesn’t need to know how to manufacture a kitchen knife; they only need the knife to chop and cook.
Volatility can predict risk, and position sizing levels can be designed based on risk. Trading strategies can also be adjusted according to volatility.
Performance Evaluation Metrics
Profit and Loss Category
Total number of trades, winning trades, losing trades, win rate
Measures how frequent trading is and how good the win rate is
- Total Profit: Sum of all profits
- Total Loss: Sum of all losses
- Net Profit: Total Profit - Total Loss
- Profit Factor: Total Profit / -Total Loss
- Average Trade Profit: Net Profit / Number of Trades
- Average Win: Total Profit / Number of Trades
- Average Loss: Total Loss / Number of Trades
- Cumulative Return: Total return rate
- Average Return: Annualized return rate
Risk Metrics
Measures the degree of strategy risk, as well as how much pain needs to be endured and for how long
- Maximum Drawdown: The peak-to-trough decline of assets over a given period
- Maximum Drawdown Duration: The time taken for assets to move from peak to trough
- Volatility: Variance of returns
Ratios Category
Sharpe Ratio: (Annualized Return - Risk-Free Rate) / Standard Deviation of Return
Measures how much volatility must be endured to achieve a given return.
The higher the return and the lower the volatility, the better—larger values are preferable.
You can observe the Sharpe Ratios of master investors.
- Sortino Ratio
- Improvements to the Sharpe Ratio
- Calmar Ratio
- Replacing the variance term in the Sharpe Ratio with Maximum Drawdown
Other Category
Alpha: Excess return rate
Your return rate - Market index return rate
Beta: Correlation between your return rate and the market index return rate
SQN: System Quality Number, a metric to evaluate the quality of quantitative strategies
Python library — pyfolio library
Option Pricing Formulas
Black-Scholes Formula, Binomial Tree Model
Conclusion
Although investing has not increased my wealth for the time being, I have gradually come to understand the underlying principles of how the world operates, and my mindset has been tempered amidst ups and downs. While researching industries, I have also gained a deeper understanding of certain sectors.