def predict(): pytrend = TrendReq(timeout=(10,25), hl='en-US', tz=360) pytrend.build_payload(kw_list=keywords, timeframe='today 5-y', geo=c_code) five_years = pytrend.interest_over_time().reset_index() if five_years[keywords].sum().values[0] < 5: return 'not enough data', 'not enough data', 'not enough data', 'not enough data', 'not enough data' else: #five_years = five_years[five_years.isPartial == 'False'] five_years = five_years[:-1] five_years.drop('isPartial', axis=1, inplace=True) five_years.columns = ['ds', 'y'] temp = five_years.copy() temp['cap'] = temp['y'].max() temp['floor'] = temp['y'].min() m = Prophet() fit = m.fit(temp) periods = 90 future = m.make_future_dataframe(periods=periods) future["floor"] = temp['y'].min() future["cap"] = temp["y"].max() forecast = m.predict(future) fig = plot_plotly(m, forecast) fig.update_layout(template='plotly_white',title='{} "{}" Interest Prediction'.format(country,keywords[0]), xaxis={'title':'Date'}, yaxis={'title':'Intrest & Prediction'}) fig.update_traces(line_color="#F66162", selector=dict(line_color='#0072B2')) fig.update_traces(marker_color="royalblue", selector=dict(marker_color='black')) comp = plot_components_plotly(m, forecast) comp.update_layout(template='plotly_white',title='{} "{}" Seasonality Prediction'.format(country,keywords[0]),yaxis={'title':'Prediction'}) comp.update_traces(line_color="#F66162", selector=dict(line_color='#0072B2')) comp.update_traces(marker_color="royalblue", selector=dict(marker_color='black')) return fig, comp, forecast, periods, pytrend
def run_forecast(category, state, seasonality, periods, uncertainty_samples, years): t0 = time.time() col = f"('{category}', '{state}')" df = walmart[["date", col]].rename(columns={"date": "ds", col: "y"}) m, forecast = run_prophet( df, weekly_seasonality=seasonality, periods=periods, uncertainty_samples=uncertainty_samples, start=years[0], end=years[1], ) # Plot figures margin = dict(l=30, r=30, t=80, b=30) fig_forecast = plot_plotly(m, forecast).update_layout( title="Forecasting with Prophet", width=None, height=None, margin=margin, ) fig_components = plot_components_plotly(m, forecast).update_layout( title="Seasonal Components", width=None, height=None, margin=margin) t1 = time.time() print(f"Training and Inference time: {t1-t0:.2f}s.") return fig_forecast, fig_components
def update_predictions(ticker): dict_timelines = portfoliomanager.download_stock_timelines([ticker]) df_timeline_with_future, m = portfoliomanager.predict_future(dict_timelines[ticker]) fig_future = plot_plotly(m, df_timeline_with_future) fig_components = plot_components_plotly(m, df_timeline_with_future) return fig_future, fig_components
def createComponentLayout(signal, frequency, holidayDropdown, holidayScale, seasonalityScale, changepointScale, seasonalityMode, contents, filename, paramSearch): print(signal, frequency, holidayDropdown, holidayScale, seasonalityScale, changepointScale, seasonalityMode, filename, paramSearch) if signal == 'VOID': return None if signal != 'NOTIFY': return html.Div('Encountered an error : ' + signal, style={'margin-left': '1rem'}) df = parseContents(contents, filename) model = generateModel(frequency, None, holidayScale, seasonalityScale, changepointScale, seasonalityMode, df, paramSearch) future = model.make_future_dataframe(periods=int(0.1 * len(df)), freq=frequency) forecast = model.predict(future) fig = plot_components_plotly(model, forecast) return dcc.Graph(figure=fig)
df_treino = df_treino.rename(columns={"Date": 'ds', 'Close': 'y'}) modelo = Prophet() modelo.fit(df_treino) futuro = modelo.make_future_dataframe(periods=n_dias, freq='B') previsao = modelo.predict(futuro) st.subheader('Previsão') st.write(previsao[['ds', 'yhat','yhat_lower','yhat_upper' ]].tail(n_dias)) #grafico grafico1 = plot_plotly(modelo, previsao) st.plotly_chart(grafico1) #grafico2 grafico2 = plot_components_plotly(modelo, previsao) st.plotly_chart(grafico2)
future = m.make_future_dataframe(periods=0) forecast = m.predict(future) # print only values of interest, ds=date, yhat=forecasted value # yhat_lower=low forecast value, yhat_upper=high forecast value print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]) # plot predictions fig = plot_plotly(m, forecast) fig.update_layout(title=sensor_name + ' forecast for November-December 2019', xaxis_title="Day", yaxis_title=sensor_name) fig.show() # check if there is seasonality+trend fig = plot_components_plotly(m, forecast) fig.update_layout(title=sensor_name + ' characteristics-seasonality') fig.show() # define a function to make a df containing the prediction and the actual values def make_comparison_dataframe(historical, forecast): return forecast.set_index('ds')[['yhat', 'yhat_lower', 'yhat_upper' ]].join(historical.set_index('ds')) cmp_df = make_comparison_dataframe(df, forecast) def mean_absolute_percentage_error(y_true, y_pred): y_true, y_pred = np.array(y_true), np.array(y_pred)
# test serisi yaratılması train = turkey.drop(turkey.index[:-18]) print(train) model.plot_components(forecast) from sklearn.metrics import mean_absolute_error, mean_squared_log_error,classification_report # MAE ve hata hesaplama y_true = turkey['y'][-len(future):].values y_pred = forecast['yhat'].values mae = mean_absolute_error(y_true, y_pred) loss = mean_squared_log_error(y_true,y_pred) print("loss score",loss) print('MAE: %.3f' % mae) # tahmin edilenle asıl veri karşılaştırma pyplot.plot(y_true, label='Actual') pyplot.plot(y_pred, label='Predicted') pyplot.legend() pyplot.show() from fbprophet.plot import plot_plotly, plot_components_plotly plot_plotly(model, forecast) plot_components_plotly(model, forecast)
from fbprophet import Prophet from fbprophet.plot import plot_plotly, plot_components_plotly from sklearn.metrics import mean_absolute_error import pandas as pd dataset = pd.read_csv('acoes.csv') # dataset.set_index(keys=['Date'], inplace=True) dataset = dataset[['Date', 'BOVA']].rename(columns={'Date': 'ds', 'BOVA': 'y'}) # Modelo modelo = Prophet() modelo.fit(dataset) futuro = modelo.make_future_dataframe(periods=90) previsoes = modelo.predict(futuro) # Gráfico das previsões modelo.plot(previsoes, xlabel='Data', ylabel='Preço') modelo.plot_components(previsoes) plot_plotly(modelo, previsoes) plot_components_plotly(modelo, previsoes) # Avaliação do modelo pred = modelo.make_future_dataframe(periods=0) previsoes = modelo.predict(pred) previsoes = previsoes['yhat'].tail(365) mean_absolute_error(teste, previsoes)
def plotly_components_plot(model, forecast, **kwargs): return plot_components_plotly(model, forecast, **kwargs)
# let's check the forecasted dates we're predicting for future_dates.tail() # let's build our forecasts forecast = simple_model.predict(future_dates) forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail() # let's do some visualiztions with our simple timeseries model simple_model_plot = simple_model.plot(forecast, uncertainty=True) simple_model_plot_w_chgpts = add_changepoints_to_plot( simple_model_plot.gca(), simple_model, forecast) plt.show() # let's look at the individual components for each of the models we built plotly_comp_model_plt = plot_components_plotly(simple_model, forecast) # Now let's do cross validation for the models we built and specify the performance metrics and plot them perf_metrics = ['mse', 'rmse', 'mae', 'mape', 'mdape', 'coverage'] client = Client(processes=False) simple_model.cv = cross_validation(simple_model, period='365 days', horizon='720 days', parallel='dask') simple_model.pm = performance_metrics(simple_model.cv, metrics=perf_metrics)