Exemple #1
0
def main():
    path_example = "../examples"
    """example 1"""
    df = read_dataframe(path_examples=path_example, data_idx=4)
    model, future, forecasted = forecast(
        df, periods=1096,
        showflag=True)  # uncertainty intervals seem way too wide

    df.loc[(df['ds'] > '2010-01-01') & (df['ds'] < '2011-01-01'), 'y'] = None
    model_removed = Prophet().fit(df)
    fig = model_removed.plot(
        model_removed.predict(future)
    )  # model with missing data. prediction of whole data with future.
    fig.set_figheight(18)
    fig.set_figwidth(9)
    plt.title('prediction (model with missing data)')
    plt.show()
    """example 2"""
    df2 = read_dataframe(path_examples=path_example, data_idx=5)
    model2, future2, forecasted2 = forecast(
        df2, periods=1096,
        showflag=True)  # extreme outlieres in June 2015 mess up estimate.

    df2.loc[(df2['ds'] > '2015-06-01') & (df2['ds'] < '2015-06-30'),
            'y'] = None
    model2_removed = Prophet().fit(df2)  # Same approach as previous example
    fig = model2_removed.plot(model2_removed.predict(future2))
    fig.set_figheight(18)
    fig.set_figwidth(9)
    plt.title('prediction2 (model with missing data)')
    plt.show()
Exemple #2
0
    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'))
Exemple #3
0
def forecast(df, periods, showflag=True):
    m = Prophet()
    m.fit(df)
    future = m.make_future_dataframe(periods=periods)
    predict = m.predict(future)

    if showflag:
        fig = m.plot(predict)
        fig.set_figheight(18)
        fig.set_figwidth(9)
        plt.title("forcasted")
        plt.show()

    return m, future, predict
Exemple #4
0
    def fit_predict_model(dataframe,
                          interval_width=0.99,
                          changepoint_range=0.8):
        m = Prophet(daily_seasonality=False,
                    yearly_seasonality=False,
                    weekly_seasonality=False,
                    seasonality_mode='multiplicative',
                    interval_width=interval_width,
                    changepoint_range=changepoint_range)
        m = m.fit(dataframe)

        forecast = m.predict(dataframe)
        forecast['fact'] = dataframe['y'].reset_index(drop=True)

        print('Displaying Prophet plot')
        fig1 = m.plot(forecast)

        return forecast
Exemple #5
0
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')
Exemple #6
0
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')
Exemple #7
0
    model = Prophet()
    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)
Exemple #8
0
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')
Exemple #9
0
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')
Exemple #10
0
# Общий вариант

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)
    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()
Exemple #12
0
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')
Exemple #13
0
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')
Exemple #14
0
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')
#FORECAST OF PROPERTY SALES FOR FIRST HALF
#Libraries
import pandas as pd
from prophet import Prophet
#Dataset
df1 = datasets[3]
#Change to date to datetime
df1['date'] = pd.to_datetime(df1['date'])
#Rename Columns for Forecast
df1.columns = ['ds', 'y']
#Create Instance of Prophet
p = Prophet(interval_width=0.92, daily_seasonality=True)
#Training The Model
model = p.fit(df1)
#Make Predections
future = p.make_future_dataframe(periods=150, freq='D')
forecast_prediction = p.predict(future)
#Visualize Predection
plot1 = p.plot(forecast_prediction)
#FORECAST COMOPONENTS IF NEEDED
#plot2 = p.plot_components(forecast_prediction)
Exemple #16
0
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')