import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.arima.model…
- User
import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.arima.model import ARIMA from pmdarima import auto_arima
讀取數據
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\tsmc stock\stock price.csv" data = pd.read_csv(file_path)
將日期轉為日期格式 (可選)
data['Date'] = pd.to_datetime(data['Date'])
劃分特徵 (X) 和目標 (y)
X = data[['Opening Price', 'Highest Price', 'Lowest Price']] # 特徵 y = data['Closing Price'] # 目標
使用 auto_arima 找到最佳 (p, d, q)
auto_model = auto_arima( y, seasonal=False, trace=True, error_action='ignore', suppress_warnings=True, stepwise=True )
打印自動選擇的 ARIMA 參數
print(f"Best ARIMA parameters: {auto_model.order}")
訓練 ARIMA 模型
arima_model = ARIMA(y, order=auto_model.order) arima_result = arima_model.fit()
計算殘差值
residuals = y - arima_result.fittedvalues
打印模型摘要
print(arima_result.summary())
預測未來 5 天的數據
forecast_steps = 5 forecast = arima_result.get_forecast(steps=forecast_steps) forecast_index = pd.date_range(start=y.index[-1], periods=forecast_steps+1, freq='B')[1:] forecast_values = forecast.predicted_mean
繪圖:實際值、模型預測值、殘差
plt.figure(figsize=(14, 7))
原始數據與擬合值
plt.plot(y, label='Actual Prices', color='blue') plt.plot(arima_result.fittedvalues, label='Fitted Values', color='orange')
預測值
plt.plot(forecast_index, forecast_values, label='Forecast', color='green', linestyle='--')
殘差
plt.figure(figsize=(14, 5)) plt.plot(residuals, label='Residuals', color='red') plt.axhline(0, linestyle='--', color='black', alpha=0.7)
圖例與標題
plt.legend() plt.title('Stock Price Analysis with ARIMA') plt.show()
將殘差與預測值輸出為文件
residuals.to_csv("residuals.csv", header=True) forecast_values.to_csv("forecast_values.csv", header=True)
###下面要有label框
原始數據與擬合值
plt.plot(y, label='Actual Prices', color='blue') plt.plot(arima_result.fittedvalues, label='Fitted Values', color='orange')
預測值
plt.plot(forecast_index, forecast_values, label='Forecast', color='green', linestyle='--')
- Assistant
The code you've provided is for time series forecasting using the ARIMA model with the
pmdarimalibrary for automatic model selection. It reads stock price data, trains an ARIMA model to predict closing prices, and visualizes the results, including predictions and residuals.Here's a step-by-step breakdown of your existing workflow and how to add a label box in your plot for clarity:
Step-by-Step Breakdown
-
Import Necessary Libraries: You have correctly imported the necessary libraries for data manipulation (
pandas), visualization (matplotlib.pyplot), and time series modeling (statsmodelsandpmdarima). -
Data Loading and Preprocessing: You've loaded the data from a CSV file and converted the 'Date' column into the datetime format. This is useful for time series analysis.
-
Feature and Target Definition: Features (
X) included opening, highest, and lowest prices while the target variable (y) is the closing price. -
Model Selection using auto_arima: You automatically determine the best ARIMA parameters (
p,d,q) for your time series data. -
Model Training and Residual Calculation: After fitting the model, you calculate the residuals as the difference between actual and fitted values.
-
Forecasting: You forecast future values and generate a date range for the forecast index.
-
Plotting: You create plots for actual prices, fitted values, forecast values, and residuals.
-
Output to CSV: Finally, you save the residuals and forecast values to CSV files.
Adding a Label Box for the Plot
To add a label box (legend) to your plots, you can call the
plt.legend()function after plotting all lines in the same figure. Here's how to implement it in the plotting section:Updated Plotting Code Example:
# 繪圖:實際值、模型預測值、殘差 plt.figure(figsize=(14, 7)) # 原始數據與擬合值 plt.plot(y, label='Actual Prices', color='blue') plt.plot(arima_result.fittedvalues, label='Fitted Values', color='orange') # 預測值 plt.plot(forecast_index, forecast_values, label='Forecast', color='green', linestyle='--') # 添加標題和標籤 plt.title('Stock Price Analysis with ARIMA') plt.xlabel('Date') plt.ylabel('Prices') plt.grid() # 圖例 plt.legend(loc='upper left') # 顯示圖形 plt.show() # 繪製殘差 plt.figure(figsize=(14, 5)) plt.plot(residuals, label='Residuals', color='red') plt.axhline(0, linestyle='--', color='black', alpha=0.7) plt.title('Residuals of the ARIMA Model') plt.xlabel('Index') plt.ylabel('Residuals') plt.grid() plt.legend(loc='upper left') plt.show()Explanation of Modifications:
- Adding
xlabelandylabel: This helps in adding context to your axes. - Adding
grid(): This helps make the plot more readable. - Positioning the Legend: You can adjust
locto the position you prefer for the legend (e.g., `'upper left', 'upper right', 'lower left', etc.)
Now, running the modified code will give you labeled plots, making it easier to understand the different components. If you have further questions or need additional functionality, feel free to ask!
-
- User
import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.arima.model import ARIMA from pmdarima import auto_arima
讀取數據
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\tsmc stock\stock price.csv" data = pd.read_csv(file_path)
將日期轉為日期格式 (可選)
data['Date'] = pd.to_datetime(data['Date'])
劃分特徵 (X) 和目標 (y)
X = data[['Opening Price', 'Highest Price', 'Lowest Price']] # 特徵 y = data['Closing Price'] # 目標
使用 auto_arima 找到最佳 (p, d, q)
auto_model = auto_arima( y, seasonal=False, trace=True, error_action='ignore', suppress_warnings=True, stepwise=True )
打印自動選擇的 ARIMA 參數
print(f"Best ARIMA parameters: {auto_model.order}")
訓練 ARIMA 模型
arima_model = ARIMA(y, order=auto_model.order) arima_result = arima_model.fit()
計算殘差值
residuals = y - arima_result.fittedvalues
打印模型摘要
print(arima_result.summary())
預測未來 5 天的數據
forecast_steps = 5 forecast = arima_result.get_forecast(steps=forecast_steps) forecast_index = pd.date_range(start=y.index[-1], periods=forecast_steps+1, freq='B')[1:] forecast_values = forecast.predicted_mean
繪圖:實際值、模型預測值、殘差
plt.figure(figsize=(14, 7))
原始數據與擬合值
plt.plot(y, label='Actual Prices', color='blue') plt.plot(arima_result.fittedvalues, label='Fitted Values', color='orange')
預測值
plt.plot(forecast_index, forecast_values, label='Forecast', color='green', linestyle='--')
添加標題和標籤
plt.title('Stock Price Analysis with ARIMA') plt.xlabel('Date') plt.ylabel('Prices') plt.grid()
圖例
plt.legend(loc='upper left')
顯示圖形
plt.show()
繪製殘差
plt.figure(figsize=(14, 5)) plt.plot(residuals, label='Residuals', color='red') plt.axhline(0, linestyle='--', color='black', alpha=0.7) plt.title('Residuals of the ARIMA Model') plt.xlabel('Index') plt.ylabel('Residuals') plt.grid() plt.legend(loc='upper left') plt.show()
###應該分為20%test,80%train
- Assistant
To split your time series data into training and testing sets (e.g., 80% for training and 20% for testing) before fitting the ARIMA model, you can follow these steps. I'll update your existing code to include this functionality.
Updated Code with Data Splitting
import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.arima.model import ARIMA from pmdarima import auto_arima # 讀取數據 file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\tsmc stock\stock price.csv" data = pd.read_csv(file_path) # 將日期轉為日期格式 (可選) data['Date'] = pd.to_datetime(data['Date']) data.set_index('Date', inplace=True) # 將日期設置為索引 # 劃分特徵 (X) 和目標 (y) X = data[['Opening Price', 'Highest Price', 'Lowest Price']] # 特徵 y = data['Closing Price'] # 目標 # 計算訓練集和測試集的切分點 (80% 訓練集,20% 測試集) train_size = int(len(y) * 0.8) train, test = y[:train_size], y[train_size:] # 使用 auto_arima 找到最佳 (p, d, q) auto_model = auto_arima( train, seasonal=False, trace=True, error_action='ignore', suppress_warnings=True, stepwise=True ) # 打印自動選擇的 ARIMA 參數 print(f"Best ARIMA parameters: {auto_model.order}") # 訓練 ARIMA 模型 arima_model = ARIMA(train, order=auto_model.order) arima_result = arima_model.fit() # 計算殘差值 residuals = train - arima_result.fittedvalues # 打印模型摘要 print(arima_result.summary()) # 預測未來的數據 (基於測試集的大小) forecast_steps = len(test) forecast = arima_result.get_forecast(steps=forecast_steps) forecast_index = test.index # 使用測試集的索引 forecast_values = forecast.predicted_mean # 繪圖:實際值、模型預測值、殘差 plt.figure(figsize=(14, 7)) # 原始數據與擬合值 plt.plot(y, label='Actual Prices', color='blue') plt.plot(arima_result.fittedvalues, label='Fitted Values', color='orange') # 預測值 plt.plot(forecast_index, forecast_values, label='Forecast', color='green', linestyle='--') # 添加標題和標籤 plt.title('Stock Price Analysis with ARIMA') plt.xlabel('Date') plt.ylabel('Prices') plt.grid() # 圖例 plt.legend(loc='upper left') # 顯示圖形 plt.show() # 繪製殘差 plt.figure(figsize=(14, 5)) plt.plot(residuals, label='Residuals', color='red') plt.axhline(0, linestyle='--', color='black', alpha=0.7) plt.title('Residuals of the ARIMA Model') plt.xlabel('Index') plt.ylabel('Residuals') plt.grid() plt.legend(loc='upper left') plt.show() # 將殘差與預測值輸出為文件 residuals.to_csv("residuals.csv", header=True) forecast_values.to_csv("forecast_values.csv", header=True)Key Changes Made:
-
Indexing by Date:
- I set the 'Date' column as the index of the DataFrame so that it works seamlessly with the time series analysis.
-
Data Splitting:
- I calculated the splitting point based on an 80/20 ratio of the total length of the
yseries. The training set (train) contains the first 80% of the data, while the testing set (test) contains the remaining 20%.
- I calculated the splitting point based on an 80/20 ratio of the total length of the
-
ARIMA Model Training:
- Instead of fitting the ARIMA model to the entire dataset, I now fit it only to the
traindataset.
- Instead of fitting the ARIMA model to the entire dataset, I now fit it only to the
-
Forecasting:
- The size of the forecast is dynamically determined based on the length of the
testdataset.
- The size of the forecast is dynamically determined based on the length of the
This code will now train the model on 80% of the data and test its predictions against the remaining 20%. Adjusting the split ratio can easily be done by changing the
train_sizecalculation. -
- User
import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.arima.model import ARIMA from pmdarima import auto_arima
讀取數據
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\tsmc stock\stock price.csv" data = pd.read_csv(file_path)
將日期轉為日期格式 (可選)
data['Date'] = pd.to_datetime(data['Date']) data.set_index('Date', inplace=True) # 將日期設置為索引
劃分特徵 (X) 和目標 (y)
X = data[['Opening Price', 'Highest Price', 'Lowest Price']] # 特徵 y = data['Closing Price'] # 目標
計算訓練集和測試集的切分點 (80% 訓練集,20% 測試集)
train_size = int(len(y) * 0.8) train, test = y[:train_size], y[train_size:]
使用 auto_arima 找到最佳 (p, d, q)
auto_model = auto_arima( train, seasonal=False, trace=True, error_action='ignore', suppress_warnings=True, stepwise=True )
打印自動選擇的 ARIMA 參數
print(f"Best ARIMA parameters: {auto_model.order}")
訓練 ARIMA 模型
arima_model = ARIMA(train, order=auto_model.order) arima_result = arima_model.fit()
計算殘差值
residuals = train - arima_result.fittedvalues
打印模型摘要
print(arima_result.summary())
預測未來的數據 (基於測試集的大小)
forecast_steps = len(test) forecast = arima_result.get_forecast(steps=forecast_steps) forecast_index = test.index # 使用測試集的索引 forecast_values = forecast.predicted_mean
繪圖:實際值、模型預測值、殘差
plt.figure(figsize=(14, 7))
原始數據與擬合值
plt.plot(y, label='Actual Prices', color='blue') plt.plot(arima_result.fittedvalues, label='Fitted Values', color='orange')
預測值
plt.plot(forecast_index, forecast_values, label='Forecast', color='green', linestyle='--')
添加標題和標籤
plt.title('Stock Price Analysis with ARIMA') plt.xlabel('Date') plt.ylabel('Prices') plt.grid()
圖例
plt.legend(loc='upper left')
顯示圖形
plt.show()
繪製殘差
plt.figure(figsize=(14, 5)) plt.plot(residuals, label='Residuals', color='red') plt.axhline(0, linestyle='--', color='black', alpha=0.7) plt.title('Residuals of the ARIMA Model') plt.xlabel('Index') plt.ylabel('Residuals') plt.grid() plt.legend(loc='upper left') plt.show()
將殘差與預測值輸出為文件
residuals.to_csv("residuals.csv", header=True) forecast_values.to_csv("forecast_values.csv", header=True)
###只需要預測值與真實值
繪圖:實際值、模型預測值、殘差
plt.figure(figsize=(14, 7))
原始數據與擬合值
plt.plot(y, label='Actual Prices', color='blue') plt.plot(arima_result.fittedvalues, label='Fitted Values', color='orange')
預測值
plt.plot(forecast_index, forecast_values, label='Forecast', color='green', linestyle='--')
添加標題和標籤
plt.title('Stock Price Analysis with ARIMA') plt.xlabel('Date') plt.ylabel('Prices') plt.grid()
圖例
plt.legend(loc='upper left')
顯示圖形
plt.show()
繪製殘差
plt.figure(figsize=(14, 5)) plt.plot(residuals, label='Residuals', color='red') plt.axhline(0, linestyle='--', color='black', alpha=0.7) plt.title('Residuals of the ARIMA Model') plt.xlabel('Index') plt.ylabel('Residuals') plt.grid() plt.legend(loc='upper left') plt.show()
將殘差與預測值輸出為文件
residuals.to_csv("residuals.csv", header=True) forecast_values.to_csv("forecast_values.csv", header=True)
- Assistant
It looks like you want to simplify your output and focus primarily on visualizing just the actual values and the forecasted values. Below I've modified your code, ensuring that only the actual and forecasted values are plotted and saved, while the residuals plotting and saving steps are removed. This will streamline the process based on your requirements.
Revised Code for Forecasting with ARIMA
Here's the simplified version of your code:
import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.arima.model import ARIMA from pmdarima import auto_arima # 讀取數據 file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\tsmc stock\stock price.csv" data = pd.read_csv(file_path) # 將日期轉為日期格式 (可選) data['Date'] = pd.to_datetime(data['Date']) data.set_index('Date', inplace=True) # 將日期設置為索引 # 劃分特徵 (X) 和目標 (y) X = data[['Opening Price', 'Highest Price', 'Lowest Price']] # 特徵 y = data['Closing Price'] # 目標 # 計算訓練集和測試集的切分點 (80% 訓練集,20% 測試集) train_size = int(len(y) * 0.8) train, test = y[:train_size], y[train_size:] # 使用 auto_arima 找到最佳 (p, d, q) auto_model = auto_arima( train, seasonal=False, trace=True, error_action='ignore', suppress_warnings=True, stepwise=True ) # 打印自動選擇的 ARIMA 參數 print(f"Best ARIMA parameters: {auto_model.order}") # 訓練 ARIMA 模型 arima_model = ARIMA(train, order=auto_model.order) arima_result = arima_model.fit() # 預測未來的數據 (基於測試集的大小) forecast_steps = len(test) forecast = arima_result.get_forecast(steps=forecast_steps) forecast_index = test.index # 使用測試集的索引 forecast_values = forecast.predicted_mean # 繪圖:實際值和預測值 plt.figure(figsize=(14, 7)) # 原始數據 plt.plot(y, label='Actual Prices', color='blue') # 預測值 plt.plot(forecast_index, forecast_values, label='Forecast', color='green', linestyle='--') # 添加標題和標籤 plt.title('Stock Price Analysis with ARIMA') plt.xlabel('Date') plt.ylabel('Prices') plt.grid() # 圖例 plt.legend(loc='upper left') # 顯示圖形 plt.show() # 將預測值與實際值輸出為文件 results = pd.DataFrame({'Actual': test, 'Forecast': forecast_values}) results.to_csv("forecast_results.csv", index=True, header=True) # 保存預測結果Key Changes Made:
-
Removed Residuals Calculation and Plotting:
- Since you only wanted to focus on actual and forecasted values, the residuals section has been omitted.
-
Forecast Results Output:
- Instead of outputting residuals and forecast values separately, I combined them into a single DataFrame containing both the actual values from the test set and the forecasted values for easy comparison. This DataFrame is then saved as
forecast_results.csv.
- Instead of outputting residuals and forecast values separately, I combined them into a single DataFrame containing both the actual values from the test set and the forecasted values for easy comparison. This DataFrame is then saved as
-
Updated Plotting Section:
- The plot now only includes actual prices and forecasted values, simplifying the visualization.
File Outputs:
- The resulting CSV file
forecast_results.csvwill contain the actual closing prices from your test dataset and the corresponding forecasted values.
This code should now fulfill your request efficiently! If you need further modifications or have additional questions, feel free to ask.
-
- User
plt.plot(forecast_index, forecast_values, label='Forecast', color='green', linestyle='--')
###預測值怪怪的,只是一條橫線,沒任何變化
- Assistant
If the forecast line appears as a flat line (i.e., doesn't change) in your plot, it could indicate an issue with how the ARIMA model is being fitted or how the forecast is generated. There are several potential reasons for this behavior:
-
Model Specification: If the ARIMA model parameters (
p,d,q) selected byauto_arimaare all set to zero or close to those values, the model will essentially predict the mean of the training data as the forecast. -
Data Characteristics: If the dataset has little variance or if it behaves in a way that the ARIMA model can't capture (e.g., non-stationarity), the predictions might reflect that by being flat.
-
Retraining Issues: If you're not updating the model correctly or if the training set does not provide enough information.
Step-by-Step Diagnosis
- Print the Selected ARIMA Parameters:
Make sure that the parameters selected by
auto_arima(stored inauto_model.order) are appropriate. Print these values to see if they make sense.
print(f"Best ARIMA parameters: {auto_model.order}")- Visualize the Training Data: Before fitting the ARIMA model, visualize your training data to ensure it’s not flat.
plt.figure(figsize=(14, 7)) plt.plot(train, label='Training Data', color='blue') plt.title('Training Data Visualization') plt.xlabel('Date') plt.ylabel('Closing Price') plt.legend() plt.grid() plt.show()- Inspect the ARIMA Model Summary: After fitting the model, inspect the summary to see the coefficients. If they are close to zero, that might explain the flat forecast.
print(arima_result.summary())- Use the Forecast Error:
Inspect the error and check if
forecast_valuescontains reasonable forecasts.
print(forecast_values)-
Check for Data Stationarity: Ensure your data is stationary. You can use tests like the Augmented Dickey-Fuller (ADF) test to check for stationarity.
-
Try Different Orders Manually: If the automatically selected parameters don't seem appropriate, consider setting the ARIMA order manually based on prior knowledge about the data.
Example Code Snippet
Here's how you can add some of these analyses into your existing code:
# Calculation of the optimal parameters print(f"Best ARIMA parameters: {auto_model.order}") # Visualize training data plt.figure(figsize=(14, 7)) plt.plot(train, label='Training Data', color='blue') plt.title('Training Data Visualization') plt.xlabel('Date') plt.ylabel('Closing Price') plt.legend() plt.grid() plt.show() # Fit the ARIMA model and print summary arima_model = ARIMA(train, order=auto_model.order) arima_result = arima_model.fit() print(arima_result.summary()) # Make forecasts forecast_steps = len(test) forecast = arima_result.get_forecast(steps=forecast_steps) forecast_index = test.index forecast_values = forecast.predicted_mean # Debug: Print forecast values print(f"Forecast Values: {forecast_values}") # Plot actual values and forecast plt.figure(figsize=(14, 7)) plt.plot(y, label='Actual Prices', color='blue') plt.plot(forecast_index, forecast_values, label='Forecast', color='green', linestyle='--') plt.title('Stock Price Analysis with ARIMA') plt.xlabel('Date') plt.ylabel('Prices') plt.grid() plt.legend(loc='upper left') plt.show()By performing these checks, you should be able to better diagnose why the forecast values appear as a flat line and adjust your model or data handling accordingly. If further adjustments are requested, feel free to ask!
-