[PYTHON] Candle chart plot with plotly

Preparation

Creating sample data

np.random.seed(9)
from randomwalk import randomwalk
df = randomwalk(60 * 24 * 90, freq='T', tick=0.01, start=pd.datetime(2017, 3, 20)
                ).resample('B').ohlc() + 115  #Convert 90-day 1-minute bar to daily bar

Random walk creation. For details, see Drawing a candle chart with python.

Convert pd.DataFrame type to StockDataFrame type

from stockstats import StockDataFrame
sdf = StockDataFrame(df.copy())

How to use the StockPlot class

Import stockplot.py

from stockplot import StockPlot
#Instantiation of StockPlot class
x = StockPlot(sdf)
#Candle chart plot
x.candle_plot()

graph1.png

A candle chart was drawn.

plotly basically spits out images in html format. When you mouse over, the value is displayed and you can zoom in / out. Since it was troublesome to create a gif file, I am pasting it in png format here.

If you want to see a graph that can be moved around with plotly, please see here for reference.

Qiita --inoory-- [Python] Make a graph that can be moved around with Plotly

index

Addition of indicators

To add an index, use the ʻappend` method as in the list type.

#25th closing price moving average added
x.append('close_25_sma')
2017-03-20    114.850000
2017-03-21    114.805000
2017-03-22    114.886667
2017-03-23    114.912500
2017-03-24    114.912000
2017-03-27    114.940000
2017-03-28    115.010000
2017-03-29    115.016250
2017-03-30    115.062222
2017-03-31    115.063000
2017-04-03    115.066364
2017-04-04    115.082500
2017-04-05    115.093846
2017-04-06    115.075714
2017-04-07    115.093333
2017-04-10    115.111250
2017-04-11    115.097059
2017-04-12    115.071111
2017-04-13    115.041579
2017-04-14    115.037000
2017-04-17    115.039048
2017-04-18    115.047273
2017-04-19    115.042609
2017-04-20    115.075417
2017-04-21    115.117200
2017-04-24    115.165600
2017-04-25    115.194000
2017-04-26    115.216800
2017-04-27    115.247600
2017-04-28    115.262800
                 ...    
2017-05-08    115.319600
2017-05-09    115.306800
2017-05-10    115.313600
2017-05-11    115.328400
2017-05-12    115.315600
2017-05-15    115.297600
2017-05-16    115.297600
2017-05-17    115.314800
2017-05-18    115.337600
2017-05-19    115.330000
2017-05-22    115.317200
2017-05-23    115.296000
2017-05-24    115.308800
2017-05-25    115.302000
2017-05-26    115.282800
2017-05-29    115.256800
2017-05-30    115.254000
2017-05-31    115.238000
2017-06-01    115.245200
2017-06-02    115.272800
2017-06-05    115.289600
2017-06-06    115.318400
2017-06-07    115.366000
2017-06-08    115.425600
2017-06-09    115.508400
2017-06-12    115.579200
2017-06-13    115.636800
2017-06-14    115.686800
2017-06-15    115.736000
2017-06-16    115.798000
Freq: B, Name: close_25_sma, dtype: float64

The return value of the ʻadd_indicator function is the same as when using the getmethod in theStockDataFrame` class.

Behind the scenes, it is converted to plotly format and added to the instance variable self._fig.

#Candle chart and plot of added indicators
x.candle_plot()

graph2.png

A 25-day moving average closing price has been added.

#25-day closing price Addition and plotting of moving averages
x.append('close_25_ema')
x.candle_plot()

graph3.png

In addition to the 25-day closing price moving average added earlier, the 25-day closing index moving average has been added.

Delete indicator

To remove an indicator, use the'remove'method in the same way as removing a list.

y = StockPlot(sdf)
# 10,11,12,13-legged moving average
for i in range(10, 14):
    y.append('close_{}_sma'.format(i))
y.candle_plot()

graph4.png

We created a new instance and added 10, 11, 12, 13 bar moving averages.

Although omitted here, the remove return value is the column of the removed StockDataFrame.

# 10,Removal of 12-legged moving average
for i in (10, 12):
    y.remove('close_{}_sma'.format(i))
y.candle_plot()

graph5.png

Only the 10-leg and 12-leg moving averages were specified and deleted.

Export to file

The StockPlot class spits out diagrams in Plotly's html export plotly.offline.iplot (Jupyter Notebook format). That is, it will not be exported to a file.

If you want to spit it out as a file, use the following method.

import plotly.offline as pyo
pyo.plot(y._fig, filename='candle_y.html', validate=False)  #Open a new tab and display html
pyo.plot(y._fig, image='png', image_filename='candle_y')
#Open a new tmp tab
#As the extension specified for image
#Save to the default download directory

Package introduction

Plotly

Let Plotly do the graph drawing. If it's easy, you can use it for free.

Installation is

conda install plotly

Or

pip install plotly

I don't mention it here because I think it's famous.

stockstats Data manipulation uses a package called stockstats.

Installation is

pip install stockstats

stockstats is a modified pandas.DataFrame class that makes it easy to get financial indicators.

