Trading Strategies: From Simplicity to Code
Mean-Reversion
When you stretch a rubber band (price goes up or down a lot), it wants to snap back to its normal shape.
Concept: Based on the idea that asset prices tend to revert to their historical average over time.
Mathematical Basis:Ornstein-Uhlenbeck Process: A stochastic process used to model mean-reverting behavior.Moving averages, z-scores, and standard deviation bands.
Example: Pairs trading involves identifying two correlated assets, such as stocks, and trading on deviations from their historical price spread.
import numpy as np
import pandas as pd
# Generate synthetic price data
np.random.seed(42)
price = np.cumsum(np.random.randn(100)) + 100 # Random walk
# Calculate moving average and z-score
mean = pd.Series(price).rolling(window=20).mean()
std = pd.Series(price).rolling(window=20).std()
z_score = (price - mean) / std
# Trading logic: Buy when z-score < -2, sell when z-score > 2
signals = np.where(z_score < -2, "Buy", np.where(z_score > 2, "Sell", "Hold"))
print(signals)
Momentum
Once a snowball starts rolling down a hill, it gets bigger and keeps going faster.
Momentum trading is based on the belief that “what is going up will keep going up, and what is going down will keep going down.”
If prices are moving strongly in one direction, they’re likely to continue in that direction for a while.
Look for stocks or assets that have been going up consistently over a period of time (e.g., days or weeks). Buy them, expecting the trend to continue.
Or look for assets that are falling and short-sell them, expecting them to keep falling.
Momentum is calculated using price changes over time:
If M > 0, the price is trending upward (buy signal). If M<0, it’s trending downward (sell signal).
# Momentum Calculation
momentum = pd.Series(price).diff(periods=10)
# Generate Buy/Sell signals
signals = np.where(momentum > 0, "Buy", "Sell")
print(signals)
Statistical Arbitrage
Imagine two friends playing on a seesaw. If one goes too high, the other will bring them back to balance
Identifies short-term mispricings between related financial instruments using statistical metrics.
Cointegration: Statistical measure that tests whether two or more time series move together in the long run.
Kalman Filters: For dynamic estimation of spreads between correlated assets.
Trading based on deviations from a statistically significant mean spread.
领英推荐
from statsmodels.tsa.stattools import coint
# Synthetic data for two correlated assets
asset1 = price
asset2 = price * 0.8 + np.random.randn(100) * 2
# Check for cointegration
score, p_value, _ = coint(asset1, asset2)
if p_value < 0.05:
print("The assets are cointegrated. Tradeable Pair!")
else:
print("No cointegration.")
Market Making
You set up a lemonade stand, offering to sell lemonade for $2 (ask) and buy it back for $1.80 (bid). You make money from the difference, even if prices change
Bid-Ask Spread:
Bid Price: The price at which the market maker is willing to buy a security.
Ask Price: The price at which the market maker is willing to sell a security.
Spread: The difference between the ask price and the bid price.
Profit Mechanism:
Market makers profit by earning the spread. For example:If the bid price is $100 and the ask price is $101, the spread is $1.If the market maker buys one share at $100 and sells it at $101, they earn $1.
High Volume and Small Profits:
Market making is not about large profits per trade. Instead, it's about executing a high volume of trades to accumulate significant profits from the spread over time.
# Simplified market-making logic
bid_price = price - 0.5 # Bid 50 cents lower than current price
ask_price = price + 0.5 # Ask 50 cents higher than current price
# Simulate trading at these prices
profit = 0
for p in price:
if p < bid_price[-1]: # Buy at bid
profit += (ask_price[-1] - p)
elif p > ask_price[-1]: # Sell at ask
profit += (p - bid_price[-1])
print(f"Total Profit: ${profit:.2f}")
Latency Arbitrage
Imagine two people are running to buy sweets at the shop, but one has a shortcut. The faster person gets there first
# Simulate a price feed with delay
market1 = np.cumsum(np.random.randn(100)) + 100 # Faster market
market2 = market1 + np.random.randn(100) * 0.5 # Slower market
# Arbitrage opportunity
profit = 0
for m1, m2 in zip(market1, market2):
if m1 > m2: # Buy in market2, sell in market1
profit += (m1 - m2)
print(f"Arbitrage Profit: ${profit:.2f}")
Bayesian Models
If it rained yesterday, there’s a higher chance it might rain today. But if it hasn’t rained for a week, it’s less likely
Probabilistic models that update predictions as new data becomes available.
Markov Chain Monte Carlo (MCMC) methods for inference.
Predictive modeling in uncertain environments.
# Simulate a price feed with delay
market1 = np.cumsum(np.random.randn(100)) + 100 # Faster market
market2 = market1 + np.random.randn(100) * 0.5 # Slower market
# Arbitrage opportunity
profit = 0
for m1, m2 in zip(market1, market2):
if m1 > m2: # Buy in market2, sell in market1
profit += (m1 - m2)
print(f"Arbitrage Profit: ${profit:.2f}")