I’m trying to plot a curve_fit for the S&P 500.
I’m successful (I think) at performing a linear fit/plot. When I try to get an exponential curve_fit to work, I get this error:
Optimal parameters not found: Number of calls to function has reached maxfev = 800.
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
from scipy.optimize import curve_fit
# get data
df = yf.download("SPY", interval = '1mo')
df = df.reset_index()
def func(x, a, b):
return a * x + b
# ?? return a * np.exp(-b * x) + c
# ?? return a*(x**b)+c
# ?? return a*np.exp(b*x)
# create data arrays
# convert Date to numeric for curve_fit ??
xdata = df['Date'].to_numpy().astype(np.int64)//10**9
ydata = df['Close'].to_numpy()
# p0 = (?, ?, ?) use guesses?
popt, pcov = curve_fit(func, xdata, ydata)
print(popt)
y_pred = func(xdata, *popt)
plt.plot(xdata, ydata)
plt.plot(xdata, y_pred, '-')
plt.show()
Am I dealing with dates correctly?
Should I be doing a p0 initial guess?
This question/solution may provide some clues:
text
It would be nice to have the x-axis labeled in a date format (but not important right now).