#How to use
np.random.seed(2)
df = pd.DataFrame(np.random.randn(10,4), columns=['open', 'high', 'low', 'close'])
from stockstats import StockDataFrame
sdf = StockDataFrame(df)  #Put the pandas dataframe in StockDataFrame
sdf
open high low close
0 -0.416758 -0.056267 -2.136196 1.640271
1 -1.793436 -0.841747 0.502881 -1.245288
2 -1.057952 -0.909008 0.551454 2.292208
3 0.041539 -1.117925 0.539058 -0.596160
4 -0.019130 1.175001 -0.747871 0.009025
5 -0.878108 -0.156434 0.256570 -0.988779
6 -0.338822 -0.236184 -0.637655 -1.187612
7 -1.421217 -0.153495 -0.269057 2.231367
8 -2.434768 0.112727 0.370445 1.359634
9 0.501857 -0.844214 0.000010 0.542353

There is no change in appearance, but if you get the financial indicator by the get method or dictionary according to the grammar of stockstats, the column of financial indicator will be added.

sdf.get('close_5_sma'); sdf
open high low close close_5_sma
0 -0.416758 -0.056267 -2.136196 1.640271 1.640271
1 -1.793436 -0.841747 0.502881 -1.245288 0.197491
2 -1.057952 -0.909008 0.551454 2.292208 0.895730
3 0.041539 -1.117925 0.539058 -0.596160 0.522758
4 -0.019130 1.175001 -0.747871 0.009025 0.420011
5 -0.878108 -0.156434 0.256570 -0.988779 -0.105799
6 -0.338822 -0.236184 -0.637655 -1.187612 -0.094264
7 -1.421217 -0.153495 -0.269057 2.231367 -0.106432
8 -2.434768 0.112727 0.370445 1.359634 0.284727
9 0.501857 -0.844214 0.000010 0.542353 0.391392

close_5_sma: A 5-bar moving average of the closing price has been added.

sdf['close_5_sma']; sdf
open high low close close_5_sma
0 -0.416758 -0.056267 -2.136196 1.640271 1.640271
1 -1.793436 -0.841747 0.502881 -1.245288 0.197491
2 -1.057952 -0.909008 0.551454 2.292208 0.895730
3 0.041539 -1.117925 0.539058 -0.596160 0.522758
4 -0.019130 1.175001 -0.747871 0.009025 0.420011
5 -0.878108 -0.156434 0.256570 -0.988779 -0.105799
6 -0.338822 -0.236184 -0.637655 -1.187612 -0.094264
7 -1.421217 -0.153495 -0.269057 2.231367 -0.106432
8 -2.434768 0.112727 0.370445 1.359634 0.284727
9 0.501857 -0.844214 0.000010 0.542353 0.391392

Exactly the same as sdf.get ('close_5_sma'). No error occurs when get typed an impossible index. Which one is better depends on the application.

The indicators that can be used as indicators are as follows.

Please see the official for details.

stockplot

This is the one I made. I have created a class StockPlot to easily plot stockstats.

Source code for stockplot.py

import numpy as np
import pandas as pd
# ----------User Module----------
from randomwalk import randomwalk
import stockstats as ss
# ----------Plotly Module----------
from plotly.tools import FigureFactory as FF
import plotly.offline as pyo
import plotly.graph_objs as go
pyo.init_notebook_mode(connected=True)


class StockPlot:
    """StockDataFrame visualization tool
    # TODO
    * heikin_plot
    * pop
    * subplot
    """

    def __init__(self, sdf: ss.StockDataFrame):
        self.StockDataFrame = sdf
        self._fig = FF.create_candlestick(self.StockDataFrame.open,
                                         self.StockDataFrame.high,
                                         self.StockDataFrame.low,
                                         self.StockDataFrame.close,
                                         dates=self.StockDataFrame.index)

    def candle_plot(self, filebasename='candlestick_and_trace'):
        """Make a StockDataFrame into a candle chart
argument: dfs: StockDataFrame
Return value: plotly plot"""
        self._fig['layout'].update(xaxis={'showgrid': True})
        ax = pyo.iplot(self._fig, filename=filebasename + '.html', validate=False)
        # pyo.plot(self._fig, image='png', image_filename=filebasename, validate=False)
        return ax

    def append(self, indicator):
        indi = self.StockDataFrame.get(indicator)
        plotter = go.Scatter(x=indi.index, y=indi,
                             name=indicator.upper().replace('_', ' '))  #Format conversion to add to the graph
        self._fig['data'].append(plotter)
        return indi

    def remove(self, indicator):
        indi = indicator.lower().replace(' ', '_')
        INDI = indicator.upper().replace('_', ' ')
        rem = self.StockDataFrame.pop(indi)
        for dicc in self._fig['data']:
            if dicc['name'] == INDI:
                self._fig['data'].remove(dicc)
                return rem

github u1and0/stockplot

NEXT Make a currency chart that can be moved around with Plotly (1)

Recommended Posts

Candle chart plot with plotly
Candlestick with plotly + Jupyter
2-axis plot with Matplotlib
3D display with plotly
3D plot with matplotlib
Create graph with plotly button
3D scatter plot with PyQtGraph
Stackable bar plot with matplotlib
Make a currency chart that can be moved around with Plotly (2)
Make a currency chart that can be moved around with Plotly (1)
Create plot animation with Python + Matplotlib
Publish nice graphs online with plotly
Candlestick chart and moving average plot
Continuously color with matplotlib scatter plot
Make a nice graph with plotly
Lognormal probability plot with Python, matplotlib
Application of graphs with plotly sliders