Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to draw time Series Diagram

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article analyzes how to use Python to draw time series diagrams. The content is detailed and easy to understand. Friends interested in "how to use Python to draw time series diagrams" can read it slowly and deeply along with the ideas of Xiaobian. I hope it can help everyone after reading. Let's learn how to draw time series diagrams using Python together with Xiaobian.

01 Retrieving datasets from Quandl

About Quandl

Quandl is a platform for financial, economic and alternative data provided by a variety of data publishers, including the United Nations, the World Bank, central banks, trade exchanges and investment research firms.

Using Python's Quandl module, you can easily import financial data into Python. Quandl offers free data sets, including some data samples, but if you need access to some of the premium data products, you have to pay first.

The process of importing data from Quandl into Python is very simple. If we are interested in the ABN AMRO Group of Euronext, we just need to enter the following code in the Jupyter Notebook cell (this dataset is coded EURONEXT/ABN on Quandl):

In[]:import quandl#Replace with your own Quandl API key QUANDL_API_KEY="BCzkk3NDWt7H9yjzx-DY'quandl.ApiConfig.api_key=QUANDL_API_KEYdf =quandl.get('EURONEXT/ABN')

It's a good practice to store Quandl's API key in a constant variable, so if the API key changes, you only need to change it in this one place!

After importing the quandl package, we store Quandl's API key in the constant variable QUANDL_API_KEY. This constant value is used to set the API key for the Quandl module and only needs to be performed once for each import of the quandl package. The last line calls the quandl.get() instruction, downloading the ABN dataset directly from Quandl into the df variable. (Note: EURONEXT stands for Euronext Stock Exchange, the data provider.)

By default, Quandl imports the dataset into the DataFrame of the pandas module. We can check the header and trailer of a DataFrame with the following code:

In[]:

df:head()

out[]:

OPen High Low Last Volume Turnower

Date

2015-11-20 18.18 18.43 18.000 18.35 38392898.0 7.003281e+08

2015-11-23 18.45 18.70 18.215 18.61 3352514.0 6.186446e+07

2015-11-24 18.70 18.80 18.370 18.80 4871901.0 8.994087e+07

2015-11-25 18.85 19.50 18.770 19.45 4802607.0 9.153862e+07

2015-11-26 19.48 19.67 19.410 19.43 1648481.0 3.220713e+07

In[]:

df:tail()

Out []:

OPen High Low Last Volume Turnower

Date

2018-08-06 23.50 23.53 23.23 23.34 1126371.0 2.634333e+07

2018-08-07 23.59 23.60 23.31 23.33 1785613.0 4.177652e+07

2018-08-08 24.00 24.39 23.83 24.14 4165320.0 1.007085e+08

2018-08-09 24.40 24.46 24.15 24.37 2422470.0 5.895752e107

2018-08-10 23.70 23.94 23.28 23.51 3951850.0 9.336493e+07

By default, the head() and tail() commands display the first 5 and last 5 lines of the DataFrame, respectively, and you can set the parameters it passes to a specific number to define the number of lines to display. For example, head(100) displays the first 100 rows in the DataFrame.

If you don't set any additional parameters for the get() command, it will retrieve the entire time series dataset from the previous business day until November 2015.

To visualize this DataFrame, we can draw a graph using the plot() command

In[]: %matplotlib inline import matplotlib.pyplot as plt df.plot();

The results are shown below.

The plot() command for pandas returns an Axis object whose string representation is displayed on the interface with the plot() command. To eliminate this message, we add a semicolon ";" at the end of the last statement. Alternatively, we can add a pass statement at the bottom of the cell. Alternatively, we can assign the plot function to a variable, which also eliminates this output.

By default, the Pandas plot() command uses the matplotlib library to display images. If the system reports an error, check that you have this library installed and that the %matplotlib inline command has been called at least once. You can customize the appearance of your chart, and more information about the plot command in DataFrame can be found at pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html

02 Plot the relationship between closing price and trading volume

When no arguments are given to the plot() command, it draws a line graph with all the columns of the DataFrame on the same graph, and we can't get anything useful out of this messy image. To extract information from this data efficiently, we can plot the closing price of a stock against its trading volume.

Enter the following command in the cell:

In[]: princes=df['Last'] volumes=df['Volume']

The above command will store the data we are interested in in the closing_prices and volumes variables, respectively. We can continue to use the head() and tail() commands to see the head and bottom of the resulting pandas data type:

In[]: Prices .head()out[]: Date ... 2015-11-20 18.35 2015-11-23 18.61 2015-11-24 18.80 2015-11-25 19.45 2015-11-26 19.43 Name: Last,dtype:float64In[]: volumes.tail()out[]: Date 2018-08-031252024.0 2018-08-061126371.0 2018-08-071785613.0 2018-08-084165320.0 2018-08-09。2422470.0 Name:Volume,dtype:float64

