0% found this document useful (0 votes)
69 views40 pages

Week6 AlgoritmicTrading EN

Uploaded by

Suleyman Sadigov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views40 pages

Week6 AlgoritmicTrading EN

Uploaded by

Suleyman Sadigov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Algorithmic Trading

Week 6

1
Agenda
Introduction to Algorithmic Trading
Strategies and Techniques
Backtesting and Simulation Techniques for Trading
Coding Example

2
What is the Stock Market?

The stock market is an organized marketplace where


securities (such as stocks and bonds), commodities
(such as gold, silver, oil), foreign exchange, and other
financial assets are bought and sold. The stock
market operates under specific rules and provides a
platform that brings together buyers and sellers. On
this platform, investors place bids to buy or sell a
specific asset (such as a company's stock), and
market prices are determined based on supply and
demand.
3
What is the Stock Market?

4
5
What is Algorithmic Trading
❑ Definition: It is a computer software that operates based on the
main parameters set by an investment firm or a client of the
investment firm, producing orders to be automatically sent to
trading platforms in response to market information.

❑ Algorithmic trading refers to the automatic execution of


trading transactions in financial markets according to Algo trading
predefined rules or mathematical models.

❑ These rules can consider various factors, such as price,


timing, quantity, or complex mathematical models.

❑ The purpose of algorithmic trading is to facilitate quick


decision-making, eliminate the emotional factor, and HFT
provide more efficient trading strategies.

❑ Algorithmic trading can be performed at low frequency


(long-term trades) or high frequency (rapid trades over very
short time intervals).

6
How Does It Work?

Y
When the 50-day moving average of
stock X rises above the 200-day
Buy 50 shares of
moving average stock X!

Sell your shares of


stock X!

❑ Automatic Monitoring
❑ Order Execution Based on Conditions
❑ Elimination of the Need for Manual Tracking
❑ Automatic Evaluation of Trading Opportunities 7
Market Structure and a HEALTHY
Trading Ecosystem

8
Key Highlights
Algorithmic trading uses process- and rule-based computational formulas to execute trades.

Algorithmic trading has grown significantly since the early 1980s and is used for various purposes.

While it offers advantages such as faster execution times and reduced costs, algorithmic trading
can also exacerbate the negative aspects of the market, leading to flash crashes and immediate
loss of liquidity.

9
Key Components of Algorithmic
Trading
• Data Analysis
Analysis of historical and real-time data for
market signals.
Data such as price movements, volume, and
volatility.
• Trading Strategies
Technical analysis, fundamental analysis,
statistical arbitrage, machine learning.
Example: Moving average crossover strategies.
• Order Execution
Automated trading based on signals.
Placing orders based on price, volume, or time.
10
Computer-Based Trading by Investors -
Algorithmic Trading
Traditional
Algorithms are designed Algorithmic Smart
Trading
to help reduce the total How Order
Routing
cost of executing an
investment decision made
independently of the When Where
trading process.

"Traders become the


conductors (managers) of a What
strategy rather than the
musicians (executors)."
Situational Algorithm

11
History: 1. ANCIENT MARKET

NASDAQ OMX 12
History: 2. ELECTRONIC MARKET

NASDAQ OMX 13
History: 3. ELECTRONIC MARKET WITH API

NASDAQ OMX 14
History: 4. HFT MARKET

NASDAQ OMX 15
HFT
High-Frequency Trading (HFT):
➢ HFT is a type of algorithmic trading that is extremely
fast, short-term, and typically occurs within milliseconds
or even microseconds.

➢ HFT strategies are usually speed-focused strategies


aimed at making a profit from small price changes in the
market.

HFT algorithms require very fast computers and low-
latency data connections. Therefore, HFT firms utilize co-
location services to place their servers close to exchange
servers.

➢ HFT can increase market liquidity with high trading


volumes and very rapid buy-sell transactions; however,
some critics argue that it may create volatility and risk in
the market.

16
HFT

17
NASDAQ Yesterday/Today Algorithmic Trading Review
▪ The organizational structure of a market directly affects the diversity of trader
types.
▪ In 2009, prior to GENIUM INET, Stockholm was a fragmented, electronic, but high-
latency market.
▪ Today, the Stockholm market is fragmented, electronic, low-latency, and still has
traditional traders.
▪ In contrast, on NASDAQ today, traditional traders have almost entirely
disappeared.

18
HFT

NASDAQ OMX 19
HFT

NASDAQ OMX 20
Data Structures

21
Hardware

22
OPERATING SYSTEM

23
Technical Requirements for Algorithmic Trading
✓ Knowledge of Computer Programming or Trading Software:
Programming knowledge sufficient to program the required trading
strategy, programmers, and/or ready-made trading software.

✓ Network Connection and Access to Trading Platforms: Reliable network


connection and access to trading platforms to place orders.

✓ Access to Market Data Feeds: Access to real-time market data feeds for
the algorithm to monitor opportunities.

✓ Testability: The ability to perform backtesting on the system after it is


created and before it is deployed to the market.

✓ Historical Data: Historical data appropriate to the complexity of the rules


in the algorithm for conducting backtests.
24
Details
Backtesting
Backtesting is the process of testing a trading strategy using historical data. It
allows investors and algorithmic traders to see how their strategies would
have performed under past market conditions.
The goal is to assess whether the strategy will be profitable in advance and to
optimize it if necessary.
Simulation Techniques
Monte Carlo Simulation:
Monte Carlo simulations test a strategy under different market conditions
using random numbers and probability distributions.
The aim is to estimate the strategy's performance and risks in possible
scenarios.
Event-Based Simulation:
An event-based simulation tests how a strategy will be affected when specific
market events occur.
It examines the impact of events such as interest rate changes, company
bankruptcies, or market crises on the strategy.
25
Concepts
Data Sources and Platforms
QuantConnect:
An algorithmic trading and backtesting platform that allows strategy writing in Python and C# and
enables cloud-based testing.
Provides access to financial data worldwide and allows strategies to be tested across different
markets.
Backtrader:
A Python-based backtesting library used for testing strategies and performing analysis.
Offers a customizable structure and flexibility in various strategy parameters.

Performance Metrics
Sharpe Ratio:
A performance metric that measures the return earned per unit of risk.
A high Sharpe ratio indicates a strong risk-return profile for the strategy.
Maximum Drawdown:
Represents the percentage loss from a strategy’s highest value to its lowest value.
Indicates how much loss the strategy may incur in the worst-case scenario.
Volatility:
Measures how much the return varies over time.
High volatility indicates that the strategy is riskier, while low volatility shows a more stable
performance.
26
Types of Algorithmic Trading
Algorithms used in financial transactions are rules or instructions designed to make trading
decisions automatically. They range from simple single-stock algorithms to more complex
black-box algorithms, and they analyze market conditions, price movements, and other
financial data to execute trades at optimal times for the highest profit margin with the least
cost.

▪ Arrival Price Algorithms: Preserve Order Price and Minimize Market Impact
▪ Basket Algorithms: Portfolio Management and Risk Control
▪ Implementation Shortfall Algorithms: Minimize the Difference Between Decision Price
and Execution Price
▪ Percentage of Volume Algorithms: Order Management Based on Market Volume
▪ Single-Stock Algorithms: Optimization for a Single Security
▪ Volume Weighted Average Price (VWAP): Execute Trades at the Volume-Weighted
Average Price
▪ Time Weighted Average Price (TWAP): Price Averaging Based on Trade Duration
▪ Risk-Aversion Parameter: Investor's Risk Tolerance and Trading Aggressiveness

27
Types of Algorithmic Trading
Black Box Algorithms
These algorithms operate differently from the ones mentioned above and are at the center of
discussions about the use of artificial intelligence (AI) in the financial world. Black box
algorithms do not consist of pre-set executable rules for specific strategies; instead, they
derive their name from being a family of algorithms with hidden and unexplainable inner
mechanisms.
While other algorithms follow pre-defined execution rules (e.g., trading at a specific volume or
price), black box algorithms are characterized by a goal-oriented approach. Designers set the
goal, and specific rules and algorithms are chosen to reach it. However, black box systems
independently determine the best way to achieve that goal based on market conditions and
external events, while designers only set the targets.

Open Source Algorithmic Trading


Just as smartphone applications and advanced AI systems have enabled non-experts to create
custom applications and APIs, the world of algorithmic trading has also allowed contributions
from outside participants. Some hedge funds and investment firms, like Two Sigma and
PanAgora, are pioneering the development of open-source applications by contributing back
to the open-source community for the development of algorithms.

28
Advantages of Algorithmic Trading

Best Execution: Transactions are usually carried out at the best possible prices.
Speed: Executes trades faster than humans.
Accuracy: Reduces manual errors.
Efficiency: Operates 24/7.
Emotionless Decision-Making: Prevents emotional decisions.
Backtesting: Provides the ability to test various scenarios in real-world
conditions.

29
Attention!

30
Disadvantages of Algorithmic Trading
1. Latency Risk: Sudden price changes can make it difficult for other investors to adjust
their trades accordingly.
Delay in trade execution speed, i.e., the time difference in executing a trade.
6. Regulation
Importance: Algorithmic trading relies on high speeds and low latency.
Algorithmic trading is subject to various legal requirements and regulations.
Risk: If trades are not executed quickly, opportunities may be missed, or
unexpected losses may occur. Challenge: Compliance is complex and time-consuming.

2. Black Swan Events Importance: Algorithms that fail to comply with regulations may face legal
penalties.
Unexpected and difficult-to-predict events that cause sudden and significant
market changes. 7. High Capital Costs

Characteristics: Algorithmic trading is based on historical data and Developing and maintaining algorithmic trading systems is costly.
mathematical models; however, black swan events cannot be predicted by
these models. Expenses: Software, data feeds, server, and internet infrastructure require
continuous payments.
Examples: 2008 financial crisis, COVID-19 pandemic, May 6, 2010, when the
Dow Jones dropped 1,000 points and then recovered. Risk: High capital costs can reduce profitability, especially for small
investors.
Risk: Such events can create situations that algorithms cannot foresee, leading
to significant losses. 8. Limited Customization

3. Flash Crash Risk Algorithmic trading systems are based on predefined rules and instructions.

A sudden sharp market drop, followed by a rapid price recovery. Risk: It may be difficult for investors to flexibly customize the system
according to their specific needs or preferences.
Cause: Algorithms triggering sequential trades and a reduction in market
liquidity. Importance: Limited control over trades can negatively impact
performance.
Risk: Sudden price movements may cause substantial losses for other investors
due to the swift reaction of algorithms. 9. Lack of Human Judgment

4. Dependence on Technology Algorithmic trading relies entirely on mathematical models and historical
data.
Algorithmic trading relies on technologies like computer programs and high-
speed internet connections. Risk: It does not consider subjective and qualitative factors that may
influence market movements.
Risk: Technical failures, internet outages, or programming errors can disrupt
the trading process and lead to losses. Disadvantage: This can be restrictive for investors who prefer an intuitive or
instinctual approach.
5. Market Impact

Large algorithmic trades can significantly impact market prices. 31


Date: May 6, 2010 to allow time for market stabilization and rebalancing during
Location: U.S. stock market, particularly the Dow Jones sudden and extreme price changes.
Industrial Average (DJIA) Risk Controls: Risk controls were implemented for algorithmic
Event: The Dow Jones Index lost approximately 1000 points trading firms to prevent a similar crash from occurring again,
(about 9%) in minutes, then rebounded just as quickly. enhancing protective measures.
Process Stricter Oversight: The U.S. Securities and Exchange
Start: On May 6, 2010, around 2:32 PM, a sudden wave Commission (SEC) and other regulatory bodies took stricter
of selling began in the stock market. oversight measures, examining the impact of algorithmic
Sudden Drop: Within just a few minutes, the Dow Jones trading on the markets.
Index dropped by about 1000 points, marking one of the Impact of the Flash Crash on the Market
largest single-day point drops in history. Investor Confidence: The sudden fluctuation shook the
Recovery: Shortly after the drop, markets rebounded confidence of market participants and raised concerns about
quickly, and most stock prices returned to normal levels. how uncontrolled algorithms could impact the market.
Key Causes of the Flash Crash Increased Volatility: The rise in market volatility following the
Algorithmic Trading: High-frequency trading (HFT) Flash Crash led many investors to withdraw from the markets.
algorithms reacted swiftly to market conditions, Increased Regulations: Due to the risks posed by algorithmic
triggering a large number of sell orders. trading, market regulations were tightened, especially for
Liquidity Issue: The rapid wave of selling reduced market high-frequency trading (HFT), which was brought under
liquidity. Many liquidity providers withdrew, increasing stricter control.
price volatility. Lessons Learned from the 2010 Flash Crash
Chain Reaction of Algorithms: Some algorithms Strengthening Market Infrastructure: It became evident that
automatically responded to the sell orders from other market infrastructure needed to be more resilient for
algorithms, triggering their own sell orders, resulting in a algorithmic trading and liquidity providers.
chain reaction. Risk Management and Controls: Risk management gained
Measures Taken After the Flash Crash importance to prevent algorithms from triggering
Circuit Breakers: Circuit breakers were added to prevent sudden uncontrolled market movements.
price drops in the markets. These are triggered if prices fall by a More Reliable Circuit Breaker Systems: The implementation
certain percentage, temporarily halting trading of circuit breakers aims to prevent sudden price movements in
the future. 32
Types of Algorithmic Trading Strategies
1. High-Frequency Trading (HFT)
HFT is a strategy focused on executing large volumes of trades at extremely high speeds. It aims to profit from small price
discrepancies by trading within milliseconds.
An HFT algorithm might detect a small price difference for the same stock between the New York Stock Exchange (NYSE) and
Nasdaq. In this case, it would buy the stock at the lower price and immediately sell it at the higher price. Since the transaction
happens within milliseconds, it can quickly capitalize on these price differences.
2. Statistical Arbitrage
Statistical arbitrage is a strategy that aims to exploit market anomalies and price discrepancies. It analyzes statistical
relationships between related assets to profit from temporary price differences.
For example, if two oil company stocks usually move in parallel but one rises more than the other on a given day, the algorithm
could buy the lower-priced stock and sell the higher one to benefit from this temporary price difference. Profit is made when
prices revert to their normal correlation.
3. Trend Following
Trend following is a strategy that identifies price trends in the market and trades in the direction of these trends. It is based on
the assumption that trends will continue.
Moving Averages: Calculate the average price of an asset over a specific period to help analyze the current price trend.
Momentum: Measures the speed and continuation tendency of an asset’s price movements. High momentum indicates
that prices are moving quickly up or down, supporting the assumption that the trend will continue.
For example, if a stock’s price enters an upward trend, the algorithm buys it and holds the position as long as the trend
persists. When the price starts to decline, it sells to close the position. In the gold or currency markets, this might involve
buying when prices rise above certain moving averages and selling when they fall below them.
4. Mean Reversion
Mean reversion is a strategy that seeks to benefit from the tendency of prices to revert to a particular average level. It assumes
that prices will return to normal levels after short-term extremes.
For instance, if a stock typically trades around 100 TL but temporarily rises to 110 TL, the algorithm may sell, assuming the price
will revert to around 100 TL. Similarly, if the stock drops to 90 TL, the algorithm might buy, anticipating that the price will rise
back to the average level.
33
Algo-Trading Time Scales
High-Frequency Trading (HFT)
Executes trades within milliseconds to make quick profits.
Capitalizes on small price movements rapidly.
Example: Detects price differences instantly and profits through buying and selling.

Medium and Long-Term Investors


Pension funds, investment funds, insurance companies.
Aims to minimize price impact when buying large quantities of shares.
Example: Investment funds make gradual purchases to avoid impacting the market.

Short-Term Investors and Sell-Side Participants


Brokerage firms, speculators, arbitrageurs.
Provides liquidity in markets and profits from instantaneous trades.
Example: Brokerages act as market makers, constantly buying and selling to provide liquidity.

Systematic Investors (Trend Followers, Hedge Funds, Pair Trading Strategies)


Includes trend followers, hedge funds, and those employing pair trading strategies.
Executes trades efficiently based on automatic rules.
Example: Buys rising stocks, sells when they start to fall.
Example: Buys the lower-priced stock and sells the higher-priced stock among similar stocks; profits when
prices balance.
34
Integration of Artificial Intelligence in
Algorithmic Trading
AI-Driven Trading Systems
AI-powered trading systems provide opportunities to improve decision-making processes
and generate more accurate predictions. (Source: Stridsman, 2014)

Machine Learning Models in Algorithmic Trading


Machine learning algorithms are commonly used in algorithmic trading systems to identify
patterns and predict market movements.
Popular Algorithms: Models such as decision trees, neural networks, and support vector
machines analyze large datasets to make data-driven trading decisions. (Source: Zhang et
al., 2018)
Deep Learning in Algorithmic Trading
Deep learning is increasingly used due to its ability to extract complex patterns from large
datasets.
Types of Algorithms: Convolutional Neural Networks (CNN) and Recurrent Neural Networks
(RNN) are commonly used to analyze sequential financial data. (Source: Fischer et al., 2020)

35
Integration of Artificial Intelligence in Algorithmic Trading
Example Applications: LSTM, Reinforcement Learning
LSTM (Long Short-Term Memory): LSTM is a type of recurrent neural network used for analyzing sequential
data, especially financial time series data. It is commonly applied in stock price prediction, trend tracking,
and time series analysis.
Reinforcement Learning: Reinforcement learning is a type of learning where an agent improves itself based
on the outcomes of its actions in a given environment. It is used for optimizing algo-trading strategies,
portfolio management, and enabling trading algorithms to self-improve.
Risk Management: AI-Based Risk Analysis and Portfolio Optimization
AI-Based Risk Analysis: AI algorithms can process large amounts of data to identify and analyze financial
risks. By performing quick analysis of market fluctuations and unexpected events, they help minimize risks.
Portfolio Optimization: AI algorithms aim to maximize returns and balance risks by maintaining an optimal
distribution of assets within a portfolio. With machine learning and deep learning techniques, portfolio
management becomes more efficient and flexible.
Future Developments: AI and Quantum Computing in Trading
AI and Quantum Computing: Quantum computing offers processing power beyond that of classical
computers, enabling much more complex computations in a short time.
Promising Applications: Combined with AI, quantum computing allows for faster and more complex
analyses in algorithmic trading.
Potential Impact on Trading: It is anticipated that quantum algorithms, especially due to their speed in
solving complex optimization problems, will be used in trading strategies. Quantum computing’s ability to
process vast amounts of data instantly could provide a competitive advantage in trading decisions.
36
Benefits of Artificial Intelligence in Algorithmic
Trading

Enhanced Trading Accuracy and Efficiency


Real-Time Processing: AI-powered trading systems analyze large amounts of data in
real time.
Benefits: More precise trading decisions, reduced transaction costs, and minimized
human biases. (Source: Fischer et al., 2020)
Improved Risk Management
Risk Analysis: AI algorithms identify potential risks and adapt strategies accordingly.
Risk Management Techniques: Stop-loss and take-profit algorithms are integrated into
AI-based systems to automate trading actions. (Source: Stridsman, 2014)
Optimized Trade Execution
Order Speed: AI technology enables faster execution of orders.
Result: Reduced price slippage, increased trading efficiency, faster identification of
liquidity opportunities, and higher profitability. (Source: Zhang et al., 2018)

37
Challenges and Limitations of Artificial
Intelligence in Algorithmic Trading
A. Data Limitations
Dependency: AI algorithms rely heavily on historical data.
Challenges: Insufficient or low-quality data can negatively impact algorithm
performance; changing market conditions can reduce data reliability. (Source: Fischer
et al., 2020)

B. Model Complexity and Interpretability


Complexity: Deep learning algorithms are complex, making them difficult to interpret.
Outcome: This makes it challenging for regulators to monitor AI-supported trading
systems and raises regulatory concerns. (Source: Stridsman, 2014)

C. Systemic Risks
Risk: Poorly designed or unverified AI-based trading strategies may increase market
volatility.
Mitigation: Regulators need to enforce supervision and establish risk management
measures. (Source: Zhang et al., 2018) 38
1. Aggressive HFT (Aggressive High-Frequency Trading): High-frequency trading that takes
market liquidity.
2. Algorithmic Trading: Electronic trading based on a set of predefined rules and parameters.
3. Direct Market Access (DMA): The process allowing a brokerage client, who is a member of
the exchange, to send orders through fully electronic channels, with orders passing through
the brokerage's order aggregation system and sent directly to the exchange. In direct market
access, it is essential for orders to undergo necessary risk checks within the member's system
before being transmitted to the exchange.
4. Co-location: Allowing broker servers to be placed physically close to exchange servers to
reduce latency.
5. Latency: The time taken for an order to travel from the client to the exchange system and for
the confirmation to return to the client. Also known as "round-trip latency."
6. Latency Jitter: The level of deviation from the average latency. The stability of latency is as
important as the latency itself.
7. Throughput: The amount of data processed per unit time, usually measured as the number
of messages received, sent, or processed per second.
8. Passive HFT: High-frequency trading that reduces market liquidity.
9. High-Frequency Trading (HFT): Algorithmic trading involving the rapid assessment of multiple
parameters and the submission/cancellation of numerous orders to the order book in
milliseconds or microseconds.
39
Q-A

40

You might also like