Code Monkey home page Code Monkey logo

learn-algorithmic-trading's Introduction

Learn Algorithmic Trading

Learn Algorithmic Trading

This is the code repository for Learn Algorithmic Trading , published by Packt.

Build and deploy algorithmic trading systems and strategies using Python and advanced data analysis

What is this book about?

It’s now harder than ever to get a significant edge over competitors in terms of speed and efficiency when it comes to algorithmic trading. Relying on sophisticated trading signals, predictive models and strategies can make all the difference. This book will guide you through these aspects, giving you insights into how modern electronic trading markets and participants operate.

This book covers the following exciting features: Understand the components of modern algorithmic trading systems and strategies Apply machine learning in algorithmic trading signals and strategies using Python Build, visualize and analyze trading strategies based on mean reversion, trend, economic releases and more Quantify and build a risk management system for Python trading strategies Build a backtester to run simulated trading strategies for improving the performance of your trading bot Deploy and incorporate trading strategies in the live market to maintain and improve profitability

If you feel this book is for you, get your copy today!

https://www.packtpub.com/

Instructions and Navigations

All of the code is organized into folders. For example, Chapter02.

The code will look like the following:

import pandas as pd
from pandas_datareader import data

Following is what you need for this book: This book is for software engineers, financial traders, data analysts, and entrepreneurs. Anyone who wants to get started with algorithmic trading and understand how it works; and learn the components of a trading system, protocols and algorithms required for black box and gray box trading, and techniques for building a completely automated and profitable trading business will also find this book useful.

With the following software and hardware list you can run all code files present in the book (Chapter 1-10).

Software and Hardware List

Chapter Software required OS required
All Python 2.7+ Windows, Mac OS X, and Linux (Any)

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. Click here to download it.

Errata

  • Page 144 (Bullet pont 4, line 9 of code): MIN_PROFIT_TO_CLOSE = 10 should be MIN_PROFIT_TO_CLOSE = 10*NUM_SHARES_PER_TRADE

Related products

Get to Know the Authors

Sebastien Donadio Sebastien Donadio is the Chief Technology Officer at Tradair, responsible for leading the technology. He has a wide variety of professional experience, including being head of software engineering at HC Technologies, partner and technical director of a high-frequency FX firm, a quantitative trading strategy software developer at Sun Trading, working as project lead for the Department of Defense. He also has research experience with Bull SAS, and an IT Credit Risk Manager with Société Générale while in France. He has taught various computer science courses for the past ten years in the University of Chicago, NYU and Columbia University. His main passion is technology but he is also a scuba diving instructor and an experienced rock-climber.

Sourav Ghosh Sourav Ghosh has worked in several proprietary high-frequency algorithmic trading firms over the last decade. He has built and deployed extremely low latency, high throughput automated trading systems for trading exchanges around the world, across multiple asset classes. He specializes in statistical arbitrage market-making, and pairs trading strategies for the most liquid global futures contracts. He works as a Senior Quantitative Developer at a trading firm in Chicago. He holds a Masters in Computer Science from the University of Southern California. His areas of interest include Computer Architecture, FinTech, Probability Theory and Stochastic Processes, Statistical Learning and Inference Methods, and Natural Language Processing.

Suggestions and Feedback

Click here if you have any feedback or suggestions.

Download a free PDF

If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.

https://packt.link/free-ebook/9781789348347

learn-algorithmic-trading's People

Contributors

dineshpackt avatar jiripik avatar manikandankurup-packt avatar packt-itservice avatar packtutkarshr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

learn-algorithmic-trading's Issues

chapter 5 mean reversion

mark the remaining position to market i.e. pnl would be what it would be if we closed at current price

open_pnl += abs(sell_sum_qty - position) * (close_price - buy_sum_price_qty / buy_sum_qty)

Above block of code is wrong. it should be open_pnl += abs(position)*(.........). Position is the amount the should be marked to market

Ch2 Seasonality Code Missing

In the tail end of the chapter 2 the concepts of seasonality is introduced along with some lines of code to help generate the graphs. Despite being listed like all other lines of code in the chapter, it is not written anywhere in this repository.

Chapter 2 - Seasonality code not working

The code of Seasonality does not work properly. when we copy paste the code an error occurs. I am using the 3.9 version python. I believe the problem is in this section:

goog_monthly_return = goog_data['Adj Close'].pct_change().groupby(
[goog_data['Adj Close'].index.year,
goog_data['Adj Close'].index.month]).mean()