If you want to know the type of a particular variable, you can use the type() command. For example, the type(volumes) command runs pandas.core.series.Series, so we know that volumes belong to the pandas series data type.

Data is available from 2018 all the way back to 2015, so you can plot the relationship between closing price and trading volume:

In[]:#The top Plot consisting of daily closing Pricestop=plt.subplot2grid((4,4),(0,0),rowspan=3,colspan=4)top .plot(Prices.index,Prices,1abel='Last')Plt.title('ABN Last Price from 2015 - 2018')plt.legend(loc=2)#The bottom Plot consisting of daily trading volumebottom=plt.subplot2grid((4,4),(3,0),rowspan=1,colspan=4)bottom.bar(volumes.index,volumes)plt.title('ABN Daily Trading Volume')Plt.gcf () .set_size_inches(12,8)plt.subplots_adjust(hspace=0.75)

The results are shown below.

In the first line, the first parameter (4,4) of the subplot2grid command divides the entire plot into a 4x4 grid, and the second parameter (0,0) indicates that the plot will be anchored in the upper-left corner of the plot. rowspan=3 indicates that the drawing will occupy 3 of the 4 available rows on the grid, i.e., 75% of the actual height of the drawing;colspan=4 indicates that the drawing will occupy all 4 columns of the grid, i.e., use all of its available width. This command returns a matplotlib axis object that we will use to draw the upper part of the graph.

In the second row, plot the upper chart using the plot() command, with the date values on the x-axis and the closing price values on the y-axis. In the next two lines, we specify the title of the current image and the legend of the time-series data placed in the upper left corner.

Next, we repeat the above operation, showing daily trading volume at the bottom, anchored in a grid space of 1 row and 4 columns at the bottom.

To make the image clearer, we call the set_size_inches() command to set the shape to 9 inches wide and 6 inches high, resulting in a rectangular shape (the previous gcf() command means to get the current size). Finally, we call the subplots_adjust() command with the hspace parameter to add a small gap between the top and bottom two subgraphs.

The subplots_adjust() command is used to optimize the layout of each subplot. It can accept parameters such as left, right, bottom, top, wspace and hspace.

03 Drawing Candlestick Charts

Candlestick charts are another popular financial chart that shows more information than a single price chart. A candlestick is a fluctuation at each specific point in time that contains four important pieces of information: the opening price, the high price, the low price and the closing price.

We no longer recommend using the old matplotlib.finance module and replacing it with another mpl_finance package consisting of extracted code, which you can get by typing the following code in the command line window:

$pip install mpl-finance

To visualize candlestick plots more easily, we will use a subset of the ABN dataset. In the example below, we retrieve the daily price for July 2018 as a dataset on Quandl and plot the candlestick chart below:

In[]:%matplotlib inline import quandlfrom mpl_finance import candlestick_ohlcimport matplotlib.dates as mdatesimport matplotlib.pyplot as pltquandl.ApiConfig.api kcy-QUANDL API KEYdf_subset-quandl.get('EURONEXT/ABN', start_date='2018-07-01", ena_date='2018-07-31')df_subset['Date'"]=df_subset.indqex.map(mdates.dqate2num)df_ohlc=df_subset[['Date','Open','High','Low','Last']]figure,ax=plt.sSubPlots(figsize= =(8,4))formatter=mdates.DateFormatter('%Y-%m-%d')ax.xaxis.set_major_formatter(formatter)candlestick_ohlc(ax df_ohlc.values, width=0.8, colorup='green', colordown='red')plt.show()

The candlestick diagram is shown below.

You can specify the time range of the dataset by defining the values of start_date and end_date in the quandl.get() command.

The prices retrieved from Quandl are placed in a variable named df_dataset, and since matplotlib's plotting function requires its own format, we convert the index values, including date and time, with the mdates.date2num command and place them in a new column named Date.

The candlestick's date, opening price, high price, low price, and closing price are extracted as a DataFrame column and stored in the df_ohlc variable. The plt.subplots() function creates a graph 8 inches wide and 4 inches high, where labels along the x-axis are converted to a format we can read.

Call candlestick_ohlc() to draw a candlestick chart (candlestick width 0.8 or 80% of the full day width), closing higher than the opening price in light gray and closing lower than the opening price in dark gray. Finally, use the plt.show() command to display the candlestick diagram.

How to use Python to draw time series diagrams is shared here. I hope the above content can improve everyone. If you want to learn more, please pay more attention to the updates of Xiaobian. Thank you for your attention to the website!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report