Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Python for Finance Cookbook

You're reading from   Python for Finance Cookbook Over 50 recipes for applying modern Python libraries to financial data analysis

Arrow left icon
Product type Paperback
Published in Jan 2020
Publisher Packt
ISBN-13 9781789618518
Length 432 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Eryk Lewinson Eryk Lewinson
Author Profile Icon Eryk Lewinson
Eryk Lewinson
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Financial Data and Preprocessing 2. Technical Analysis in Python FREE CHAPTER 3. Time Series Modeling 4. Multi-Factor Models 5. Modeling Volatility with GARCH Class Models 6. Monte Carlo Simulations in Finance 7. Asset Allocation in Python 8. Identifying Credit Default with Machine Learning 9. Advanced Machine Learning Models in Finance 10. Deep Learning in Finance 11. Other Books You May Enjoy

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

You have been reading a chapter from
Python for Finance Cookbook
Published in: Jan 2020
Publisher: Packt
ISBN-13: 9781789618518
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image