I am very proud to announce the book “Hands-On Financial Trading with Python” written with Sourav Ghosh and published by Packt Publishing on April 29, 2021. The book is available for purchase at amazon.com and at packtpub.com.

Front Cover
Back Cover

Book’s Target Audience

  • Anybody curious about financial/algorithmic trading who has not yet found the ideal environment for experimenting with the market data and trading strategies. The book is written for anybody who wants to start daily algorithmic trading but has not a comprehensive view of the Python libraries and market data sources to use. All its examples are real-life and the book enclosed code allows you to set up your backtesting system within minutes.
  • Professional asset managers and traders migrating to Python from any other programming language or any other Python backtesting framework.
  • Introductory finance and economics university courses.

Book’s Primary Goals

The book is more about “firing the light in you” than being an encyclopedia of trading strategies. It aims at building the readers’ intuition by listing key examples and use cases.

It does list the key Python libraries for time series analysis, market data access and algorithmic trading, along with explaining how to instantly build a backtesting and risk/return analysis system using Zipline and PyFolio. These two libraries are unique in the way how easy it is with them to test a trading strategy over tens of years of market data and to produce sophisticated risk reports – all with just a few lines of Python code. Check this Jupyter Notebook for yourself.

The key advantage of using Zipline for backtesting is that Quandl offers their uses complimentary historical market data database with daily prices up to 2018. That is more than enough for building the reader’s intuition of how to build successful algorithmic strategies.

How to Get Most of the Book

We recommend reading the book from cover to cover, and while reading running the examples covered in the book in the Jupyter Lab.

All book’s examples are available in the book’s GitHub repository.

The book’s Appendix A contains instructions how to restore the book’s Conda’s virtual environment. The virtual environment has been rather tricky to set up since the book depends on tens of libraries with sometimes conflicting versions’ requirements. All is prepared for the reader to set up the environment with a one-line command.

While running the examples, we urge the reader to modify the parameters, such as trading horizon, the stock symbol, or the trading strategy’s entry / exit rule, and to see how the strategy’s profitability changes.

The book contains most of the key concepts used in modern algorithmic trading. The reader is encouraged to recombine them in his/her own trading strategies.

For example, one way to classify a time series is by the magnitude of the Facebook Prophet’s trend component. The stocks with a very strong trend component are more suitable for certain trading strategies. On the other hand, the stocks with oscillating prices are more suitable for other types of strategies.

The key components of algorithmic trading are the trading strategies’ entry and exit rules. We demonstrate that combining multiple criteria from the book make the trading strategy more robust and profitable.

The Next Steps

Once you become familiar with the Zipline backtesting, the next step is to start trading with Zipline.

We recommend using Zipline Trader built upon Zipline which supports Alpaca and IB as their brokers. It also offers free market data using the alpaca data bundle (sign up here).

The entire sample trading algorithm is listed below (source):

import os
import yaml
import pytz
import pandas as pd
from datetime import datetime
import pandas_datareader.data as yahoo_reader

from zipline.utils.calendars import get_calendar
from zipline.api import order_target, symbol
from zipline.data import bundles
from zipline import run_algorithm
from zipline.gens.brokers.alpaca_broker import ALPACABroker


def get_benchmark(symbol=None, start=None, end=None):
    bm = yahoo_reader.DataReader(symbol,
                                 'yahoo',
                                 pd.Timestamp(start),
                                 pd.Timestamp(end))['Close']
    bm.index = bm.index.tz_localize('UTC')
    return bm.pct_change(periods=1).fillna(0)


def initialize(context):
    pass


def handle_data(context, data):
    order_target(context.equity, 100)


def before_trading_start(context, data):
    context.equity = symbol("AMZN")


if __name__ == '__main__':
    bundle_name = 'alpaca_api'
    bundle_data = bundles.load(bundle_name)

    with open("zipline-trader.yaml", mode='r') as f:
        o = yaml.safe_load(f)
        os.environ["APCA_API_KEY_ID"] = o["alpaca"]["key_id"]
        os.environ["APCA_API_SECRET_KEY"] = o["alpaca"]["secret"]
        os.environ["APCA_API_BASE_URL"] = o["alpaca"]["base_url"]
    broker = ALPACABroker()

    # Set the trading calendar
    trading_calendar = get_calendar('NYSE')

    start = pd.Timestamp(datetime(2020, 1, 1, tzinfo=pytz.UTC))
    end = pd.Timestamp.utcnow()

    run_algorithm(start=start,
                  end=end,
                  initialize=initialize,
                  handle_data=handle_data,
                  capital_base=100000,
                  benchmark_returns=get_benchmark(symbol="SPY",
                                                  start=start.date().isoformat(),
                                                  end=end.date().isoformat()),
                  bundle='alpaca_api',
                  broker=broker,
                  state_filename="./demo.state",
                  trading_calendar=trading_calendar,
                  before_trading_start=before_trading_start,
                  data_frequency='daily'
                  )

How to Report Bugs and Mistakes

No book is ever perfect and small mistakes are inevitable. We do all we can to correct the bugs and mistakes once we learn about them.

Steps:
1. Login to GitHub under your credentials
2. Open Issues · PacktPublishing/Hands-On-Financial-Trading-with-Python (github.com) and create a new issue

Book’s Errata and Updated Code

To be notified of any code’s changes, we recommend to “watch” the book’s GitHub repository.

Steps:
1. Login to GitHub under your credentials
2. Open PacktPublishing/Hands-On-Financial-Trading-with-Python: Hands-On Financial Trading with Python, published by Packt (github.com) in your browser
3. Click on Watch/Unwatch button on the top of the repository’s page


Book’s Table Of Contents

Author

keyboard_arrow_up