Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Python for Finance Cookbook
Python for Finance Cookbook

Python for Finance Cookbook: Over 50 recipes for applying modern Python libraries to financial data analysis

eBook
€23.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Python for Finance Cookbook

Technical Analysis in Python

In this chapter, we will cover the basics of technical analysis (TA) in Python. In short, TA is a methodology for determining (forecasting) the future direction of asset prices and identifying investment opportunities, based on studying past market data, especially the prices themselves and the traded volume.

We begin by introducing a simple way of visualizing stock prices using the candlestick chart. Then, we show how to calculate selected indicators (with hints on how to calculate others using selected Python libraries) used for TA. Using established Python libraries, we show how easy it is to backtest trading strategies built on the basis of TA indicators. In this way, we can evaluate the performance of these strategies in a real-life context (even including commission fees and so on).

At the end of the chapter, we also demonstrate how to create an interactive dashboard in Jupyter Notebook, which enables us to add and inspect the predefined TA indicators on the fly.

We present the following recipes in this chapter:

  • Creating a candlestick chart
  • Backtesting a strategy based on simple moving average
  • Calculating Bollinger Bands and testing a buy/sell strategy
  • Calculating the relative strength index and testing a long/short strategy
  • Building an interactive dashboard for TA

Creating a candlestick chart

A candlestick chart is a type of financial graph, used to describe a given security's price movements. A single candlestick (typically corresponding to one day, but a higher frequency is possible) combines the open, high, low, and close prices (OHLC). The elements of a bullish candlestick (where the close price in a given time period is higher than the open price) are presented in the following image (for a bearish one, we should swap the positions of the open and close prices):

In comparison to the plots introduced in the previous chapter, candlestick charts convey much more information than a simple line plot of the adjusted close price. That is why they are often used in real trading platforms, and traders use them for identifying patterns and making trading decisions.

In this recipe, we also add moving average lines (which are one of the most basic technical indicators), as well as bar charts representing volume.

Getting ready

In this recipe, we download Twitter's (adjusted) stock prices for the year 2018. We use Yahoo Finance to download the data, as described in the Getting data from Yahoo Finance recipe, found in Chapter 1, Financial Data and Preprocessing. Follow these steps:

  1. Import the libraries:
import pandas as pd 
import yfinance as yf
  1. Download the adjusted prices:
df_twtr = yf.download('TWTR', 
start='2018-01-01',
end='2018-12-31',
progress=False,
auto_adjust=True)

For creating the plot, we use the plotly and cufflinks libraries. For more details, please refer to the Visualizing time series data recipe, found in Chapter 1, Financial Data and Preprocessing.

How to do it...

Execute the following steps to create an interactive candlestick chart.

  1. Import the libraries:
import cufflinks as cf
from plotly.offline import iplot, init_notebook_mode

init_notebook_mode()
  1. Create the candlestick chart, using Twitter's stock prices:
qf = cf.QuantFig(df_twtr, title="Twitter's Stock Price", 
                 legend='top', name='TWTR')
  1. Add volume and moving averages to the figure:
qf.add_volume()
qf.add_sma(periods=20, column='Close', color='red')
qf.add_ema(periods=20, color='green')

  1. Display the plot:
qf.iplot()

We can observe the following plot (it is interactive in the notebook):

In the plot, we can see that the exponential moving average (EMA) adapts to the changes in prices much faster than the SMA. Some discontinuities in the chart are caused by the fact that we are using daily data, and there is no data for weekends/bank holidays.

How it works...

In Step 2, we created a QuantFig object by passing a DataFrame containing the input data, as well as some arguments for the title and legend's position. We could have created a simple candlestick chart by running the iplot method of QuantFig immediately afterward.

However, in Step 3, we also added two moving average lines by using the add_sma/add_ema methods. We decided to consider 20 periods (days, in this case). By default, the averages are calculated using the close column, however, we can change this by providing the column argument.

The difference between the two moving averages is that the exponential one puts more weight on recent prices. By doing so, it is more responsive to new information and reacts faster to any changes in the general trend.

See also

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Use powerful Python libraries such as pandas, NumPy, and SciPy to analyze your financial data
  • Explore unique recipes for financial data analysis and processing with Python
  • Estimate popular financial models such as CAPM and GARCH using a problem-solution approach

Description

Python is one of the most popular programming languages used in the financial industry, with a huge set of accompanying libraries. In this book, you'll cover different ways of downloading financial data and preparing it for modeling. You'll calculate popular indicators used in technical analysis, such as Bollinger Bands, MACD, RSI, and backtest automatic trading strategies. Next, you'll cover time series analysis and models, such as exponential smoothing, ARIMA, and GARCH (including multivariate specifications), before exploring the popular CAPM and the Fama-French three-factor model. You'll then discover how to optimize asset allocation and use Monte Carlo simulations for tasks such as calculating the price of American options and estimating the Value at Risk (VaR). In later chapters, you'll work through an entire data science project in the financial domain. You'll also learn how to solve the credit card fraud and default problems using advanced classifiers such as random forest, XGBoost, LightGBM, and stacked models. You'll then be able to tune the hyperparameters of the models and handle class imbalance. Finally, you'll focus on learning how to use deep learning (PyTorch) for approaching financial tasks. By the end of this book, you’ll have learned how to effectively analyze financial data using a recipe-based approach.

