Plotly is a stock trading visualization

This is the 7th installment of Plotly, which explains how to use Plotly to plot graphs related to the stock market, such as the basic K-chart, OHLC chart, etc.

⚠️ : There are risks in the stock market, so be careful with your investments. This doesn’t prevent you from learning Plotly.

Further reading

The First six Plotly visualization articles will be serialized as follows:

  • Cool! Love advanced visualization artifact Plotly_Express
  • Plotly play scatter chart
  • Plotly plays a pie chart
  • Plotly plays a funnel
  • Plotly play bar chart
  • Plotly play bubble chart

Import libraries

import pandas as pd
import numpy as np

# Two interfaces
import plotly_express as px
import plotly.graph_objects as go
Copy the code

The stock figure

Here are two stock market charts:

  • K line graph
  • OHLC figure

K line graph

K line by the opening price, the closing price, the highest price, the lowest price of four prices. An opening price below the closing price is called a positive line, and vice versa.

The rectangle in the middle is called the solid, the thin line above the solid is called the shadow line, and the thin line below the solid is called the shadow line.

1. Red rising:

2, green down

3. Flat state

According to the calculation period of K line, it can be divided into: day K line, week K line, month K line, year K line

OHLC charts

An excerpt from a Wikipedia introduction:

Us line **(English: Open-high-low-close chart, OHLC Chart) shows the changes of stock prices by vertical lines, which can present “opening price, High price, Low price and Close price”. Vertical lines show the price difference between the highest price and the lowest price. The horizontal line on the left represents the opening price and the horizontal line on the right represents the closing price

Map OHLC

The drawing data

Some of the graphs in this article are based on the apple (AAPL) stock data stored in Plotly

# Read the online CSV file

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df.head()  Display the first 5 rows of data
Copy the code

The data size is:

df.shape

# the results
(506.11)
Copy the code

All fields are:

df.columns

# the results
Index(['Date'.'AAPL.Open'.'AAPL.High'.'AAPL.Low'.'AAPL.Close'.'AAPL.Volume'.'AAPL.Adjusted'.'dn'.'mavg'.'up'.'direction'],
      dtype='object')
Copy the code

Based on drawing

# The 'close' property is an array that may be specified as a tuple, list, numpy array, or pandas Series

fig = go.Figure(data=go.Ohlc(
    x=df['Date'].open=df['AAPL.Open'].The field data must be tuples, lists, NUMPY arrays, or Series data for pandas
    high=df['AAPL.High'],
    low=df['AAPL.Low'],
    close=df['AAPL.Close']
))

fig.update(layout_xaxis_rangeslider_visible=False)

fig.show()
Copy the code

Add text information and remarks

fig = go.Figure(data=go.Ohlc(
    x=df['Date'].# Date and four sets of data
    open=df['AAPL.Open'],
    high=df['AAPL.High'],
    low=df['AAPL.Low'],
    close=df['AAPL.Close']
))

fig.update_layout(
    title="Apple stock chart.".# titles
    yaxis_title="Stock price".# Y-axis name
    shapes = [dict(  # display shape position and line width
        x0='2015-06-01', x1='2016-05-13'.The value of # x
        y0=0, y1=1.The value of y
        xref='x', yref='paper',
        line_width=2)],
    annotations=[dict(   # Note information
        x='2015-06-01', y=0.05, 
        xref='x', yref='paper',
        showarrow=False, 
        xanchor='left', 
        text='Descent stage')]
)

fig.show()
Copy the code

The selected sections and remarks in the box are added in the figure above

Custom colors

The graph above is Plotly’s colors: up is red, down is green, and below is Plotly’s blue

fig = go.Figure(data=[go.Ohlc(
    x=df['Date'].# date
    open=df['AAPL.Open'].# 4 sets of data
    high=df['AAPL.High'],
    low=df['AAPL.Low'], 
    close=df['AAPL.Close'],
    increasing_line_color= 'blue'.# Uptrend color
    decreasing_line_color= 'green'  # Downtrend color
)])

fig.show()
Copy the code

OHLC chart for specific date

The graphics above are OHLC graphics of continuous date (based on month). The following is how to draw OHLC graphics of specific dates

How to generate a datetime object
import plotly.graph_objects as go
from datetime import datetime

datetime(year=2013, month=10, day=10)   
Copy the code

# 4 pieces of data to draw
open_data = [133.0.133.3.133.5.133.0.134.1]
high_data = [133.1.133.3.133.6.133.2.134.8]
low_data = [132.7.132.7.132.8.132.6.132.8]
close_data = [133.0.132.9.133.3.133.1.133.1]

