[Time series with plotly] Dynamic visualization with plotly [python, stock price]

I will muzzle the time series

c.gif

environment

python==3.8 plotly==4.10.0

Time series visualization using plotly

Preprocessing of time series data is difficult, but beautiful visualization is just as difficult.

If there is a strange peak in the time series visualization, ・ What month and day was it? ・ If it is abnormal, can you refer to the comment at that time? ・ Is it possible to expand or change the scale a little more? Will occur

It's hard to go to the source data side each time, but with plotly dynamic visualization It ’s easy to identify what month and day it is. It is also possible to narrow down to a specific period and expand to only half-year orders

First line plot

Try using plotly line plot

import plotly.express as px
fig = px.line(x=[1,2,3,4,5], y=[10,11,15,16,8], title="line plot")
fig.show()

image.png

Ordinary linear plot

Try using stock price data that can be called from plotly datasets

image.png

import plotly.express as px
import pandas as pd
df = px.data.stocks()
fig = px.line(df,x='date', y='NFLX', title="NFLX stocks plot")
fig.show()

If the date is entered in a recognizable format, it will be set to the time by specifying it on the X axis.

image.png

Range to specify the display period

import plotly.express as px
import pandas as pd
df = px.data.stocks()
fig = px.line(df,x='date', y='NFLX', title="NFLX stocks plot", range_x=['2018-07-01','2019-12-31'])
fig.show()

image.png

Specify multiple Y-axis

import plotly.express as px
import pandas as pd
df = px.data.stocks()
fig = px.line(df,x='date', y=df.columns[1:6], title="6 company stocks plot")
fig.show()

image.png

Change the scale interval

import plotly.express as px
import pandas as pd
df = px.data.stocks()
fig = px.line(df,x='date', y=df.columns[1:6], title="6 company stocks plot")
fig.update_xaxes(
    dtick="M1",
    tickformat="%b\n%Y")
fig.show()

image.png

〇 Pass the month break to dtick with M 〇 The format of the scale label can be passed in character type, and the display format can be changed using line feed symbols, etc.

For example

fig.update_layout(
    title="6 company stocks plot",
    xaxis_tickformat = '%d %B (%a)<br>%Y'
)

If you specify as, you can operate the display of the day of the week and the date

image.png

Change the behavior when hovering the mouse

Normally, you can refer to one point of information by hovering the mouse, but You can also change the layout to display information for all data

Normal case

a.gif

import plotly.express as px
import pandas as pd
df = px.data.stocks()
fig = px.line(df,x='date', y=df.columns[1:6], title="6 company stocks plot")
fig.update_xaxes(
    dtick="M1",
    tickformat="%b\n%Y")

fig.update_layout(template=go.layout.Template())

fig.show()

b.gif

Range selector that makes the display section interactive

By using update_layout, you can add a function to specify the display section in the graph put in the fig. Applicable to both go.Figure and plotly.express Convenient because you can copy and use it

Add to graph_objects

import plotly.graph_objects as go
import pandas as pd

fig = go.Figure()

fig.add_trace(go.Scatter(x=list(df.date), y=list(df.GOOG)))

fig.update_layout(
    title_text="range slider and selectors"
)

fig.update_layout(
    xaxis=dict(
        rangeselector=dict(
            buttons=list([
                dict(count=1,
                     label="1m",
                     step="month",
                     stepmode="backward"),
                dict(count=6,
                     label="6m",
                     step="month",
                     stepmode="backward"),
                dict(count=1,
                     label="YTD",
                     step="year",
                     stepmode="todate"),
                dict(count=1,
                     label="1y",
                     step="year",
                     stepmode="backward"),
                dict(step="all")
            ])
        ),
        rangeslider=dict(
            visible=True
        ),
        type="date"
    )
)

fig.show()

Add to plotly.express

import plotly.express as px
fig = px.line(df,x='date', y=df.columns[1:6])

fig.update_layout(
    title_text="range slider and selectors"
)

fig.update_layout(
    xaxis=dict(
        rangeselector=dict(
            buttons=list([
                dict(count=1,
                     label="1m",
                     step="month",
                     stepmode="backward"),
                dict(count=6,
                     label="6m",
                     step="month",
                     stepmode="backward"),
                dict(count=1,
                     label="YTD",
                     step="year",
                     stepmode="todate"),
                dict(count=1,
                     label="1y",
                     step="year",
                     stepmode="backward"),
                dict(step="all")
            ])
        ),
        rangeslider=dict(
            visible=True
        ),
        type="date"
    )
)

fig.show()

c.gif

plot using scatter

import plotly.express as px
fig = px.scatter(df,x=df['date'], y=df.columns[1:6])
fig.show()

image.png

plot using graph_objects


import plotly.graph_objects as go

fig = go.Figure([
    go.Scatter(
        x=df['date'], y=df[df.columns[i]],
        opacity=.5
    )
    for i in range(1,len(df.columns))
])

fig.show()

image.png

