Python Stock Analysis — Candlestick Chart with Python and Plotly

Python Stock Analysis — Candlestick Chart with Python and Plotly

A candlestick chart is a very common and useful representation of stock prices. By looking into a candlestick chart, we can visually see the open, close, low and high price for any given stock.

In this article, I would like to show you how to use Python, Pandas and Plotly to build your own candlestick chart.

Photo by M. B. M. on Unsplash

We will start by importing all the required packages. We will need Pandas , Plotly , Json and requests. Requests and Json are needed to retrieve stock information from a free financial API F inancialmodelingprep .

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import requests
import json
quote = 'AAPL'days = 300def candlestick(quote,days):
r = requests.get(f'https://financialmodelingprep.com/api/v3/historical- price-full/{quote}?timeseries={days}')
r = r.json() return r

We pass as an argument of the get function the API endpoint url that we store in a variable named r . Then, we convert the API response to Json so that we Python can easily manipulate it with Python. The variable r will contain historical price data for any stock that we passed to our candlestick function. In above example, we have passed as parameters of our function ‘ AAPL ’ (i.e. Apple) and 300 days. Therefore, as a result, we get a list representing 300 data points. Each element in the list is a dictionary containing the information needed for our candlestick chart, that is, the open, high, low and close for each of the date s .

“symbol” : “AAPL”, “historical” : [ { “date” : “2015–01–20”, “open” : 107.84, “high” : 108.97, “low” : 106.5, “close” : 108.72, “volume” : 4.98999E7, “unadjustedVolume” : 4.98999E7, “change” : -0.88, “changePercent” : -0.816,....

When possible, I always like to convert my data into a Pandas DataFrame since it let me handle, operate and clean my data on a very easy and convenient manner. That is what we achieve with below two lines of code.

First, we parse our variable r to extract the value associated to the historical key and store it in a variable called stockdata . This way, we keep a list of dictionaries. Each dictionary contains stock price data for a single day. Then, we can simply convert the stockdata list to a Pandas DataFrame.

stockdata = r[‘historical’]
stockdata_df = pd.DataFrame(stockdata)

If we print out our Pandas Dataframe stockdata_df, we get something similar to below where each row represents a day and each column is giving us stock price information:

So far so good. Now, let’s move to the fun part. We can start building our chart with Plotly . Plotly is a very powerful graphing library. Very easy to use with Python and Pandas.

First of all, we need to create a fig object which will contain our data points. Within our Figure, we define our date, open, high, low and close. Each of the data points will be a column from our stockdata_df Pandas DataFrame. For example, open will contain the open price for each of the dates included in our Pandas DataFrame. Since, we passed in our function 300 days, open will contain the open stock price of Apple for the last 300 days.

Let’s also update the layout of our figure by using the Plotly fig.update_layout command to give some nice title to our chart, change the font and ensure that the the text is well positioned in the top center of the chart area.

Finally, we can use fig.show() to display the candlestick chart:

fig = go.Figure(data=[go.Candlestick(x=stockdata_df['date'],
                open=stockdata_df['open'],
                high=stockdata_df['high'],
                low=stockdata_df['low'],
                close=stockdata_df['close'])])fig.update_layout(
    title= {
        'text': quote,
      'y':0.9,
        'x':0.5,
        'xanchor': 'center',
        'yanchor': 'top'},
      font=dict(
        family="Courier New, monospace",
        size=20,
        color="#7f7f7f"
    )
    )fig.show()

And now magically, or rather because our coding skills, an impressive candlestick chart is displayed in front of us, including a slider to zoom in and out for any particular period of time. Try it out by your own!

Candlestick chart with Python and Plotly

I have included the whole script below for your reference. Just replace quote and days variables to select the desired stock and the number of days that you want to display in the chart.

Note: If you have any problems while running below code, ensure that you have all required libraries installed.

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import requests
import json
quote = ‘AAPL’
days = 300
def candlestick(quote,days):
r = requests.get(f’https://financialmodelingprep.com/api/v3/historical-price-full/{quote}?timeseries={days}')
r = r.json()

stockdata = r[‘historical’]
stockdata_df = pd.DataFrame(stockdata)

fig = go.Figure(data=[go.Candlestick(x=stockdata_df[‘date’],
open=stockdata_df[‘open’],
high=stockdata_df[‘high’],
low=stockdata_df[‘low’],
close=stockdata_df[‘close’])])
fig.update_layout(
title= {
‘text’: quote,
‘y’:0.9,
‘x’:0.5,
‘xanchor’: ‘center’,
‘yanchor’: ‘top’},
font=dict(
family=”Courier New, monospace”,
size=20,
color=”#7f7f7f”
))
fig.show()


candlestick(quote,days)
我来评几句
登录后评论

已发表评论数()

相关站点

热门文章