# draw 5 dates: specify year, month, day
dates = [datetime(year=2019, month=10, day=10),
         datetime(year=2019, month=11, day=10),
         datetime(year=2019, month=12, day=10),
         datetime(year=2020, month=1, day=10),
         datetime(year=2020, month=2, day=10)]

# drawing: Incoming time and data
fig = go.Figure(data=[go.Ohlc(
    x=dates,
    open=open_data, 
    high=high_data,
    low=low_data, 
    close=close_data)])

fig.show()
Copy the code

Added hover message hoverText

Hover information refers to the fact that the data itself cannot be seen in the graph. When we move the cursor over the graph, we can see the corresponding data.

Take apple’s stock numbers again:

hovertext=[]  # add hover information

for i in range(len(df['AAPL.Open')) :# < br > said
    hovertext.append('Open: '+str(df['AAPL.Open'][i])+'<br>Close: '+str(df['AAPL.Close'][i]))

# Result representation
['Open: < br > 127.489998 Close: 127.830002'.'Open: < br > 127.629997 Close: 128.720001'.'Open: < br > 128.479996 Close: 128.449997']
Copy the code

The red part of the figure above is the hover information

Based on time series

The drawing data

Here is how to draw a stock graph based on a time series, using Plotly stock data:

stocks = px.data.stocks()
stocks.head()  Display the first 5 rows of data
Copy the code

The first field is the date and time, and the rest are different company names: Google, Apple, Amazon, and so on

Implementation based on PX

We use Plotly_Express to realize the drawing of basic graphics, and the company selected is FB: Facebook

# Plot the stock trend of FB

fig = px.line(
    stocks,
    x='date',
    y='FB'
)

fig.update_layout(title={
    'text':'Facebook stock trend '.'x':0.52.'y':0.96.'xanchor':'center'.'yanchor':'top'
})

fig.show()
Copy the code

Implementation based on GO

The following is based on the GO method:

import pandas as pd
import numpy as np

# Two interfaces
import plotly_express as px
import plotly.graph_objects as go

# based on the go
fig = go.Figure([go.Scatter(
    x=stocks['date'], 
    y=stocks['FB'])])

fig.update_layout(title={
    'text':'Facebook stock trend '.'x':0.52.'y':0.96.'xanchor':'center'.'yanchor':'top'
})

fig.show()
Copy the code

Shared timeline

import plotly.express as px

stock = px.data.stocks(indexed=True) - 1  Subtract 1 from the original number
stock.head()
Copy the code

fig = px.bar(
  stock,  # data
  x=stock.index,  # x
  y="GOOG"  # y
)

fig.show()
Copy the code

Polyhedral maps share a timeline

fig = px.area(
    stock,
    facet_col="company".Display different elements according to the formula
    facet_col_wrap=3   # Number of graphics displayed per line
)

fig.show()
Copy the code

Change parameters to display 2 figures per line:

fig = px.area(
    stock,
    facet_col="company",
    facet_col_wrap=2   # Number of graphics displayed per line
)

fig.show()
Copy the code

Label Indicates the Label personality

fig = px.line(
    df4,   # Drawing data
    x="date".# X-axis tag
    y=df4.columns,
    hover_data={"date": "|%B %d, %Y"},  # Hover information Settings
    title='Label Personalization - Centered'   # figure title
)

fig.update_xaxes(
    dtick="M1".# indicates one month: displays it once a month
    tickformat="%b\n%Y".Date display mode
    ticklabelmode='instant'  # ticklabelMode: center 'instant', 'period'
)

fig.show()
Copy the code

Time series implementation based on histogram

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

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

fig = px.histogram(  # histogram
    df, 
    x="Date", 
    y="AAPL.Open", 
    histfunc="avg".# histogram function
    title="Histogram implementation of the timeline")

fig.update_traces(xbins_size="M1")  Display by month

fig.update_xaxes(
    showgrid=False, 
    dtick="M1".Display by month
    ticklabelmode="period".# instant period
    tickformat="%b\n%Y"   # Tag display mode
)

fig.update_layout(bargap=0.1)

fig.show()
Copy the code

What is drawn above is a simple histogram, and on this basis can be combined with the scatter diagram to display:

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

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

# 1. Generate histograms
fig = px.histogram(
    df, 
    x="Date", 
    y="AAPL.Open", 
    histfunc="avg", 
    title=Histogram + scatter plot)

# 2. Update track: monthly display
fig.update_traces(xbins_size="M1")   # Each column displays data for several months: M1 shows one month and M2 shows two months


# 3. Set the X-axis
fig.update_xaxes(
    showgrid=True, 
    dtick="M1".Display by month
    ticklabelmode="period".# instant period
    tickformat="%b\n%Y"   
)

# 4. Each bar chart interval
fig.update_layout(bargap=0.1) 

# 5. Setting of red track
fig.add_trace(go.Scatter(
    mode="lines".# ['lines', 'markers', 'text'] 
    x=df["Date"].# Data for two axes
    y=df["AAPL.Open"], 
    name="daily"))   # Track name

fig.show()
Copy the code

Designated trading day

import plotly.graph_objects as go
import pandas as pd

df = pd.DataFrame(dict(
    # transverse
    date=["2019-01-10"."2019-02-10"."2019-03-10"."2019-04-10"."2019-05-10"."2019-06-10"].# on the vertical
    value=[10.12.13.11.12.13]
))

df
Copy the code

# Add canvas
fig = go.Figure()

# Add different tracks
fig.add_trace(go.Scatter(  # a scatter diagram
    name=Track "1".# Track name
    mode="markers+lines".Track mode: mark + fold
    x=df["date"].# Data for two axes
    y=df["value"],
    marker_symbol="star"   # Mark symbol: star star
))

fig.add_trace(go.Scatter(
    name="Track 2",
    mode="markers+lines", 
    x=df["date"], 
    y=df["value"],
    xperiod="M1".# X axis time phase display mode: based on 1 month
    xperiodalignment="start"   # start left middle middle end right
))

fig.add_trace(go.Scatter(
    name="Track 3",
    mode="markers+lines", 
    x=df["date"], 
    y=df["value"],
    xperiod="M1",
    xperiodalignment="middle"
))

fig.add_trace(go.Scatter(
    name="Track 4",
    mode="markers+lines", 
    x=df["date"],
    y=df["value"],
    xperiod="M1",
    xperiodalignment="end"
))

fig.add_trace(go.Bar(  # histogram
    name="Track 5",
    x=df["date"], 
    y=df["value"],
    xperiod="M1",
    xperiodalignment="middle"
))

fig.update_xaxes(showgrid=True, ticklabelmode="period")

fig.show()
Copy the code

Designated trading range

Let’s plot over a time horizon, again using Apple’s stock:

# px implementation

import plotly.express as px
import pandas as pd

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

fig = px.line(df, 
              x='Date'.# x
              y='AAPL.High'.# y
              range_x=['2015-07-01'.'2016-8-31'])   # specify a trading time range
fig.show()
Copy the code

Drawing with interval slider

import plotly.express as px
import pandas as pd

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

fig = px.line(df, 
              x='Date',
              y='AAPL.Open',
              title='Drawing with interval slider')
fig.update_xaxes(rangeslider_visible=True)  # Open range slider
fig.show()
Copy the code

The slider combines with the time button

In addition to the slider, we can also set the button in the graph to select:

import plotly.express as px
import pandas as pd

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

fig = px.line(
    df,
    x='Date',
    y='AAPL.High',
    title='Time series drawing with sliders and buttons')

fig.update_xaxes(
    rangeslider_visible=True.# start display
    rangeselector=dict(
        buttons=list([
            dict(count=1, label="1m", step="month", stepmode="backward"),  # Forward one month
            dict(count=6, label="6m", step="month", stepmode="backward"),  # Forward 6 months
            dict(count=1, label="YTD", step="year", stepmode="todate"),  # show only this year's data
            dict(count=1, label="1y", step="year", stepmode="backward"),  # display data for the past year
            dict(step="all")   Display all data
        ])
    )
)


fig.show()
Copy the code

Hide weekends and trading days

1. Let’s first look at what the graph would look like if we didn’t process non-trading days over a specific period of time.

# default form

import plotly.express as px
import pandas as pd

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

fig = px.scatter(
    df, 
    x='Date', 
    y='AAPL.High', 
    range_x=['2015-12-01'.'2016-01-31'].# specify drawing time range
    title="Non-trading (hidden)")

fig.show()
Copy the code

2, specify the time to hide: can be a week, can be a specific day

# Hide weekends and holidays

fig = px.scatter(
    df, 
    x='Date', y='AAPL.High', 
    range_x=['2015-12-01'.'2016-01-15'],
    title="Hide weekends and holidays (specified dates)")

fig.update_xaxes(
    rangebreaks=[
        dict(bounds=["sat"."mon"]), # Hide Saturday, Monday
        dict(values=["2015-12-25"."2016-01-01"])  # Hide the date
    ]
)
fig.show()
Copy the code

Hide non-trading time

There are not 24 hours of trading in a day and we need to hide the non-trading hours:

import plotly.express as px
import pandas as pd
import numpy as np
np.random.seed(1)

work_week_40h = pd.date_range(
    start='2020-03-01', 
    end='2020-03-07', 
    freq="BH"   # Frequency of data generation: by hour
)

work_week_40h
Copy the code

df5 = pd.DataFrame(dict(
    date = work_week_40h,
    value = np.cumsum(np.random.rand(40) -0.5)
))

fig = px.scatter(df5, 
                 x="date", 
                 y="value",
                 title="Excluding non-trading hours.")

fig.update_xaxes(
    rangebreaks=[  # Exclude time period
        dict(bounds=[17.9], pattern="hour"), # Exclude 5 PM (17 PM) to 9 am h
    ]
)

fig.show()
Copy the code

Practical cases

The following is A practical drawing of three stocks in A shares:

  • China’s ping an
  • Ping an bank
  • Fujian dickinson

tushare

Tushare is a website providing financial and economic data, including: stocks, bonds, futures, funds, etc. The main features are:

  • Rich data: have rich data content, such as stock, fund, futures, digital currency and other market data, corporate finance, fund managers and other fundamental data
  • Easy to obtain: The SDK development package supports languages and provides HTTP Restful interfaces, which is convenient for different people to use
  • Convenient landing: Multiple data storage methods, such as Oracle, MySQL, MongoDB, HDF5, CSV, etc. are provided to ensure the performance of data acquisition

To use this data, we need to install the Tushare library:

pip install tushare   The following figure shows a successful installation
Copy the code

To get the data

Let’s take ping an’s data as an example: 14 fields have the opening price open, the highest price high, etc. Each website has different standards for data collection. The data in this paper is for reference only.

import pandas as pd
import tushare as ts
pingan = ts.get_hist_data("603018")  Stock symbol should be prepared in advance
pingan   Data display total 607 rows, 14 fields
Copy the code

Add two fields to the data:

pingan = pingan.reset_index()

pingan["code_name"] = "Peace in China"
pingan["code"] = "603018"

# all fields
Index(['date'.'open'.'high'.'close'.'low'.'volume'.'price_change'.'p_change'.'ma5'.'ma10'.'ma20'.'v_ma5'.'v_ma10'.'v_ma20'.'turnover'.'code_name'.'code'],
      dtype='object')
Copy the code

The same method can obtain ping An Bank and Fujian Kinson stock data

OHLC drawing

fig = go.Figure(data=go.Ohlc(
    x=pingan['date'].# incoming date
    open=pingan['open'].Pass in 4 copies of data
    high=pingan['high'],
    low=pingan['low'],
    close=pingan['close']
))

fig.update(layout_xaxis_rangeslider_visible=False)  # Hide slider

fig.update_xaxes(
    rangebreaks=[   # set to hide data
        dict(bounds=["sat"."sun"]), # Hide Saturday, Sunday
    ]
)

fig.show()
Copy the code

Open the display slider: Fig.update (layout_xaxIS_rangeslider_visible =True)

Merge data mapping

We combine the data of three stocks and plot them using concat function:

# tushare_data

td = pd.concat([pingan,pinganbank,jinsen],axis=0).reset_index(drop=True)  # specify merged data on horizontal and vertical axis=0
td
Copy the code

OHLC charts for 3 stocks:

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=pingan['date'],
    y=pingan['open'],
    mode='lines',
    name='China Peace'
))

