Visualizing Stock Market data in Python

Harinath Selvaraj
coding&stuff
Published in
3 min readFeb 11, 2019

This article will give you step by step information on how to obtain stock data and create the famous candlestick visualisation using Python and a library called Bokeh

Step 1 — Getting access to free Stock Trading Data

Although there are many companies who provide stock data for a small cost, alpha advantage provides free use of their API to obtain the data. In order to access them, you need to obtain the API Key here. Copy the generated API key as you would need it in the later steps.

Step 2 — Writing Python code to pull the data using API

The below code pulls the daily trading data for the stock — Apple (Code: AAPL). In case you wanted to look at the codes for other companies, go to Yahoo Finance and search the company name in the ‘Quote Lookup’ search bar located at top of the page.

In the below code, instead of <Your-API-Key>, use the API key obtained from step 1.

Bokeh library can be installed using the below command,

pip install bokeh

The print command present in the below code should always return value ‘200’ which denotes that the API call was successful.

#Importing Librariesimport requests
import pandas as pd
import datetime
from bokeh.plotting import figure, show, output_file
#Code to obtain trade data for AAPLAPI_KEY = '<Your-API-Key>'
stock_name = 'AAPL'
r = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' + stock_name + '&apikey=' + API_KEY)
print(r.status_code)
result = r.json()
dataForAllDays = result['Time Series (Daily)']

APIs are also available to pull Intraday, Weekly & Monthly data. Additional information on how to use those APIs can be found here.

Step 3 — Modifying the column names & their positions for feeding into the visualization.

The below code converts python dictionary, ‘dataForAllDays’ into a dataframe, ‘df’ and does few changes for the data visualizations.

#convert to dataframe
df = pd.DataFrame.from_dict(dataForAllDays, orient='index')
df = df.reset_index()
#rename columns
df = df.rename(index=str, columns={"index": "date", "1. open": "open", "2. high": "high", "3. low": "low", "4. close": "close","5. volume":"volume"})
#Changing to datetime
df['date'] = pd.to_datetime(df['date'])
#Sort according to date
df = df.sort_values(by=['date'])
#Changing the datatype
df.open = df.open.astype(float)
df.close = df.close.astype(float)
df.high = df.high.astype(float)
df.low = df.low.astype(float)
df.volume = df.volume.astype(int)
#check the data
df.head()
#Check the datatype
df.info()

Step 4 — Display visualization using Bokeh

The below commands should display the visualization in a new browser tab.

inc = df.close > df.open
dec = df.open > df.close
w = 12*60*60*1000 # half day in ms
TOOLS = "pan,wheel_zoom,box_zoom,reset,save"title = stock_name + ' Chart'
p = figure(x_axis_type="datetime", tools=TOOLS, plot_width=1000, title = title)
p.xaxis.major_label_orientation = pi/4
p.grid.grid_line_alpha=0.3
p.segment(df.date, df.high, df.date, df.low, color="black")
p.vbar(df.date[inc], w, df.open[inc], df.close[inc], fill_color="#D5E1DD", line_color="black")
p.vbar(df.date[dec], w, df.open[dec], df.close[dec], fill_color="#F2583E", line_color="black")
#Store as a HTML file
output_file("stock_information.html", title="candlestick.py example")
# Display in browser
show(p)

Output

Stock data visualization using Bokeh Candlestick Chart

In the output visualization, you can also zoom in a particular date period to have a closer look at the stock performance.

In the upcoming posts, I will be writing on how to implement write your own Algo Trading program ie) automating buying or selling stocks using Python

Please give me a clap if you liked my post!

Happy reading 😄

--

--