Exemplo n.º 1
0
def fbp(ts, stock, pers=90):
    """
    Plots the forecast of the FBProphet model
    """
    plt.style.use('fivethirtyeight')

    # Instantiating the FBP
    mod = proph(interval_width=.95, daily_seasonality=True)
    
    # Fitting the model
    mod.fit(ts)
    
    # Making future Dataframes
    future = mod.make_future_dataframe(periods=pers, freq='D')
    
    # Forecasting
    forecast = mod.predict(future)
        
    # Plotting the forecast
    mod.plot(forecast, uncertainty=True)
    
    plt.xlabel("Dates")
    plt.ylabel("Price")
    plt.xlim(['2018-10', None])
    st.pyplot()
Exemplo n.º 2
0
def get_ROI_FBprophet(ts,
                      periods,
                      plot=False,
                      plot_components=False,
                      plot_title=None):
    '''
    Get forecasted ROI based on number of periods from end of ts.
    
    '''

    df = pd.DataFrame(ts)
    df.reset_index(inplace=True)
    df.columns = ['ds', 'y']

    model = proph(interval_width=0.95)
    model.fit(df)

    future_dates = model.make_future_dataframe(periods=periods, freq='MS')
    forecast = model.predict(future_dates)

    pred_end_val = forecast[-1:]['yhat'].values[0]
    start_val = df[-1:]['y'].values[0]
    roi = (pred_end_val - start_val) / start_val

    if plot:
        model.plot(forecast, uncertainty=True)
        plt.title(plot_title)
        plt.show()

    if plot_components:
        model.plot_components(forecast)
        plt.title(plot_title)
        plt.show()

    return roi
Exemplo n.º 3
0
def forecast(date=None, showPlot = False, histPeriodDays=30, periodsAhead=100):

    date = date.strftime('%Y-%m-%d %H:%M:%S')
    start = time.time()

    # Get data from binance
    ts = getBinanceData.getData('BTCUSDT', interval=getBinanceData.Client.KLINE_INTERVAL_4HOUR, minutes= histPeriodDays * 24 * 60)
    # print(ts.tail())

    # Resetting the index back so Dates are no longer indexed
    ts.reset_index(inplace=True)

    # Renaming the columns for use in FB prophet
    ts.rename(columns={'DateTime': 'ds', 'close': 'y'}, inplace=True)

    # Fitting and training
    mod = proph(interval_width=0.95,daily_seasonality=True,)

    #region:add daily
    # m = Prophet(weekly_seasonality=False)
    mod.fit(ts)
    #endregion

    # Setting up predictions to be made
    future = mod.make_future_dataframe(periods=periodsAhead, freq='4H')
    future.tail()

    # Making predictions
    forecast = mod.predict(future)

    forecast.to_csv('forecast.csv')

    end = time.time()

    print('Time taken: %.2f s' % (end - start))

    # Plotting the model
    if showPlot:
        mod.plot(forecast, uncertainty=True)
        plt.title('Facebook Prophet Forecast and Fitting')
        plt.show()

    selected = forecast.ds == date
    selected = forecast[selected]

    upper = selected.yhat_upper.values[0]
    lower = selected.yhat_lower.values[0]
    yhat = selected.yhat.values[0]

    return yhat, upper, lower
Exemplo n.º 4
0
    def ProphetETH(self):
        conn = self._getConnection()
        df = pd.read_sql('select * from eth1', conn)
        #df.to_csv("/home/student/Pied Piper/ethfinal101.csv")

        conn.close()

        lst = ['Open', 'High', 'Low', 'Close']

        #df.drop(df.index[0],inplace=True)
        df.insert(0, 'index', np.arange(1, 1607), True)

        df.columns = [
            'index', 'Date', 'Open', 'High', 'Low', 'Close', 'Volume'
        ]

        result_ETH = []

        for i in lst:
            df_ETH = pd.DataFrame(df)

            df_ETH.rename(columns={'Date': 'ds', i: 'y'}, inplace=True)

            mod_ETH = proph(interval_width=0.95)
            mod_ETH.fit(df_ETH)

            future_ETH = mod_ETH.make_future_dataframe(periods=360, freq='D')

            forecast_ETH = mod_ETH.predict(future_ETH)
            result_ETH.append(forecast_ETH)

            for jB in result_ETH:
                df_ETH.predict = pd.DataFrame(jB)
                df_ETH.predict.to_csv(str(i) + 'ETH' + '.csv')
            mod_ETH.plot(forecast_ETH,
                         uncertainty=True,
                         xlabel='Date',
                         ylabel=i).savefig('/home/student/Pied Piper/static/' +
                                           str(i) + 'ETH' + '.png')
            mod_ETH.plot_components(
                forecast_ETH,
                uncertainty=True).savefig('/home/student/Pied Piper/static/' +
                                          str(i) + 'ETHComponent' + '.png')
            plt.title('Facebook Prophet Forecast and Fitting' +
                      (str(i) + 'ETH'))
            plt.suptitle(str(i) + ' ' + 'ETH', fontsize=20)
def prophet_forecast(df, zipcodes_list):
    """ Function that when inputed a dataframe and a list of zipcodes, retrieves a dictionary containing each
    zipcode as a key and the forecasted values from the Prophet model associated with that zipcode as values.
    """
    forecasts = {}    
    for zipcode in zipcodes_list:
        returns = df.loc[(df['RegionName'] == zipcode)][['time', 'value']]
        returns = returns.rename(columns={'time': 'ds','value': 'y'})

        Model = proph(interval_width=0.95)
        Model.fit(returns)

        future_dates = Model.make_future_dataframe(periods=36, freq='MS')
        forecast = Model.predict(future_dates)

        forecasts[zipcode] = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]

    return forecasts