Python Algorithmic Trading Cookbook
上QQ阅读APP看书,第一时间看更新

Preface

Python is a very popular language that is used to build and execute algorithmic trading strategies. If you want to find out how you can build a solid foundation in algorithmic trading using Python, this cookbook is here to help.

Starting by setting up the Python environment for trading and connectivity with brokers, you'll then learn the important aspects of financial markets. As you progress through this algorithmic trading book, you'll learn to fetch financial instruments, query and calculate various types of candles and historical data, and finally, compute and plot technical indicators. Next, you'll discover how to place various types of orders, such as regular, bracket, and cover orders, and understand their state transitions. You'll also uncover challenges faced while devising and executing powerful algorithmic trading strategies from scratch. Later chapters will take you through backtesting, paper trading, and finally real trading for the algorithmic strategies that you've created from the ground up. You'll even understand how to automate trading and find the right strategy for making effective decisions that would otherwise be impossible for human traders.

By the end of this book, you'll be able to use Python for algorithmic trading by implementing Python libraries to conduct key tasks in the algorithmic trading ecosystem.

Who this book is for

If you are a financial analyst, financial trader, data analyst, algorithmic trader, trading enthusiast or anyone who wants to learn algorithmic trading with Python and important techniques to address the challenges faced in the realm of finance, this book is for you. A basic working knowledge of the Python programming language is expected. Although some fundamental knowledge of trade-related terminology will be helpful, it is not mandatory.

What this book covers

Chapter 1, Handling and Manipulating Date, Time, and Time Series Data, explains everything about the Python DateTime module and pandas DataFrames that are required to handle time series data efficiently.

Chapter 2, Stock Markets – Primer on Trading, covers how to set up Python connectivity with a broker, fetch financial instruments, and get a quick hands-on at placing simple orders. You will also learn how to query margins and calculate brokerage and government taxes.

Chapter 3, Fetching Financial Data, covers financial instruments in-depth.

Chapter 4, Computing Candlesticks and Historical Data, explains how to fetch and understand historical data, and also how to fetch, compute, and plot various candlestick patterns, including Japanese (OHLC), Renko, Line Break, and Heikin-Ashi.

Chapter 5, Computing and Plotting of Technical Indicators, explains how to compute and plot 10 types of technical indicators, including trend indicators, momentum indicators, volatility indicators, and volume indicators.

Chapter 6, Placing Regular Orders on the Exchange, explains how to place 16 types of regular orders across two transaction types, two order codes, and four order varieties. You will learn how to query the order status in real time, while also learning about the possible order states supported by the broker and the order life cycle for regular orders.

Chapter 7, Placing Bracket and Cover Orders on the Exchange, explains how to place eight types of bracket orders and four types of cover orders across two transaction types and multiple order varieties and how to query the order status in real time. You will learn about target, stoploss, and trailing stoploss, along with the possible order states supported by the broker and the order life cycle for both bracket and cover orders.

Chapter 8, Algorithmic Trading Strategies – Code Step by Step, explains how to code your own algorithmic trading strategy from scratch using two strategy coding examples involving regular and bracket orders, respectively.

Chapter 9, Algorithmic Trading – Backtesting, covers how to backtest your own algorithmic trading strategy using two strategy coding examples involving regular and bracket orders, respectively. You will also learn how to fetch execution logs and various types of backtesting reports, including profit and loss reports, statistics reports, and order history logs for your strategy.

Chapter 10Algorithmic Trading – Paper Trading, explains how to paper trade your own algorithmic trading strategy in live markets using two strategy coding examples involving regular and bracket orders, respectively. You will also learn how to fetch execution logs and various types of paper trading reports, including profit and loss reports, statistics reports, and order history logs, in real time for your strategy.

Chapter 11Algorithmic Trading – Real Trading, explains how to real trade your own algorithmic trading strategy in live markets and real money using two strategy coding examples involving regular and bracket orders, respectively. You will also learn how to fetch execution logs and various types of real trading reports, including profit and loss reports and statistics reports, in real time for your strategy.

To get the most out of this book

This book is for anyone who is interested in the field of algorithmic trading. You are not expected to have any background in finance or algorithmic trading. You are expected to have a basic knowledge of the Python programming language. Each chapter introduces a new concept in algorithmic trading and takes you step by step, from zero to hero. This book can help you build a rock-solid foundation in algorithmic trading using Python.

You need to have the latest version of Python 3 installed on your computer. The recipes in this book were tested on Python 3.8.2 and they should work on any future release of Python as well.

You also need a broking account with Zerodha, a modern broker, to try out the recipes covered in most of the chapters. Appendix I provides detailed, step-by-step information on how to set up your Zerodha account in case you do not have one.

To execute trading strategies, you also need an account with AlgoBulls. Appendix II provides detailed, step-by-step information on how to set up your AlgoBulls account in case you do not have one.

Also, almost every chapter expects you to have additional Python packages installed, such as pyalgotrading. You can install these using pip. This is explained in the technical requirements section of every chapter.

All the recipes in this chapter are provided as Jupyter notebooks on our GitHub repository: https://github.com/PacktPublishing/Python-Algorithmic-Trading-Cookbook. You can install Jupyter Notebook as well if you would like to try out the recipes directly without typing any code. You can install this using pip: pip install notebook.

The requirements for each chapter are summarized in the following table:

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at www.packt.com.
  2. Select the Support tab.
  3. Click on Code Downloads.
  4. Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip/UnRarX for Mac
  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Python-Algorithmic-Trading-CookbookIn case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781838989354_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The broker provides unique keys to each customer, typically as api-key and api-secret key pairs."

A block of code is set as follows:

>>> plot_candlestick_chart(historical_data, 
PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:TATASTEEL | 1st Jan, 2020 | '
'Candle Interval: 1 Minute')

Any command-line input or output is written as follows:

$ pip install pyalgotrading

Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "A Japanese candle is green in color if its close price is above its open price."

Warnings or important notes appear like this.

Tips and tricks appear like this.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at customercare@packtpub.com.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.