Home > Article > Backend Development > Time series analysis examples in Python
Python is a popular programming language whose powerful data processing and visualization capabilities make it widely used in the field of data science. In terms of time series analysis, Python provides a wealth of tools and libraries to help us process and analyze time series data. This article will introduce some examples of time series analysis in Python.
1. Data acquisition
In time series analysis, the most commonly used data types are timestamp and date objects. Python's built-in datetime module can easily handle this type of data. When obtaining time series data, we can use the data reading functions provided by the Python pandas library, such as read_csv(), read_excel(), and read_sql().
Here is a sample code to read time series data from a CSV file:
import pandas as pd
import matplotlib.pyplot as plt
df = pd .read_csv('data.csv', parse_dates=['Date'], index_col='Date')
print(df.head())
In this example, we use read_csv( ) function reads the CSV file and sets the parse_dates parameter to a list ['Date'] to convert the timestamps in the data into Python date objects. In addition, we also specified the index_col parameter as 'Date' to use the date column as the index of the data.
2. Time Series Visualization
Python provides a variety of data visualization tools, the most commonly used of which is the matplotlib library. We can use matplotlib's plot() function to plot time series data and set the x-axis to the time series. The following is a sample code:
plt.plot(df.index, df['Value'])
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Time Series')
plt.show()
This code uses the time series in the time series data df as the x-axis, the data column as the y-axis, and the chart After the horizontal and vertical axis labels and titles are set, draw them.
3. Time series stationarity test
In time series analysis, it is usually necessary to test the stationarity of the data. The mean and variance of a stationary time series do not change over time, which allows us to use some robust analysis methods, such as autoregressive models (AR) and moving average models (MA).
We can use Python’s statistical library statsmodels to complete the stationarity test. The library provides the adfuller() function, which can use the Dickey-Fuller test method to test the stationarity of time series data. The following is a sample code:
from statsmodels.tsa.stattools import adfuller
result = adfuller(df['Value'])
print('ADF Statistic: %f' % result[0])
print('p-value: %f' % result[1])
print('Critical Values:')
for key, value in result[4].items( ):
print(' %s: %.3f' % (key, value))
In this example, we use the value of df['Value'] as the time series that needs to be tested data. The function adfuller() returns the test results and key statistics, which we print out for analysis.
4. Seasonal decomposition of time series
In time series analysis, seasonal decomposition is an important analysis method. We can perform seasonal decomposition of time series data using the seasonal_decompose() function provided by the Python library statsmodels. Here is a sample code:
from statsmodels.tsa.seasonal import seasonal_decompose
result = seasonal_decompose(df['Value'], model='multiplicative', period=12)
result.plot()
plt.show()
In this example, we use the value of df['Value'] as the time series data that needs to be decomposed, and set the parameter model='multiplicative ' and period=12, respectively, represent decomposition using the multiplicative model and annual periodicity occurring 12 months. Finally, the decomposition results are plotted and displayed.
Conclusion
This article introduces some classic examples of Python used for time series analysis, including data acquisition, time series visualization, stationarity testing and seasonal decomposition. The above methods are just the tip of the iceberg of time series analysis in Python. Through continuous learning and practice, we can further master various methods of time series analysis and achieve better results.
The above is the detailed content of Time series analysis examples in Python. For more information, please follow other related articles on the PHP Chinese website!