goog_montly_return_list=[]
for i in range(len(goog_monthly_return)):
goog_montly_return_list.append
({'month':goog_monthly_return.index[i][1],
'monthly_return': goog_monthly_return[i]})

Chapter 1 , cant run the code .

xd im getting this error . thx for rewieving this issue , not sure if its a library mistake or something else ; as im a beginner ... thx for helping me out ( ;

D:\algo_trding_learning\venv\Scripts\python.exe D:\algo_trding_learning\buylowsellhigh.py
Traceback (most recent call last):
File "D:\algo_trding_learning\buylowsellhigh.py", line 5, in
goog_data = data.DataReader('GOOG', 'yahoo', start_date, end_date)
File "D:\algo_trding_learning\venv\lib\site-packages\pandas\util_decorators.py", line 213, in wrapper
return func(*args, **kwargs)
File "D:\algo_trding_learning\venv\lib\site-packages\pandas_datareader\data.py", line 370, in DataReader
return YahooDailyReader(
File "D:\algo_trding_learning\venv\lib\site-packages\pandas_datareader\base.py", line 253, in read
df = self._read_one_data(self.url, params=self._get_params(self.symbols))
File "D:\algo_trding_learning\venv\lib\site-packages\pandas_datareader\yahoo\daily.py", line 153, in _read_one_data
data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
TypeError: string indices must be integers

Process finished with exit code 1

Getting error with Chapter 7, Trading Strategy Unit Test

Hello,

I keep getting the following bug when trying to run the unit test for Trading Strategy.

TradingStrategy_ut.py::TestMarketSimulator::test_filled_order FAILED     [ 33%]
TradingStrategy_ut.py:45 (TestMarketSimulator.test_filled_order)
self = <TradingStrategy_ut.TestMarketSimulator testMethod=test_filled_order>

    def setUp(self):
>       self.trading_strategy= TradingStrategy()
E       TypeError: __init__() missing 3 required positional arguments: 'ob_2_ts', 'ts_2_om', and 'om_2_ts'

TradingStrategy_ut.py:8: TypeError
FAILED [ 66%]
TradingStrategy_ut.py:10 (TestMarketSimulator.test_receive_top_of_book)
self = <TradingStrategy_ut.TestMarketSimulator testMethod=test_receive_top_of_book>

    def setUp(self):
>       self.trading_strategy= TradingStrategy()
E       TypeError: __init__() missing 3 required positional arguments: 'ob_2_ts', 'ts_2_om', and 'om_2_ts'

TradingStrategy_ut.py:8: TypeError
FAILED   [100%]
TradingStrategy_ut.py:29 (TestMarketSimulator.test_rejected_order)
self = <TradingStrategy_ut.TestMarketSimulator testMethod=test_rejected_order>

    def setUp(self):
>       self.trading_strategy= TradingStrategy()
E       TypeError: __init__() missing 3 required positional arguments: 'ob_2_ts', 'ts_2_om', and 'om_2_ts'

TradingStrategy_ut.py:8: TypeError

volatility_mean_reversion_with_dynamic_risk_allocation wrong closed pnl calculation

Hi there,
I checked this script, and i my opinion, there is a bug on a stage where open close pnl is calculated.
As a solution i propose make something like that:

This section updates Open/Unrealized & Closed/Realized positions

  if position > 0:
    open_pnl = 0
    if sell_sum_qty > 0:  # long position and some sell trades have been made against it, close that amount based on how much was sold against this long position
      open_pnl = abs(sell_sum_qty) * (sell_sum_price_qty / sell_sum_qty - buy_sum_price_qty / buy_sum_qty)
    # mark the remaining position to market i.e. pnl would be what it would be if we closed at current price
    open_pnl += abs(sell_sum_qty - position) * (close_price - buy_sum_price_qty / buy_sum_qty)
  elif position < 0:
    open_pnl = 0
    if buy_sum_qty > 0:  # short position and some buy trades have been made against it, close that amount based on how much was bought against this short position
      open_pnl = abs(buy_sum_qty) * (sell_sum_price_qty / sell_sum_qty - buy_sum_price_qty / buy_sum_qty)
    # mark the remaining position to market i.e. pnl would be what it would be if we closed at current price
    open_pnl += abs(buy_sum_qty - position) * (sell_sum_price_qty / sell_sum_qty - close_price)
  else:
    # flat, so update closed_pnl and reset tracking variables for positions & pnls
    closed_pnl += open_pnl
    buy_sum_price_qty = 0
    buy_sum_qty = 0
    sell_sum_price_qty = 0
    sell_sum_qty = 0
    last_buy_price = 0
    last_sell_price = 0
    open_pnl = 0

Error in ch4_turtle_trading.py?

In this part of ch4_turtle_trading.py, shouldn't in the last two elif statements "short_exit" and "long_exit" be swapped? Since if position > 0 then we are long and there should be a long exit and not a short exit and vice versa.

init=True
    position=0
    for k in range(len(signals)):
        if signals['long_entry'][k] and position==0:
            signals.orders.values[k] = 1
            position=1
        elif signals['short_entry'][k] and position==0:
            signals.orders.values[k] = -1
            position=-1
        elif signals['short_exit'][k] and position>0:
            signals.orders.values[k] = -1
            position = 0
        elif signals['long_exit'][k] and position < 0:
            signals.orders.values[k] = 1
            position = 0
        else:
            signals.orders.values[k] = 0

    return signals

TypeError: string indices must be integers

Great Book Thank you for Author, Lot of best wishes !

I am getting an error on the 4th line of the first chapter, any idea ?

from pandas_datareader import data
start_date = '2014-01-01'
end_date = '2018-01-01'
goog_data = data.DataReader('GOOG', 'yahoo', start_date, end_date)

ERROR:

data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
TypeError: string indices must be integers

ch2 seasonality code issue not able to compile

Hello,

I tried running the seasonality code and I am not able to run it. The first issue I notice is at line code 24. there is a typo instead of monthly im seeing montly.
its also missing index for 'monthly_return.

there is also an issue in line code 28 and 31 with the boxplot call function.

Error Chapter2\seasonality.py

Chapter2\seasonality.py

Traceback (most recent call last):
File "C:\Python310\lib\site-packages\pandas\core\indexes\base.py", line 3803, in get_loc
return self._engine.get_loc(casted_key)
File "pandas_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\hashtable_class_helper.pxi", line 2263, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas_libs\hashtable_class_helper.pxi", line 2273, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 0

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "c:*\Workspace\learn-algorithmic-trading\Chapter2\seasonality.py", line 26, in
'monthly_return': goog_monthly_return[i]})
File "C:\Python310\lib\site-packages\pandas\core\series.py", line 981, in getitem
return self._get_value(key)
File "C:\Python310\lib\site-packages\pandas\core\series.py", line 1089, in _get_value
loc = self.index.get_loc(label)
File "C:\Python310\lib\site-packages\pandas\core\indexes\multi.py", line 2916, in get_loc
loc = self._get_level_indexer(key, level=0)
File "C:\Python310\lib\site-packages\pandas\core\indexes\multi.py", line 3263, in _get_level_indexer
idx = self._get_loc_single_level_index(level_index, key)
File "C:\Python310\lib\site-packages\pandas\core\indexes\multi.py", line 2849, in _get_loc_single_level_index
return level_index.get_loc(key)
File "C:\Python310\lib\site-packages\pandas\core\indexes\base.py", line 3805, in get_loc
raise KeyError(key) from err
KeyError: 0

