Как установить statsmodels в python
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
The easiest way to install statsmodels is to install it as part of the Anaconda distribution, a cross-platform distribution for data analysis and scientific computing. This is the recommended installation method for most users.
Instructions for installing from PyPI, source or a development version are also provided.
statsmodels supports Python 3.8, 3.9, and 3.10.
statsmodels is available through conda provided by Anaconda. The latest release can be installed using:
To obtain the latest released version of statsmodels using pip:
Follow this link to our PyPI page to directly download wheels or source.
For Windows users, unofficial recent binaries (wheels) are occasionally available here.
Obtaining the Source
We do not release very often but the main branch of our source code is usually fine for everyday use. You can get the latest source from our github repository. Or if you have git installed:
If you want to keep up to date with the source on github just periodically do:
in the statsmodels directory.
Installation from Source
You will need a C compiler installed to build statsmodels. If you are building from the github source and not a source release, then you will also need Cython. You can follow the instructions below to get a C compiler setup for Windows.
If your system is already set up with pip, a compiler, and git, you can try:
If you do not have pip installed or want to do the installation more manually, you can also type:
statsmodels can also be installed in develop mode which installs statsmodels into the current python environment in-place. The advantage of this is that edited modules will immediately be re-interpreted when the python interpreter restarts without having to re-install statsmodels.
It is usually recommended to use the —no-build-isolation to speed up the build process.
If you are using Linux, we assume that you are savvy enough to install gcc on your own. More than likely, it is already installed.
It is strongly recommended to use 64-bit Python if possible.
Getting the right compiler is especially confusing for Windows users. Over time, Python has been built using a variety of different Windows C compilers. This guide should help clarify which version of Python uses which compiler by default.
Installing statsmodels on MacOS requires installing gcc which provides a suitable C compiler. We recommend installing Xcode and the Command Line Tools.
The current minimum dependencies are:
-
>= 3.8 >= 1.18 >= 1.4 >= 1.0 >= 0.5.2
Cython is required to build from a git checkout but not to run or install from PyPI:
-
>= 0.29.26 is required to build the code from github but not from a source distribution.
Given the long release cycle, statsmodels follows a loose time-based policy for dependencies: minimal dependencies are lagged about one and a half to two years. Our next planned update of minimum versions is expected in the first half of 2020.
Визуализация временных рядов в Python 3
Анализ временных рядов относится к области статистики, которая изучает упорядоченные и временные данные. Своевременный и хорошо продуманный анализ временных рядов может предоставить полезные статистические данные и даже составить некоторый прогноз на будущее. Поэтому он применяется во многих областях, включая экономику, прогнозирование погоды и планирование пропускной способности.
Данное руководство ознакомит вас с базовыми методами анализа временных рядов и научит визуализировать такие данные.
Требования
Данное руководство можно выполнить на локальном компьютере или удалённом сервере.
- Для работы с объёмными базами данных и выполнения некоторых расчетов компьютеру потребуется как минимум 2 ГБ памяти.
- Jupyter Notebook (руководство по установке Jupyter Notebook вы найдёте здесь). или удалённая среда разработки.
1: Установка пакетов
Установите гибкую библиотеку pandas, которая предназначена для управления данными, и библиотеку statsmodels, которая позволяет выполнять статистические вычисления в Python. Эти две библиотеки расширяют аналитический инструментарий Python.
Как и другие инструменты Python, pandas и statsmodels можно установить с помощью pip. Разверните среду разработки:
cd environments
. my_env/bin/activate
Создайте новый каталог для проекта; в руководстве он будет называться timeseries. Откройте этот каталог.
mkdir timeseries
cd timeseries
Примечание: Вместо timeseries укажите имя своего каталога.
Теперь можно установить pandas, statsmodels и пакет визуализации данных matplotlib. Следующая команда установит эти пакеты и их зависимости:
pip install pandas statsmodels matplotlib
2: Загрузка данных временного ряда
Запустите Jupyter Notebook:
Чтобы создать новый документ, выберите New →Python 3 в выпадающем меню в правом верхнем углу страницы.
В новый документ можно добавить установленные библиотеки (сошлитесь на них с помощью сокращений). Добавьте в начало документа:
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
Примечание: После добавления каждого блока кода нужно нажимать Alt + Enter, чтобы запустить код.
Библиотека statsmodels предоставляет встроенные данные временного ряда, потому набор данных можно загрузить прямо в память.
Для примера можно использовать набор «Atmospheric CO2 from Continuous Air Samples at Mauna Loa Observatory, Hawaii, U.S.A.», в котором собраны образцы CO2 с марта 1958 года по декабрь 2001 года. Добавьте в файл:
data = sm.datasets.co2.load_pandas()
co2 = data.data
Убедитесь, что первые строки набора выглядят так:
print(co2.head(5))
co2
1958-03-29 316.1
1958-04-05 317.3
1958-04-12 317.6
1958-04-19 317.5
1958-04-26 316.4
3: Индексация данных временного ряда
Возможно, вы заметили, что даты в наборе данных используются в качестве индексов структуры DataFrame. При работе с данными временных рядов в Python даты должны использоваться как индексы. Для этого нужно запустить:
co2.index
DatetimeIndex([‘1958-03-29’, ‘1958-04-05’, ‘1958-04-12’, ‘1958-04-19’,
‘1958-04-26’, ‘1958-05-03’, ‘1958-05-10’, ‘1958-05-17’,
‘1958-05-24’, ‘1958-05-31’,
.
‘2001-10-27’, ‘2001-11-03’, ‘2001-11-10’, ‘2001-11-17’,
‘2001-11-24’, ‘2001-12-01’, ‘2001-12-08’, ‘2001-12-15’,
‘2001-12-22’, ‘2001-12-29’],
dtype=’datetime64[ns]’, length=2284, freq=’W-SAT’)
Поле dtype=datetime[ns] будет индексировать данные с помощью объектов временных меток, а length=2284 и freq=’W-SAT’ добавляют 2,284 временные метки еженедельно (начиная с субботы).
Вместо данных за неделю лучше и надёжнее использовать среднемесячные значения временных рядов. Их можно получить с помощью удобной функции resample, которая позволяет группировать временные ряды в блоки (1 месяц), применять функцию к каждой группе (получать среднее значение) и комбинировать результат (по одной строке на группу).
MS значит, что данные сгруппированы по месяцам. В качестве временной метки используется первый день месяца.
y.head(5)
1958-03-01 316.100
1958-04-01 317.200
1958-05-01 317.120
1958-06-01 315.800
1958-07-01 315.625
Freq: MS, Name: co2, dtype: float64
Интересной особенностью библиотеки pandas является возможность обрабатывать индексы меток дат, благодаря чему можно быстро создать срез данных. Например, Можно создать срез и получить данные за определённый год:
y[‘1990’:] 1990-01-01 353.650
1990-02-01 354.650
.
2001-11-01 369.375
2001-12-01 371.020
Freq: MS, Name: co2, dtype: float64
Чтобы извлечь данные за период с октября 1995 года по октябрь 1996 года, введите:
y[‘1995-10-01′:’1996-10-01’] 1995-10-01 357.850
1995-11-01 359.475
1995-12-01 360.700
1996-01-01 362.025
1996-02-01 363.175
1996-03-01 364.060
1996-04-01 364.700
1996-05-01 365.325
1996-06-01 364.880
1996-07-01 363.475
1996-08-01 361.320
1996-09-01 359.400
1996-10-01 359.625
Freq: MS, Name: co2, dtype: float64
4: Обработка пропущенных значений в данных временного ряда
Во временных рядах нередко встречаются пропущенные значения. Чтобы проверить временной ряд на наличие пропущенных значений, вы можете создать график или использовать эту команду:
Этот вывод сообщает о том, что пропущенные значения были обнаружены в 5 месяцах.
В целом, если пропущенных значений не очень много, можно их заполнить. В pandas для этого используется команда fillna(). Для простоты пропущенные значения в временном ряду можно заполнить ближайшим ненулевым значением, хотя важно отметить, что иногда предпочтительнее использовать скользящее среднее.
Заполнив пропущенные значения, повторите проверку:
Как видите, пропущенные значения был заполнены.
5: Визуализация временных данных
Визуализация временного ряда может предоставить много полезной информации. Основные компоненты анализа:
- Сезонность: зависят ли данные от временного периода? Существует ли чёткая картина их колебаний?
- Тренд: можно ли отследить долгосрочный рост или спад данных?
- Шум: существуют ли какие-либо точки выброса или пропущенные значения, которые не согласуются с остальными данными?
Чтобы отобразить график, используйте обёртку pandas вокруг matplotlib API:
y.plot(figsize=(15, 6))
plt.show()
При построении данных вы получите несколько шаблонов их поведения. К примеру, временной ряд может отличаться сезонностью, а также иметь общий тренд на увеличение.
Визуализировать данные можно также с помощью декомпозиции временных рядов. Метод декомпозиции временных рядов позволяет разложить временные ряды на три отдельных компонента: тренд, сезонность и шум.
Для выполнения декомпозиции рядов по сезонности библиотека statsmodels предоставляет встроенную функцию seasonal_decompose.
Приведённый ниже сценарий выполняет декомпозицию временных рядов по сезонности. По умолчанию seasonal_decompose возвращает изображение относительно небольшого размера; первые две строки этого фрагмента кода увеличивают полученное изображение.
from pylab import rcParams
rcParams[‘figure.figsize’] = 11, 9
decomposition = sm.tsa.seasonal_decompose(y, model=’additive’)
fig = decomposition.plot()
plt.show()
Декомпозиция временного ряда позволяет быстро определить изменяющееся среднее значение.
Полученные данные помогут лучше понять структуру временных рядов. Многие методы прогнозирования основаны на концепции структурированной декомпозиции.
Заключение
Теперь вы умеете визуализировать данные временного ряда в Python 3.
Чтобы немного попрактиковаться, загрузите другой временной ряд и попробуйте повторить это руководство с другими данными.
Installing statsmodels¶
The easiest way to install statsmodels is to install it as part of the Anaconda distribution, a cross-platform distribution for data analysis and scientific computing. This is the recommended installation method for most users.
Instructions for installing from PyPI, source or a development version are also provided.
Python Support¶
statsmodels supports Python 3.7, 3.8, and 3.9.
Anaconda¶
statsmodels is available through conda provided by Anaconda. The latest release can be installed using:
PyPI (pip)¶
To obtain the latest released version of statsmodels using pip:
Follow this link to our PyPI page to directly download wheels or source.
For Windows users, unofficial recent binaries (wheels) are occasionally available here.
Obtaining the Source¶
We do not release very often but the main branch of our source code is usually fine for everyday use. You can get the latest source from our github repository. Or if you have git installed:
If you want to keep up to date with the source on github just periodically do:
in the statsmodels directory.
Installation from Source¶
You will need a C compiler installed to build statsmodels. If you are building from the github source and not a source release, then you will also need Cython. You can follow the instructions below to get a C compiler setup for Windows.
If your system is already set up with pip, a compiler, and git, you can try:
If you do not have pip installed or want to do the installation more manually, you can also type:
Or even more manually
statsmodels can also be installed in develop mode which installs statsmodels into the current python environment in-place. The advantage of this is that edited modules will immediately be re-interpreted when the python interpreter restarts without having to re-install statsmodels.
Compilers¶
Linux¶
If you are using Linux, we assume that you are savvy enough to install gcc on your own. More than likely, it is already installed.
Windows¶
It is strongly recommended to use 64-bit Python if possible.
Getting the right compiler is especially confusing for Windows users. Over time, Python has been built using a variety of different Windows C compilers. This guide should help clarify which version of Python uses which compiler by default.
Installing statsmodels on MacOS requires installing gcc which provides a suitable C compiler. We recommend installing Xcode and the Command Line Tools.
Dependencies¶
The current minimum dependencies are:
Cython is required to build from a git checkout but not to run or install from PyPI:
Cython >= 0.29 is required to build the code from github but not from a source distribution.
Given the long release cycle, statsmodels follows a loose time-based policy for dependencies: minimal dependencies are lagged about one and a half to two years. Our next planned update of minimum versions is expected in the first half of 2020.
Optional Dependencies¶
cvxopt is required for regularized fitting of some models.
Matplotlib >= 3 is needed for plotting functions and running many of the examples.
If installed, X-12-ARIMA or X-13ARIMA-SEATS can be used for time-series analysis.
pytest is required to run the test suite.
IPython >= 6.0 is required to build the docs locally or to use the notebooks.
joblib >= 1.0can be used to accelerate distributed estimation for certain models.