graph_objects is good at drawing like adding to the campus from above Add go.scatter to the canvas created with go.Figure This time I added go.scatter 5 times while changing the column with for, You can add them individually with add_trace In that case, some lines can be broken lines and some lines can be solid lines.

The following is a change of line type

import plotly.graph_objects as go

fig = go.Figure([
    go.Scatter(
        x=df['date'], y=df[df.columns[i]], 
        opacity=.5, 
        line=dict(dash='dash')
    )
    for i in range(1,len(df.columns))
])

fig.show()

image.png

Stock price candle chart

You can easily make a candle chart by specifying the opening price; high price; low price; closing price of the stock price.

import plotly.graph_objects as go
import pandas as pd
from datetime import datetime

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

fig = go.Figure(data=[go.Candlestick(x=df['Date'],
                open=df['AAPL.Open'],
                high=df['AAPL.High'],
                low=df['AAPL.Low'],
                close=df['AAPL.Close'])])

fig.update_layout(
    title_text="Candle"
)

fig.update_layout(
    xaxis=dict(
        rangeselector=dict(
            buttons=list([
                dict(count=1,
                     label="1m",
                     step="month",
                     stepmode="backward"),
                dict(count=6,
                     label="6m",
                     step="month",
                     stepmode="backward"),
                dict(count=1,
                     label="YTD",
                     step="year",
                     stepmode="todate"),
                dict(count=1,
                     label="1y",
                     step="year",
                     stepmode="backward"),
                dict(step="all")
            ])
        ),
        rangeslider=dict(
            visible=True
        ),
        type="date"
    )
)

fig.show()

image.png

that's all

It's great to be able to see the values

Recommended Posts

[Time series with plotly] Dynamic visualization with plotly [python, stock price]
[Various image analysis with plotly] Dynamic visualization with plotly [python, image]
[Write to map with plotly] Dynamic visualization with plotly [python]
Get stock price with Python
"Getting stock price time series data from k-db.com with Python" Program environment creation memo
Download Japanese stock price data with python
[Talking about the drawing structure of plotly] Dynamic visualization with plotly [python]
Get stock price data with Quandl API [Python]
Let's do web scraping with Python (stock price)
Python: Time Series Analysis
Python time series question
Logistics visualization with Python
Create an animated time series map of coronavirus infection status with python + plotly
Visualize Prophet's time series forecasts more clearly with Plotly
Execution time measurement with Python With
Python: Stock Price Forecast Part 2
[Python] Plot time series data
Time synchronization (Windows) with Python
Python: Stock Price Forecast Part 1
Programming history 1 month Extract NY Dow stock price with Python!
I made a package to filter time series with python
Easy time series prediction with Prophet
Python: Time Series Analysis: Preprocessing Time Series Data
Dynamic proxy with python, ruby, PHP
[Python] My stock price forecast [HFT]
Time series plot started ~ python edition ~
Get US stock price from Python with Web API with Raspberry Pi
Easy data visualization with Python seaborn.
[Capacity indicator, Gantt chart, UI] Plotly dynamic visualization [python, gauge display, Gantt chart]
Data analysis starting with python (data visualization 1)
Data analysis starting with python (data visualization 2)
[Visualization of ratio] Plotly and dynamic visualization [python, pie, sunburst, sanky, treemap, fannele,]
Plot CSV of time series data with unixtime value in Python (matplotlib)
[Density visualization] Plotly and dynamic visualization [python3, hist, kde, join, contour, heat map]
Forecasting time series data with Simplex Projection
Predict time series data with neural network
Check stock prices with slackbot using python
[Python] Accelerates loading of time series CSV
Web scraping with Python ② (Actually scraping stock sites)
Stock Price Forecast with TensorFlow (LSTM) ~ Stock Forecast Part 1 ~
[Python] Creating a stock price drawdown chart
Recommendation of Altair! Data visualization with Python
Text mining with Python ② Visualization with Word Cloud
Format and display time series data with different scales and units with Python or Matplotlib
[Drawing and labeling multiple graphs] Plotly dynamic visualization [python3, make subplot, xlabel, ylabel]
[EDA super basic] Plotly and dynamic visualization [python3, table, bar, box, violin, joy]
[Scatter plot, 3D plot and regression plane] Plotly dynamic visualization [python, scatter, 3D, surface, pair, joint]
Get the stock price of a Japanese company with Python and make a graph
Convenient time series aggregation with TimeGrouper in pandas
Python: Time Series Analysis: Building a SARIMA Model
[Python3] A story stuck with time zone conversion
Python: Time Series Analysis: Stationarity, ARMA / ARIMA Model
Acquisition of time series data (daily) of stock prices
Use logger with Python for the time being
How to measure execution time with Python Part 1
View details of time series data with Remotte
Automatic acquisition of stock price data with docker-compose
Python & Machine Learning Study Memo ⑦: Stock Price Forecast
How to measure execution time with Python Part 2
✨ Easy with Python ☆ Estimated elapsed time after death ✨
Reading, summarizing, visualizing, and exporting time series data to an Excel file with Python