Coding by ChatGPT — An Asset Price Forecasting Program on Colab
Program Coding by ChatGPT 1 — Stock Price Forecast by Prophet
ChatGPT is well known to be very powerful in coding. Here is one of my tests. We have discussed about writing Python codes to forecast stock prices by Prophet on Colab (Yiu, 2021), but it has become outdated and not necessary now because ChatGPT can do the coding on our behalf.
Here for example, I simply ask ChatGPT to help write a Python code for Colab use to retrieve Yahoo finance stock price data of Apple Inc. from 2019 to 2023, and forecast its prices in the next three months, it immediately generates the full program for trial (Figure 1). There are bugs to be fixed before it works.
The Codes — data retrieved from Yahoo finance
Here shows the codes for retrieving Yahoo finance data of Apple Inc. from 2019–2023 and forecasting its prices by using Prophet library. The codes are similar to the one in Yiu (2021).
!pip install prophet
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
from prophet import Prophet
# Retrieve the stock price data for Apple Inc. from Yahoo Finance
symbol = "AAPL"
start_date = "2019-01-01"
end_date = "2023-12-31"
data = yf.download(symbol, start=start_date, end=end_date)
# Extract the "Close" prices
prices = data["Close"]
# Reset index and rename columns for Prophet compatibility
prices = prices.reset_index()
prices = prices.rename(columns={"Date": "ds", "Close": "y"})
# Create and fit the Prophet model
model = Prophet()
model.fit(prices)
# Forecast the next three months
future = model.make_future_dataframe(periods=90)
forecast = model.predict(future)
# Plot the forecasted values
plt.figure(figsize=(10, 6))
plt.plot(prices["ds"], prices["y"], label="Historical")
plt.plot(forecast["ds"], forecast["yhat"], color="red", label="Forecast")
plt.fill_between(forecast["ds"], forecast["yhat_lower"], forecast["yhat_upper"], color="gray", alpha=0.3, label="Confidence Intervals")
plt.title("Apple Inc. Stock Price Forecast")
plt.xlabel("Date")
plt.ylabel("Price ($)")
plt.legend()
plt.show()
The Prophet Forecast Results
Figure 2 shows the forecast it produces. It provides the original stock price index (blue line) from 2019 to 2023 (June), and the 90 days forecasts (red line) plus the upper and lower confidence intervals (grey shadows).
Program Coding by ChatGPT 2 — House Price Forecast by SARIMA
However, not all price data can be automatically retrieved from webpages, here for example, I asked ChatGPT to help write a Python code for Colab use to forecast the OECD housing price index of New Zealand, it generated the program below, but the url does not work (Figure 3). I then suggested ChatGPT how to code to retrieve data from a google drive.
The data are available from OECD housing data at https://data.oecd.org/price/housing-prices.htm. Unfortunately, the url link provided by ChatGPT does not work and so the following example code creates a .csv file at google drive with columns 1,2,3 as TIME, PRICE, and LOCATION, where TIME shows the date, PRICE is the house price index, and LOCATION shows the location code NZL.
ChatGPT suggests using statsmodels.tsa.statespace.sarima to carry out the forecasting task. It is an ARIMA model, which is very commonly used for time series forecasting. More information of statsmodels and SARIMA model can be found at https://www.statsmodels.org/stable/statespace.html# and https://barnesanalytics.com/sarima-models-using-statsmodels-in-python/
The Codes — data retrieved from Google Drive
Here shows the codes for the forecasting of OECD housing price index of New Zealand, with the .csv data file pre-saved at your google drive in the directory and named as /Colab Notebooks/housing_prices.csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.statespace.sarimax import SARIMAX
from google.colab import drive
# Load the data from the local CSV file
drive.mount('/content/drive/')
data = pd.read_csv("drive/MyDrive/Colab Notebooks/housing_prices.csv")
data.head()
# Convert the "TIME" column to datetime
data['TIME'] = pd.to_datetime(data['TIME'])
# Set the "TIME" column as the index
data.set_index('TIME', inplace=True)
# Plot the original data
plt.figure(figsize=(10, 6))
plt.plot(data['PRICE'])
plt.title('OECD Housing Price Index - New Zealand')
plt.xlabel('YEAR')
plt.ylabel('INDEX VALUE')
plt.show()
# Perform forecasting
model = SARIMAX(data['PRICE'], order=(1, 1, 1), seasonal_order=(1, 0, 1, 12))
results = model.fit()
# Forecast for the next 12 months
forecast = results.get_forecast(steps=12)
# Get the predicted values and confidence intervals
predicted_values = forecast.predicted_mean
conf_int = forecast.conf_int()
# Plot the forecasted values and confidence intervals
plt.figure(figsize=(10, 6))
plt.plot(data.index, data['PRICE'], label='Original')
plt.plot(predicted_values.index, predicted_values, color='red', label='Forecast')
plt.fill_between(conf_int.index, conf_int.iloc[:, 0], conf_int.iloc[:, 1], color='gray', alpha=0.3, label='Confidence Intervals')
plt.title('OECD Housing Price Index - New Zealand (Forecast)')
plt.xlabel('YEAR')
plt.ylabel('INDEX VALUE')
plt.legend()
plt.show()
The SARIMA Forecast Results
Figure 4 shows the forecast it produces. It provides the original house price index (blue line) from 2001Q4 to 2022Q3, and the 12 quarters forecasts (red line) plus the upper and lower confidence intervals (grey shadows).
As the OECD data is a bit outdated, the forecasts for 2022Q4 and 2023Q1 seem to be accurate, as Figure 5 shows that the recent falls of the house prices of New Zealand have been levelled off.
References
Yiu, C.Y. (2021) Forecasting by FB Prophet in Colab, Medium, May 31. https://ecyy.medium.com/forecasting-by-fb-prophet-in-colab-c9d4db2d4195