Who is this book for?

This book is for financial analysts, data analysts, and Python developers who want to learn how to implement a broad range of tasks in the finance domain. Data scientists looking to devise intelligent financial strategies to perform efficient financial analysis will also find this book useful. Working knowledge of the Python programming language is mandatory to grasp the concepts covered in the book effectively.

What you will learn

  • Download and preprocess financial data from different sources
  • Backtest the performance of automatic trading strategies in a real-world setting
  • Estimate financial econometrics models in Python and interpret their results
  • Use Monte Carlo simulations for a variety of tasks such as derivatives valuation and risk assessment
  • Improve the performance of financial models with the latest Python libraries
  • Apply machine learning and deep learning techniques to solve different financial problems
  • Understand the different approaches used to model financial time series data

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 31, 2020
Length: 432 pages
Edition : 1st
Language : English
ISBN-13 : 9781789617320
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jan 31, 2020
Length: 432 pages
Edition : 1st
Language : English
ISBN-13 : 9781789617320
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 102.97
Python for Finance Cookbook
€32.99
Python Algorithmic Trading Cookbook
€36.99
Mastering Python for Finance
€32.99
Total 102.97 Stars icon

Table of Contents

11 Chapters
Financial Data and Preprocessing Chevron down icon Chevron up icon
Technical Analysis in Python Chevron down icon Chevron up icon
Time Series Modeling Chevron down icon Chevron up icon
Multi-Factor Models Chevron down icon Chevron up icon
Modeling Volatility with GARCH Class Models Chevron down icon Chevron up icon
Monte Carlo Simulations in Finance Chevron down icon Chevron up icon
Asset Allocation in Python Chevron down icon Chevron up icon
Identifying Credit Default with Machine Learning Chevron down icon Chevron up icon
Advanced Machine Learning Models in Finance Chevron down icon Chevron up icon
Deep Learning in Finance Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(6 Ratings)
5 star 33.3%
4 star 50%
3 star 16.7%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




FieryHarrison Jan 28, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I could not put this book down. I read every page multiple times and have run every line of code. I have been a SAS programmer for 20+ years and have been slowly migrating to Python for my financial analysis. A handful of books over the years have stood the test of time for their usefulness in analytics. This is one of those books. Don't expect to be a chef coder of Michelin status with this cookbook but at least you will learn by doing and be well established to take your skills to another level. I loved that the book assumes analytical knowledge and focuses on the recipes. The where to go to find more information is extremely helpful. Thank you so much Eryk for your contribution. I look forward to buying all of your books!
Amazon Verified review Amazon
Jeweler24 Sep 28, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I work for a financial technology company and I was looking for a book to help me understand some of the work the teams were doing. I personally learn better by getting my hands dirty and writing code.This book covers a lot of topics and it does it in a way that lets you skip around and do it in any order that works for you. You don’t need to read it end to end, you can pick it up, read the chapter that you care about, and put it back on the shelf for when you need it again. Since the chapters are well written, and it is extremely easy and fun, and you probably won’t want to put it back on the shelf.I love the fact that all of the code is in python, and it gives lots of examples to get you started. Each one of the chapters gives you a starting point and you can easily customize the code to fit your given situation.While going through the book, I didn’t just learn how to solve some common financial problems, I also learned a lot about the different python libraries that there out there and what they are good for. Since there are a ton of libraries out there, having a resource like this that shows you which ones are good along with example code, saved me a lot of time and research doing that on my own.I highly recommend this book even if you don’t know python, it shouldn’t stop you, and by the end of the book you might just learn enough python to be dangerous.
Amazon Verified review Amazon
Robin T. Wernick Jun 03, 2021
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I liked the complete display of trading from trading centers. It certainly showed a quick way to make connections to two automated brokers.However, the calculations that supported the trading were completely hidden and if you want to make improvements, you are on your own.Some other book holds the secrets to tweaking the backtesting or holding the access to the complete list of instruments. So I took off a star for withholding critical data access from me.
Amazon Verified review Amazon
William J. Brown Feb 08, 2021
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I confess I often avoid Packt books because the quality is so variable, but Eryk Lewinson has provided us with an insightful and useful book. I also have the Hilpisch book and found it spent a lot of time teaching Python and didn't have a clear source for financial data, which was one of the reasons I bought the book.
Amazon Verified review Amazon
Matthew Sep 03, 2020
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
fastai 2.0 API changed lot. Some of classes and methods are gone.What's fastai version the book using?Thanks.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.