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']) 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 )
###幫我寫train/test,分出預測值與真實值
- Assistant
當然可以。在您的代碼中,我們已經使用
auto_arima訓練了模型。接下來,我們將使用訓練好的模型來對測試集進行預測,並將預測值與真實值進行比較。以下是如何實現這個過程的代碼:# 對測試集進行預測 n_periods = len(test) # 測試集的長度 forecast, conf_int = auto_model.predict(n_periods=n_periods, return_conf_int=True) # 建立預測結果的 DataFrame forecast_index = test.index # 使用測試集的索引作為預測的索引 forecast_df = pd.DataFrame(forecast, index=forecast_index, columns=['Forecast']) # 將預測結果合併真實值 results = pd.DataFrame({'Actual': test, 'Forecast': forecast_df['Forecast']}) # 繪製預測結果 plt.figure(figsize=(12, 6)) plt.plot(results.index, results['Actual'], label='Actual Closing Price', color='blue') plt.plot(results.index, results['Forecast'], label='Forecasted Closing Price', color='orange') plt.title('Actual vs Forecasted Closing Price') plt.xlabel('Date') plt.ylabel('Price') plt.legend() plt.show() # 選擇進一步度量模型的表現 (例如計算 RMSE) from sklearn.metrics import mean_squared_error import numpy as np rmse = np.sqrt(mean_squared_error(results['Actual'], results['Forecast'])) print(f'Root Mean Squared Error: {rmse}')這段代碼執行了以下幾個步驟:
- 預測:使用從 得到的模型對測試集進行預測。
- 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 )
對測試集進行預測
n_periods = len(test) # 測試集的長度 forecast, conf_int = auto_model.predict(n_periods=n_periods, return_conf_int=True)
- Assistant
出現
ValueError: Input contains NaN的錯誤,通常是由於數據中包含缺失值(NaN)。在進行任何統計或機器學習分析之前,需要清理數據,處理這些缺失值。這裡有幾個步驟來幫助您檢查和處理缺失值:
- 檢查缺失值:首先,您可以檢查整個數據集是否有缺失值。
- 填補或刪除缺失值:根據情況選擇合適的方法來處理缺失值。
以下是更新的代碼片段,以便您可以檢查和處理缺失值後再進行預測:
# 檢查數據中是否有缺失值 if data.isnull().values.any(): print("數據中存在缺失值,將進行處理。") # 顯示每一列的缺失值數量 print(data.isnull().sum()) # 此處可以選擇填補缺失值或刪除缺失值。我們這裡選擇刪除缺失值。 data.dropna(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 ) # 對測試集進行預測 n_periods = len(test) # 測試集的長度 forecast, conf_int = auto_model.predict(n_periods=n_periods, return_conf_int=True) # 建立預測結果的 DataFrame forecast_index = test.index # 使用測試集的索引作為預測的索引 forecast_df = pd.DataFrame(forecast, index=forecast_index, columns=['Forecast']) # 將預測結果合併真實值 results = pd.DataFrame({'Actual': test, 'Forecast': forecast_df['Forecast']}) # 繪製預測結果 plt.figure(figsize=(12, 6)) plt.plot(results.index, results['Actual'], label='Actual Closing Price', color='blue') plt.plot(results.index, results['Forecast'], label='Forecasted Closing Price', color='orange') plt.title('Actual vs Forecasted Closing Price') plt.xlabel('Date') plt.ylabel('Price') plt.legend() plt.show() # 計算 RMSE from sklearn.metrics import mean_squared_error import numpy as np rmse = np.sqrt(mean_squared_error(results['Actual'], results['Forecast'])) print(f'Root Mean Squared Error: {rmse}') - User
File: arima_forecast.py
import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.arima.model import ARIMA from sklearn.metrics import mean_squared_error import numpy as np
Step 1: Read the CSV file
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\tsmc stock\stock price.csv" df = pd.read_csv(file_path)
Step 2: Preprocess the data
df['Date'] = pd.to_datetime(df['Date'], format='%Y/%m/%d') df.set_index('Date', inplace=True)
Step 3: Select the target variable
closing_prices = df['Closing Price']
Step 4: Split into training and testing sets
train_size = int(len(closing_prices) * 0.8) train, test = closing_prices[:train_size], closing_prices[train_size:]
Step 5: Fit the ARIMA model
(p, d, q) are the parameters for the ARIMA model
- Assistant
如果您想要將實際值和預測值分開繪圖,您可以簡單地為實際值和預測值創建兩個不同的圖形,並且可以設置相同的標籤和顏色,以保證它們的可讀性。以下是更新的代碼,將實際值和預測值分開繪製:
# File: arima_forecast.py import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.arima.model import ARIMA from sklearn.metrics import mean_squared_error import numpy as np # Step 1: Read the CSV file file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\tsmc stock\stock price.csv" df = pd.read_csv(file_path) # Step 2: Preprocess the data df['Date'] = pd.to_datetime(df['Date'], format='%Y/%m/%d') df.set_index('Date', inplace=True) # Step 3: Select the target variable closing_prices = df['Closing Price'] # Step 4: Split into training and testing sets train_size = int(len(closing_prices) * 0.8) train, test = closing_prices[:train_size], closing_prices[train_size:] # Step 5: Fit the ARIMA model # (p, d, q) are the parameters for the ARIMA model model = ARIMA(train, order=(5, 1, 0)) arima_result = model.fit() # Step 6: Make predictions predictions = arima_result.forecast(steps=len(test)) forecast_index = test.index # Step 7: Evaluate the model mse = mean_squared_error(test, predictions) print(f"Mean Squared Error: {mse}") # Step 8: Plot the actual values plt.figure(figsize=(12, 6)) plt.plot(closing_prices, label='Actual Closing Prices', color='blue') plt.axvline(x=train.index[-1], color='gray', linestyle='--', label='Train-Test Split') plt.title('Actual Closing Prices') plt.xlabel('Date') plt.ylabel('Closing Price') plt.legend() plt.show() # Step 9: Plot the forecasted values plt.figure(figsize=(12, 6)) plt.plot(forecast_index, predictions, label='Forecasted Prices', color='red') plt.axvline(x=train.index[-1], color='gray', linestyle='--', label='Train-Test Split') plt.title('Forecasted Closing Prices') plt.xlabel('Date') plt.ylabel('Closing Price') plt.legend() plt.show() - User
首先把file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\tsmc stock\stock price.csv" 給head出來,之後把所需的進行正規化標準化之後,實行訓練並預測出來
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.