Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
QuantConnect
GitHub Repository: QuantConnect/Research
Path: blob/master/Documentation/Python/Plotting-Price-Data-Using-Plotly.ipynb
984 views
Kernel: Python 3

QuantConnect Logo


Visualizing Data with Plotly

Line Charts, Candlestick Charts, Bar Charts, and Heat Maps

Import Libraries

Let's start by importing the libraries we need.

import plotly.express as px import plotly.graph_objects as go

Visualizing SPY

We will visualize SPY using a time-series line chart and a candlestick chart.

Gathering Data

To begin, we retrieve daily close data for SPY.

qb = QuantBook() spy = qb.AddEquity("SPY") history = qb.History(qb.Securities.Keys, 360, Resolution.Daily) spy_hist = history.loc['SPY'] spy_hist

SPY Time-Series Line Chart

We reset the index of the DataFrame so that it is easier to use with plotly.

spy_hist2 = spy_hist.reset_index() fig = px.line(spy_hist2, x='time', y='high') fig.show()

SPY Candlesticks

fig = go.Figure(data=[go.Candlestick(x=spy_hist.index, open=spy_hist['open'], high=spy_hist['high'], low=spy_hist['low'], close=spy_hist['close'])], layout=go.Layout( title=go.layout.Title(text='SPY OHLC'), xaxis_title='Date', yaxis_title='Price', xaxis_rangeslider_visible=False )) fig.show()

Visualizing the Correlation Between GLD and BAR Returns

GLD and BAR are two different Gold-tracking ETFs, and we would like to visualize their correlation. To do this, we will employ a scatter plot of their returns.

Gathering Data

First, we get daily close data for GLD and BAR, and call pct_change() on the DataFrames to get daily returns.

qb.AddEquity('GLD') qb.AddEquity('BAR') gold_etf_hist = qb.History(['GLD', 'BAR'], 300, Resolution.Daily) gld_ret = gold_etf_hist.loc['GLD']['close'].pct_change()[1:] bar_ret = gold_etf_hist.loc['BAR']['close'].pct_change()[1:]

Now, we can plot the daily returns of GLD vs the daily returns of BAR. We include a trendline by specifying a trendline key word argument, and setting to OLS, which is the most common way to calculate a trend line.

fig = px.scatter(x=gld_ret, y=bar_ret, trendline='ols', labels={'x': 'GLD', 'y': 'BAR'}) fig.update_layout(title='GLD vs BAR Daily % Returns') fig.show()

Visualizing the Average Daily Percent Returns of Banking Stocks

We use a bar chart to compare the average daily percent returns of various banking stocks.

Gathering Data

First, we get historical closing prices for four banking sector stocks, then compute the average daily return for each stock.

banking_tickers = [ "COF", # Capital One Financial Corporation "JPM", # J P Morgan Chase & Co "STI", # SunTrust Banks, Inc. "WFC", # Wells Fargo & Company ] for ticker in banking_tickers: qb.AddEquity(ticker) banking_hist = qb.History(banking_tickers, 300, Resolution.Daily) banking_close = banking_hist.unstack(level=0)['close'] banking_avg_daily_ret = pd.DataFrame() banking_avg_daily_ret['avg_daily_ret'] = banking_close.pct_change().dropna().apply(lambda x: x.mean(), axis=0) # reset_index() is necessary because plotly only uses columns banking_avg_daily_ret = banking_avg_daily_ret.reset_index()

With the average daily returns for each stock, we can now create our bar chart to compare these values.

fig = px.bar(banking_avg_daily_ret, x='symbol', y='avg_daily_ret') fig.update_layout(title='Banking Stocks Average Daily % Returns')

Visualizing Correlations Between Banking Stocks

Correlations between stocks in the same sector are commonly applied to develop pairs trading strategies. We will visualize the correlations between a few stocks in the banking sector using a heat map.

Gathering Data

First, we get historical closing prices for four banking sector stocks.

Before we create the heat map, we must create a correlation matrix, which has all the correlations between all possible pairs of symbols. This can be easily done with pandas DataFrame's built-in corr() method.

corr_matrix = banking_close.corr() corr_matrix

With the correlation matrix, we are ready to create a heat map.

px.imshow(corr_matrix, x=banking_tickers, y=banking_tickers)