Algo Trading
Algo Trading
http://neverlosstrading.com/Algorithmic%20Trading.html
Motivation
Computers can process larger amounts of data than humans and make
decisions faster than humans
Algorithms do what they are told, takes the human emotion out of trading
Trillions of $$$ traded daily - highly paid employees
Bleeding edge of sciences; math, engineering, computer science, etc.
Introduction:
The Efficient Market Hypothesis
Impossible to beat the market
Market efficiency causes prices to incorporate and reflect all relevant information
Prices adjust quickly to new information
Prices should reflect all available information
DataCollection.jar
Python Pandas
Hello World Algo Trading
Kinds of Trading Strategies
Backtesting
System Architecture
Appendix
DataCollection.jar
Collects intra-day data from Google Finance
Writes data to current directory
Snapshots
Can collect multiple stocks
Type in ticker, hit collect data
Works on Macs and PCs with Java
Example Output (tab delimited)
127.35 4:00PM EDT
# Get Data
aapl = pd.io.data.get_data_yahoo('AAPL',
start=datetime.datetime(2006, 10, 1),
end=datetime.datetime(2015, 4, 7) )
aapl.head()
# Do some time series manipulation
aapl['SMA50'] = pd.rolling_mean(aapl['Adj Close'],50)
aapl['EMA50'] = pd.ewma(aapl['Adj Close'], 50)
# Plot
plt.figure()
plot(aapl.index, aapl['Adj Close'])
plot(aapl.index, aapl['SMA50'])
plot(aapl.index, aapl['EMA50'])
plt.legend(('ADJ Close', 'SMA50', 'EMA50'))
Pandas Example: DataFrame
Great for data manipulation Open High Low Close Volume Adj Close SMA50 EMA50
Date
Common functions 10/2/2006 75.1 75.87 74.3 74.86 178159800 10.09NaN 10.09
10/3/2006 74.45 74.95 73.19 74.08 197677200 9.98 NaN 10.03446
Df.head()
10/4/2006 74.1 75.46 73.16 75.38 207270700 10.16 NaN 10.07714
Df.tail() 10/5/2006 74.53 76.16 74.13 74.83 170970800 10.08NaN 10.07787
10/6/2006 74.42 75.04 73.81 74.22 116739700 10NaN 10.06168
Df.index()
Df.ffill()
Align and fill missing data
Pandas Example: Data Visualization
df = pd.io.data.get_data_yahoo(symbols=['AAPL', 'GE',
'GOOG', 'IBM', 'KO', 'MSFT', 'PEP'])['Adj Close']
rets = df.pct_change()
a = plt.figure()
plt.scatter(rets.PEP, rets.KO)
plt.xlabel('Returns PEP')
plt.ylabel('Returns KO')
pd.scatter_matrix(rets, diagonal='kde', figsize=(10, 10));
Pandas Example: Data Visualization 2
plt.scatter(rets.mean(), rets.std())
plt.xlabel('Expected returns')
plt.ylabel('Risk')
for label, x, y in zip(rets.columns,
rets.mean(), rets.std()):
plt.annotate(label, xy = (x, y), xytext =
(20, -20),textcoords = 'offset points', ha =
'right', va = 'bottom', bbox = dict(boxstyle =
'round,pad=0.5', fc = 'yellow', alpha = 0.5),
arrowprops = dict(arrowstyle = '->',
connectionstyle = 'arc3,rad=0'))
http://nbviewer.ipython.org/github/twiecki/financial-analysis-
python-tutorial/blob/master/1.%20Pandas%20Basics.ipynb
Hello World Algorithmic Trading
Backtesting a Moving Average Crossover Strategy
http://www.quantstart.com/articles/Backtesting-a-Moving-Average-Crossover-in-
Python-with-pandas, Zipline
Strategy: Moving Average Crossover
+ 1 + + 1
=
= +
=
Strategy Detail: Common Signals
Exponential Moving Average: EMA
Volume By Price
Best Ask
Best Bid
http://www.trade2win.com/articles/
1750-understanding-liquidity-market-
pullbacks
Limit Order Execution
For an order to be executed, a trade must cross below your buy, or a trade happens at your price,
when you have been filled in the queue
Limit Order Execution Place Order
Bids Price Asks
100.03 2,1
100.02 3,7,8
100.01 5,2,15
100 1,2,5
1,2 99.99
2,5,8 99.98
3,8,1,5,3 99.97
2,3 99.85
Place limit
order of 2 lots
at 99.99
Limit Order Execution Book Movement
Bids Price Asks
100.03 2,1
100.02 3,7,8
100.01 5,2,15
100 1,2,5
1,2,5 99.99
2,5,8 99.98
3,8,1,5,3 99.97
2,3 99.85
Key Statistics
Average wins :: 0.637 USD
Average loss :: -0.438 USD
# Wins :: 214
# Losses :: 210
# Neutrals :: 3
Win Rate :: 0.501
PPC :: 0.104USD
# Traded :: 427.0
Ann. Sharpe :: 2.335
Backtesting a Strategy
Does the strategy work across many assets?
How many years does it work for? Overall: 1980 2016
Sharpe: 2.12
Does it escape the bid-ask bounce? PPC: 0.13
Wins: 12634
Losses: 10527
Risk Tolerance? Trades: 23666
Maximum Drawdown?
Fees? Trading frequency?
Sharpe:1.299
PPC:0.338
Wins:255
Losses:202 In Sample: SPY 2004-2010
Trades:463.0 Out of Sample: Assets Randomly Selected:
ADBE XLNX BBBY CFN EMC ADP AFL DE T SPLS DG ADS
ALL MET CL PX WYN
Order Sizing
Multi-Threaded
C++, Java, Python Can instantiate multiple
Communication strategies
over interfaces RSI
Event Driven Backtester
Eliminates errors
Can use the same strategy
for trading and
backtesting
Visualizing an Intraday Strategy
Exit Long
Entry Long
General Tips
This is not a get rich quick scheme
Finding alpha is hard, do not get discouraged
Drawdown are painful, be careful with leverage
Trust your alpha (if you have some), strategies are usually simple
Performance
Out of sample performance is generally of in sample performance
Live trading performance is generally of in sample performance
Due to curve fitting, unexpected slippage, etc.
Make sure you account for transaction fees and slippage and order sizes
Fun and exciting way to learn not only the markets but also computer science
and math
Data is your friend
Build your own backtester/execution environment
Questions?
Further Readings
Best guide to starting algo trading (intro/backtester taken from here)
http://www.quantstart.com/
Execution Environment/Backtester/Community
https://www.quantopian.com/
Cheap trading platform with API
https://www.interactivebrokers.com/ind/en/main.php
Stellar documentation on how to do execution
http://www.financial-spread-
betting.com/course/candle-stick-charting.html
Appendix: Order Sizing
= $1,000
=
10 ($)
= max , ,
1 1 +
=
Appendix: Sharpe Ratio
=
=
=
=
Developed by William F. Sharpe
Measures risk adjusted performance
Risk vs. Reward
Higher is usually better
Usually annualized
Adjust portfolio returns to a daily basis, average the returns and multiply
by 252
Appendix: PPC
Profit Per Contract
=
=
=
A measure of profitability, measured in ticks
A highly liquid stock usually has a tick size of a penny
If your strategy has more than 2 ticks, it is considered profitable (can
escape the bid/ask bounce), if testing on bar data without limit order
execution on bar closes
You can submit market orders and still make money
Assumes liquidity!!!!!
Appendix: CAPM
Capital Asset Pricing Model
= +
=
=
=
=
Describes the relationship between risk and the expected
return
Investors need to be compensated for time (risk free rate)
and risk (beta)
Appendix: Drawdown
The measure of the largest drop from peak to bottom (in percentage)
It is a pain index measure
Extremely important to measure the duration of the drawdown
Do you want to be losing money for years?
= max {() }
(0,)
http://ctaperformance.com/wntn
Appendix: Distribution of Returns
http://ctaperformance.com/wntn
Generally a histogram of returns
Look at center, shape, distribution, spread
Want positive center, and no major outliers
Appendix: Strategy Correlation
Generally you want to make sure that your strategies are not correlated to
each other (look at daily returns)
You do not want everything to have a bad day at the same time
Balanced returns are good
Uncorrelated strategies tend to yield higher Sharpe ratios when mixed
Correlated strategies tend to reflect the same alpha
These strategies tend to compete with each other
Negatively correlated strategies can be good
Highly negatively correlated strategies can indicate problems with your alpha