Trading Strategies: From Simplicity to Code

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.


Bayes' Theorem

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}")        




要查看或添加评论,请登录

Colman M.的更多文章

  • CPU Optimization

    CPU Optimization

    Super Scalar & SIMD Architectures: Modern CPUs can handle more operations per cycle, but only if workloads are…

  • T7 EOBI with a Custom SharedPtr

    T7 EOBI with a Custom SharedPtr

    Setting Up Custom Shared Pointer A manages order book updates and execution data coming from the T7 EOBI feed, allowing…

  • Building a Compliance Module

    Building a Compliance Module

    Key Features for Compliance in HFT Order Validation: Ensure all orders comply with regulatory rules (e.g.

  • Warming Up an HFT System: Pre-Trading with a Custom SharedPtr and QuantLib

    Warming Up an HFT System: Pre-Trading with a Custom SharedPtr and QuantLib

    HFT systems demand extreme performance and reliability. Before the trading day begins, these systems often require a…

  • Order Book with Custom shared_ptr

    Order Book with Custom shared_ptr

    Shared Order Representation Use to manage orders efficiently and safely across multiple threads. Lock-Free Order Book A…

  • Lock-Free shared_ptr

    Lock-Free shared_ptr

    Use Lock-Free Reference Counting Spinlocks, while effective, can be too slow for HFT. Instead, a lock-free reference…

  • Build a shared_ptr

    Build a shared_ptr

    Define the Control Block with Atomic Reference Counting Use atomic integers for thread-safe reference counting…

  • To turn AWS-based trading systems on/off or to dynamic

    To turn AWS-based trading systems on/off or to dynamic

    EC2 Instances for Trading Infrastructure Turn Down Trading System Terminate EC2 Instances Move Trading System to a New…

  • Unifying Market Data Formats Across Global Exchanges

    Unifying Market Data Formats Across Global Exchanges

    Market data integration is a cornerstone of building efficient and robust trading systems. Exchanges like Deutsche…

    3 条评论
  • Outsourcing the Dev Lifecycle to AI

    Outsourcing the Dev Lifecycle to AI

    This would essentially involve an AI that has complete control over the entire software development lifecycle. This AI…

    1 条评论

社区洞察

其他会员也浏览了