fig.add_trace(go.Scatter(
    x=pinganbank['date'],
    y=pinganbank['open'],
    mode='lines',
    name=Ping an Bank
))


fig.add_trace(go.Scatter(
    x=jinsen['date'],
    y=jinsen['open'],
    mode='lines',
    name='Fujian Kingson'
))

fig.update_xaxes(
    rangeslider_visible=True.# Open the display slider
    rangeselector=dict(
        buttons=list([
            dict(count=1, label="1m", step="month", stepmode="backward"),  # Push back a month
            dict(count=6, label="6m", step="month", stepmode="backward"),  # Delay by 6 months
            dict(count=1, label="YTD", step="year", stepmode="todate"),  # show only this year's data
            dict(count=1, label="1y", step="year", stepmode="backward"),  # display data for the past year
            dict(step="all")   Display all data
        ])
    )
)

fig.show()
Copy the code

Enter the stock market 7 years, the only experience summary: do not fry, do not fry, do not fry 😭

Further reading

  • Cool! Love advanced visualization artifact Plotly_Express
  • Plotly play scatter chart
  • Plotly plays a pie chart
  • Plotly plays a funnel
  • Plotly play bar chart
  • Plotly play bubble chart

You cottage, a sweet cottage. Cabin master, one hand code for survival, one hand cooking spoon to enjoy life, welcome your presence 😃