def prophet_forecast(self, train_start, train_end, test_start, test_end): from sys import platform if platform == "linux" or platform == "linux2": from prophet import Prophet # linux elif platform == "darwin": from fbprophet import Prophet # OS X elif platform == "win32": from fbprophet import Prophet # Windows... data = self.data.reset_index() data.rename(columns={'Date': 'ds', self.column: 'y'}, inplace=True) # FIXME and take user input size = len(data) df_train = data.iloc[int(-size * .10):, :] df_test = data.iloc[int(-size * .20):, :] model_prophet = Prophet(seasonality_mode='additive') model_prophet.add_seasonality(name='monthly', period=30.5, fourier_order=5) model_prophet.fit(df_train) df_future = model_prophet.make_future_dataframe(periods=365) df_pred = model_prophet.predict(df_future) model_prophet.plot(df_pred) plt.tight_layout() plt.title('Prophet Forecast') plt.savefig(os.path.join(img_dirp, f'img/prophet_forecast.png')) model_prophet.plot_components(df_pred) plt.tight_layout() plt.savefig(os.path.join(img_dirp, 'img/components.png')) # merge test set with predicted data and plot accuracy of model's predictions selected_columns = ['ds', 'yhat_lower', 'yhat_upper', 'yhat'] df_pred = df_pred.loc[:, selected_columns].reset_index(drop=True) df_test = df_test.merge(df_pred, on=['ds'], how='left') df_test.ds = pd.to_datetime(df_test.ds) df_test.set_index('ds', inplace=True) fig, ax = plt.subplots(1, 1) ax = sns.lineplot( data=df_test[['y', 'yhat_lower', 'yhat_upper', 'yhat']]) ax.fill_between(df_test.index, df_test.yhat_lower, df_test.yhat_upper, alpha=0.3) ax.set(title=f'{self.column} - actual vs. predicted', xlabel='Date', ylabel='{self.column}') plt.tight_layout() plt.savefig(os.path.join(img_dirp, 'img/actual_v_predicted.png'))
import pandas as pd from prophet import Prophet # float_precision='high' required for pd.read_csv to match precision of Rover.read_csv df = pd.read_csv('examples/example_wp_log_R.csv', float_precision='high') df['cap'] = 8.5 m = Prophet(growth='logistic') m.fit(df, seed=123) future = m.make_future_dataframe(periods=365) future['cap'] = 8.5 forecast = m.predict(future) print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()) m.plot(forecast).savefig('/tmp/py_logistic.png') m.plot_components(forecast).savefig('/tmp/py_logistic2.png')
import pandas as pd from prophet import Prophet # float_precision='high' required for pd.read_csv to match precision of Rover.read_csv df = pd.read_csv('examples/example_wp_log_peyton_manning.csv', float_precision='high') m = Prophet() m.add_country_holidays(country_name='US') m.fit(df, seed=123) future = m.make_future_dataframe(periods=365) forecast = m.predict(future) print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()) m.plot(forecast).savefig('/tmp/py_country_holidays.png') m.plot_components(forecast).savefig('/tmp/py_country_holidays2.png')
import pandas as pd from prophet import Prophet # float_precision='high' required for pd.read_csv to match precision of Rover.read_csv df = pd.read_csv('examples/example_yosemite_temps.csv', float_precision='high') m = Prophet(changepoint_prior_scale=0.01) m.fit(df, seed=123) future = m.make_future_dataframe(periods=300, freq='H') forecast = m.predict(future) print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()) m.plot(forecast).savefig('/tmp/py_subdaily.png') m.plot_components(forecast).savefig('/tmp/py_subdaily2.png')
model.fit(data_forecast) st.header('How far into the future to forecast') with st.echo(): future = model.make_future_dataframe(periods=365) st.dataframe(future) st.header('Create the forecasts') with st.echo(): forecast = model.predict(future) st.write(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]) st.header('Plot the forecast') with st.echo(): fig1 = model.plot(forecast) fig2 = model.plot_components(forecast) st.write(fig1) st.write(fig2) prophet_chart = alt.Chart(data).mark_circle().encode(x='Date', y='Open', tooltip=['Date', 'Open']) st.write(prophet_chart) st.markdown('----') path = st.text_input('CSV file path') if path: df = pd.read_csv(path) df
# Общий вариант df2 = df2.rename(columns={'payment_day': 'Days'}) df2['Days'] = pd.DatetimeIndex(df2['Days']) # Визуализация текущих данных ax = df2.set_index('Days').plot(figsize=(12, 8)) ax.set_ylabel("Payment value") ax.set_xlabel('Date') plt.show() # Прогнозирование my_model = Prophet(interval_width=0.95) my_model.fit(df2) future_dates = my_model.make_future_dataframe(periods=30, freq="day") print(future_dates.tail()) forecast = my_model.predict(future_dates) # визуализации прогнозируемых данных # Prophet показывает значения временных рядов (черные точки), # прогнозируемые значения (синяя линия) # и интервалы неопределенности прогнозов (синие заштрихованные области). my_model.plot(forecast, uncertainty=True) # компоненты прогнозов my_model.plot_components(forecast)
import pandas as pd from prophet import Prophet # float_precision='high' required for pd.read_csv to match precision of Rover.read_csv df = pd.read_csv('examples/example_air_passengers.csv', float_precision='high') m = Prophet(seasonality_mode='multiplicative') m.fit(df, seed=123) future = m.make_future_dataframe(50, freq='MS') forecast = m.predict(future) print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()) m.plot(forecast).savefig('/tmp/py_multiplicative_seasonality.png') m.plot_components(forecast).savefig('/tmp/py_multiplicative_seasonality2.png')
df.drop_duplicates(inplace=True) if not df.index.is_monotonic_increasing: df.sort_index(inplace=True) # Create Price value df['y'] = (df[f'open'] + df[f'close']) / 2 # Resample data by by the mean of the day df_daily = df.resample(interval).mean() # (2) Prepare Data : ds:y df_daily['ds'] = df_daily.index df_daily_prophet = df_daily[['ds', 'y']] df_daily_prophet = df_daily_prophet.reset_index() df_daily_prophet = df_daily_prophet.drop(columns=['time']) m = Prophet() m.fit(df_daily_prophet) print(f'Model is trained on {len(df_daily_prophet)} data') future = m.make_future_dataframe(periods=10) # Python forecast = m.predict(future) predictions = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(10) predictions.to_csv(name + '.csv') fig1 = m.plot(forecast) plt.title(name) plt.savefig(name) plt.show() fig2 = m.plot_components(forecast) plt.title(name + 'Component') plt.show()
import pandas as pd from prophet import Prophet # float_precision='high' required for pd.read_csv to match precision of Rover.read_csv df = pd.read_csv('examples/example_wp_log_peyton_manning.csv', float_precision='high') def nfl_sunday(ds): date = pd.to_datetime(ds) if date.weekday() == 6 and (date.month > 8 or date.month < 2): return 1 else: return 0 df['nfl_sunday'] = df['ds'].apply(nfl_sunday) m = Prophet() m.add_regressor('nfl_sunday') m.fit(df) future = m.make_future_dataframe(periods=365) future['nfl_sunday'] = future['ds'].apply(nfl_sunday) forecast = m.predict(future) m.plot(forecast).savefig('/tmp/py_regressors.png') m.plot_components(forecast).savefig('/tmp/py_regressors2.png')
import pandas as pd from prophet import Prophet # float_precision='high' required for pd.read_csv to match precision of Rover.read_csv df = pd.read_csv('examples/example_wp_log_peyton_manning.csv', float_precision='high') m = Prophet(growth='flat') m.fit(df, seed=123) print(m.params) future = m.make_future_dataframe(periods=365) forecast = m.predict(future) print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()) m.plot(forecast).savefig('/tmp/py_flat.png') m.plot_components(forecast).savefig('/tmp/py_flat2.png')
import pandas as pd from prophet import Prophet # float_precision='high' required for pd.read_csv to match precision of Rover.read_csv df = pd.read_csv('examples/example_wp_log_peyton_manning.csv', float_precision='high') m = Prophet(weekly_seasonality=False) m.add_seasonality(name='monthly', period=30.5, fourier_order=5) m.fit(df, seed=123) future = m.make_future_dataframe(periods=365) forecast = m.predict(future) print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()) m.plot(forecast).savefig('/tmp/py_custom_seasonality.png') m.plot_components(forecast).savefig('/tmp/py_custom_seasonality2.png')
import pandas as pd from prophet import Prophet # float_precision='high' required for pd.read_csv to match precision of Rover.read_csv df = pd.read_csv('examples/example_wp_log_peyton_manning.csv', float_precision='high') m = Prophet() m.fit(df, seed=123) future = m.make_future_dataframe(periods=365) forecast = m.predict(future) print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()) m.plot(forecast).savefig('/tmp/py_linear.png') m.plot_components(forecast).savefig('/tmp/py_linear2.png')