<jupyter_start><jupyter_text>For API<jupyter_code>df = pd.DataFrame(exp_list)
df['date'] = pd.to_datetime(df['date'])
df['date'] = df['date'].dt.year.astype('str') + '-' + df['date'].dt.month.astype('str') + '-01'
df['date'] = pd.to_datetime(df['date'])#groupby date and sum the sales
df = df.groupby('date').amount.sum().reset_index()
latest_dt = df['date'].max()
# 1 quarter
datetime_series = pd.Series(
    pd.date_range(latest_dt, periods=3, freq="M")
)
df_test = pd.DataFrame()
df_test['date'] = datetime_series
df_test['amount'] = 0
df_test
#create a new dataframe to model the difference
df_diff = df.copy()
df_diff = df_diff.append(df_test, ignore_index=True)

df_diff['prev_amount'] = df_diff['amount'].shift(1)#drop the null values and calculate the difference
df_diff = df_diff.dropna()
df_diff['diff'] = (df_diff['amount'] - df_diff['prev_amount'])
df_supervised = df_diff.drop(['prev_amount'],axis=1)#adding lags
#add previous sales to the next row
for inc in range(1,4):
    field_name = 'lag_' + str(inc)
    df_supervised[field_name] = df_supervised['diff'].shift(inc)#drop null values

df_supervised = df_supervised.dropna().reset_index(drop=True)
df_supervised
from keras.layers import Dense
from keras.models import Sequential
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler

df_model = df_supervised.drop(['amount','date'],axis=1)#split train and test set
train_set, test_set = df_model[0:-3].values, df_model[-3:].values
# train_set = df_model.values
# test_set = df_test.values

scaler = MinMaxScaler(feature_range=(-1, 1))
scaler = scaler.fit(train_set)
# reshape training set
train_set = train_set.reshape(train_set.shape[0], train_set.shape[1])
train_set_scaled = scaler.transform(train_set)
# reshape test set
test_set = test_set.reshape(test_set.shape[0], test_set.shape[1])
test_set_scaled = scaler.transform(test_set)


X_train= train_set_scaled[:, 1:]
y_train =  train_set_scaled[:, 0:1]
X_train = X_train.reshape(X_train.shape[0], 1, X_train.shape[1])
model = Sequential()
model.add(LSTM(4, batch_input_shape=(1, X_train.shape[1], X_train.shape[2]), stateful=True))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X_train, y_train, epochs=10, batch_size=1, verbose=1, shuffle=False)
X_test, y_test = test_set_scaled[:, 1:], test_set_scaled[:, 0:1]
X_test = X_test.reshape(X_test.shape[0], 1, X_test.shape[1])

y_pred = model.predict(X_test,batch_size=1)#for multistep prediction, you need to replace X_test values with the predictions coming from t-1
import numpy as np
#reshape y_pred
y_pred = y_pred.reshape(y_pred.shape[0], 1, y_pred.shape[1])#rebuild test set for inverse transform
pred_test_set = []
for index in range(0,len(y_pred)):
    print(np.concatenate([y_pred[index],X_test[index]],axis=1))
    pred_test_set.append(np.concatenate([y_pred[index],X_test[index]],axis=1))#reshape pred_test_set
pred_test_set = np.array(pred_test_set)
pred_test_set = pred_test_set.reshape(pred_test_set.shape[0], pred_test_set.shape[2])#inverse transform
pred_test_set_inverted = scaler.inverse_transform(pred_test_set)
#create dataframe that shows the predicted sales
result_list = []
sales_dates = list(df[-7:].date)
act_sales = list(df[-7:].amount)
for index in range(0,len(pred_test_set_inverted)):
    result_dict = {}
    result_dict['pred_value'] = int(pred_test_set_inverted[index][0] + act_sales[index])
    result_dict['date'] = sales_dates[index+1]
    result_list.append(result_dict)
df_result = pd.DataFrame(result_list)#for multistep prediction, replace act_sales with the predicted sales

df_result

model.predict()<jupyter_output><empty_output><jupyter_text>Prophet<jupyter_code># Python
from fbprophet import Prophet
m = Prophet()
df = pd.DataFrame(exp_list)
df['ds'] = pd.to_datetime(df['date'])
# df['ds'] = df['ds'].dt.year.astype('str') + '-' + df['date'].dt.month.astype('str') + '-01'
# df['ds'] = pd.to_datetime(df['ds'])#groupby date and sum the sales
df['y'] = df['amount']

prophet_df = pd.DataFrame()
prophet_df['ds'] = df['ds']
prophet_df['y'] = df['y']

m.fit(prophet_df)
future = m.make_future_dataframe(periods=3, freq='MS')
future.tail()
# Python
forecast = m.predict(future)
forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()

# Python
fig1 = m.plot(forecast)
d = forecast[['ds','yhat']].tail(12).to_dict(orient='records')
d<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16051912568306012, 'fraction_numerical': 0.013888888888888888, 'mean_word_length': 7.19589552238806, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '374685', 'license': 'MIT', 'n_tokens_mistral': 1691, 'n_tokens_neox': 1654, 'n_words': 302, 'path': 'app/core/exp_pred.ipynb', 'repo_name': 'Acquil/greevil-app', 'size': '4392'}