Using the ARIMA model with Python

Currently, I am utilizing ARIMA for forecasting in Python. Below is the code snippet I am working with:

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
from statsmodels.tsa.seasonal import seasonal_decompose
from sklearn import datasets, linear_model
from sklearn.model_selection import train_test_split

HSBC = pd.read_csv('HSBC.csv', index_col = 'Date', parse_dates = True)
HSBC2 = HSBC['Close']
result = seasonal_decompose(HSBC2, model='multiplicative', period = 1)

from pmdarima import auto_arima
import warnings
warnings.filterwarnings("ignore")

stepwise_fit = auto_arima(HSBC2, start_p = 1, start_q = 1, 
                      max_p = 3, max_q = 3, m = 12, 
                      start_P = 0, seasonal = True, 
                      d = None, D = 1, trace = True, 
                      error_action ='ignore',    
                      suppress_warnings = True,  
                      stepwise = True) 

train = HSBC2[0:173]
test = HSBC2[173:248]
model = SARIMAX(train, order = (0, 1, 1), seasonal_order =(0,1,1,12)) 
result = model.fit()

start = len(train)
end = len(train) + len(test) - 1
prediction = result.predict(start,end,
                            typ = 'levels').rename("Predictions")  
predictions.plot(legend = True) 
test.plot(legend = True)

I am puzzled as to why the x-axis of the prediction plot displays numbers instead of dates like that of the test plot.

Answer №1

It seems like the issue may be that you haven't specified the frequency of your index. Give this a try:

HSBC.index = pd.date_range(freq='d', start=HSBC.index[0], periods=len(HSBC)

Remember to use frequency='d' if your index is spaced daily.

UPDATE:

Simply adjust the start and end parameters in the predict method, for example:

start = test['Date'].iloc[0]
end = test['Date'].iloc[-1]
prediction = result.predict(start,end,
                            typ = 'levels').rename("Predictions")  

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to format line breaks and indentation for better viewing with MySQL's json.dump() method

I am currently working with code to extract and display data from my SQL database. Strangely, I have found that only one command has been successful in this process. json_string = json.dumps(location_query_1) My query pertains to the specific format in w ...

What is the best way to exclude a specific part of text, enclosed in quotation marks, when editing a line of text in Python?

I have a log file from Apache that I want to convert to csv. The challenge is that the spaces in the file need to be replaced with commas, but some of the columns contain fields with spaces between them. However, these particular fields are enclosed in quo ...

When attempting to create a table with a foreign key in SQLite using Python, I encountered a syntax error near the "-"

While experimenting with sqlite in Python and following some tutorials, I encountered an issue when attempting to create a table with a foreign key. The error message "near "-": syntax error" kept popping up. Below is the code I was working on: import sq ...

Utilizing Python to Merge Sets in a List

I'm grappling with a relatively simple issue that is proving to be quite problematic for me. I've been exploring various Python tools (such as chain, combinations, permutations, and product from itertools) but haven't found much success in s ...

Retrieving JSON data embedded within a webpage's source code

Lately, I've been delving into various web scraping techniques and solutions. My current project involves extracting specific elements from JSON code embedded within a webpage (). My main goal is to extract details from the comments section, with a ...

Python tkinter infinite loop causing program to become unresponsive

Currently, I am developing a tkinter application that automatically backs up files by monitoring the last modification time of the file. The code for this app is provided below. from tkinter import * from tkinter import filedialog import shutil import os f ...

The mysterious results of the 2F1 function in the scipy module

Why does hyp2f1 from scipy return 1? Shouldn't it be something else? https://i.stack.imgur.com/iEWIr.png Below is the code I used import numpy as np from scipy import special x = np.arange(0,2,0.01) y = special.hyp2f1(-1/2, 1/2, 2, -400/(1-8/9*np.c ...

Modify the data values and reconstruct the JSON structure using Python

I'm facing a situation where I need to work with the following json data: data = { "app": [ { "ida": 10, "configur": { "config": [ { "active": "true", "tol": ...

Search for a specific value within a CSV document

I'm having trouble retrieving a specific value from a CSV file based on certain criteria within a function. Although my program successfully fetches all the values, it fails to return the one linked to the input I provided. Any assistance would be gre ...

Two applications installed on a single server, each running on its own port. The first application is unable to communicate with the second

I have two applications running on the same VPS (Ubuntu) and domain. The first is a Node.js app running on port 80, while the second is a Python (Flask) app running under Apache on port 3000. The Python app has a simple API with one endpoint /test. When I ...

Combine two data sets by matching their time columns

Please note: I previously posted a similar question with the same dataset on this link, but now I am exploring a different approach to merge the data frames. I have two separate data frames that house diverse types of medical information for patients. The ...

I must transfer this information to an Excel spreadsheet

After extracting this data using Selenium in Python, I am looking to export it to an Excel file. I believe that pandas could be the solution, but I am unsure of how to accomplish this task. Any guidance would be greatly appreciated. Below is the code snip ...

Output the distinct JSON keys in dot notation through Python

In an attempt to create a script for analyzing the structure of a JSON file efficiently, I want to print the unique keys in dot notation. Let's consider a sample file named 'myfile.json' with the format below: { "a": "one", "b": "two", "c" ...

A situation where a complex query involves multiple variables being reused and formatted using the %s string format

I stumbled upon a helpful thread on SO which got me thinking. Currently, I'm utilizing psycopg2 to run SQL queries using strings: import credentials as creds import psycopg2 start_date = '2020-01-01' end_date = '2020-01-02' anothe ...

Django: A guide to efficiently retrieving related objects along with a model instance

ClassOne: ... ClassTwo: ForeignKey(One) ClassThree: ForeignKey(Two) Currently, I have an object of Three. t = Three() two = t.two one = two.one During this process, the database needs to be accessed three times. Is there a way to fetch all ...

Using Selenium to Extract Data from Complex HTML Structure

I am seeking assistance in web scraping using Selenium with Python. The page I am trying to scrape requires a paid account to access, making it difficult to create a reproducible example. Here is the page I am attempting to scrape Specifically, I am tryi ...

pydantic.error_wrappers.ValidationError: There is 1 validation error for object B

Every time I attempt to parse a JSON object using Pydantic, my IDE keeps throwing an error... Here's the code snippet causing the issue: from pydantic import BaseModel, Field class A(BaseModel): a: str = Field(None, alias="А") class ...

python pause the execution of a program for n seconds

Does Python have a built-in function to pause a program for a specific number of seconds? I want to create something similar to the following: print("Hello") delay(5) #delays the program by 5 seconds print("World!") I would really appreciate any help on ...

Utilizing re.sub for modifying a pandas dataframe column while incorporating predefined restrictions - **Highly Beneficial**

This particular problem took some time for me to solve, as there were only bits and pieces of information on stack overflow. I wanted to share my solution in case anyone else is facing the same issue. Objective: 1- Modify strings in a entire pandas DataF ...

Comment form on post detail page in Django

Currently, I am in the process of learning Django and attempting to implement a comment form within my blogdetail view. I have been following a tutorial on YouTube for guidance: https://www.youtube.com/watch?v=An4hW4TjKhE&t=40s The tutorial I am foll ...