cp5_basic_mean_reversion.py

mark the remaining position to market i.e. pnl would be what it would be if we closed at current price

author line 106 : open_pnl += abs(sell_sum_qty - position) * (close_price - buy_sum_price_qty / buy_sum_qty)

should be corrected since:

position -= NUM_SHARES_PER_TRADE # reduce position by the size of this trade
sell_sum_qty += NUM_SHARES_PER_TRADE
so the remaining position : abs(position)
Line 106 : open_pnl += abs(position) * (close_price - buy_sum_price_qty / buy_sum_qty)
and the author line 111 : open_pnl += abs(buy_sum_qty - position) * (sell_sum_price_qty/sell_sum_qty - close_price)
also need to be corrected:
Line 111 : open_pnl += abs(buy_sum_qty - position) * (sell_sum_price_qty/sell_sum_qty - close_price)

Note: abs(position) = abs(buy_sum_qty-sell_sum_qty)

basic_trend_following

In line 72, when defining the Sell_entry rationale for the first case (Short Entry) shouldn't we have:
apo > apo_value_sell_entry?
Since an APO above the threshold points to an uptrend in prices and thus a good moment to short the stock.

chapter 7 LiquidityProvider.py bug

I think I found some bug in Chapter 7: LiquidityProvider.py

def lookup_orders(self, id) (line 11) returns a tuple of (None, None) or (o, count).

But generate_random_order(self) lines 35-40 compares the tuple with a None, making new_order always False

And line 52, shouldn't it be if new_order instead of if not new_order? If it is a new_order, we want to increase the order_id and append the new order ord to self.orders

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.