示例#1
0
    def predict_and_plot(self):
        print("PREDICTING")
        self.df_new.head()

        # this model will apply repeatedly until the positiveness value reaches to 100.
        # this while loop will do that and calculate the number of iteration required
        # then it will decide the number of days(decide according to the iteration count) needed to job fit
        while (self.value <= 100):
            self.days = self.days + 7
            self.future = self.m.make_future_dataframe(periods=self.days)
            self.future.tail()
            forecast = self.m.predict(self.future)
            forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
            f_cast = forecast['yhat'].tail(1)
            f_cast = f_cast.tolist()
            self.value = f_cast[0]
            print("Days: {}--- Positive value:{}".format(
                self.days, self.value))

        self.m.plot(forecast)  #plotting the data
        self.m.plot_components(forecast)  #plotting the data
        py.init_notebook_mode()  # initialize the notebook mode
        fig = plot_plotly(self.m, forecast)  # This returns a plotly Figure
        py.iplot(fig)
        print("Number of days to fit the job: {} Days".format(self.days))
        self.remove_temp_files()
示例#2
0
 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
示例#3
0
def do_prophet():
    n_days = 7
    # Predict forecast with Prophet.
    df_train = df[['Date','Close']]
    df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})
    m = Prophet()
    m.fit(df_train)
    future = m.make_future_dataframe(periods=n_days)
    forecast = m.predict(future)
    # Show and plot forecast
    st.subheader('Forecast data')
    st.write(forecast.tail())
        
    st.subheader(f'시세 예측 그래프: {n_days} 일')
    test = m.plot(forecast)
    # st.write(test)
    fig1 = plot_plotly(m, forecast)
    # st.write('그렸어야해..')
    # st.plotly_chart(forecast)
    st.plotly_chart(fig1)

    # st.write("Forecast components")
    # fig2 = m.plot_components(forecast)
    # st.write(fig2)
    st.success("시세 예측 완료!")
    st.balloons()
示例#4
0
    def plot_forecast(
        self,
        title="Forecast",
        template="plotly_white",
        yaxis_title="Number of individuals",
        output_image=False,
        width=800,
        height=600,
        scale=2,
        output_figure=False,
    ):

        fig = plot_plotly(self.m, self.forecast)
        fig.update_layout(
            title=title,
            yaxis_title=yaxis_title,
            template=template,
            title_x=0.5,
        )

        if output_image:
            return Image(
                fig.to_image(format="png",
                             width=width,
                             height=height,
                             scale=scale))

        if output_figure:
            return fig

        return fig.show()
示例#5
0
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 indiadeaths():
    df = pd.read_csv("Indiajuly21.csv", parse_dates=['Date'], dayfirst=True)
    df = df[['Date', 'State/UnionTerritory', 'Cured', 'Deaths', 'Confirmed']]
    df.columns = ['date', 'state', 'cured', 'deaths', 'confirmed']
    today = df[df.date == '2020-07-24']
    df2 = df.groupby(['date'])['confirmed', 'deaths',
                               'cured', ].sum().reset_index()
    #making columns for daily new cases
    df2['new_confirmed'] = df2.confirmed.diff()
    df2['new_deaths'] = df2.deaths.diff()
    df2['new_cured'] = df2.cured.diff()
    #taking dates from 15th March
    df2 = df2.iloc[64:]
    #Statewise new confirmed
    df['new_confirmed'] = df.groupby(['state'])['confirmed'].diff()
    df['new_deaths'] = df.groupby(['state'])['deaths'].diff()
    df['new_cured'] = df.groupby(['state'])['cured'].diff()
    df3 = df2[['date', 'deaths']]
    #Renaming column names according to fb prophet
    df3.columns = ['ds', 'y']
    m = Prophet()
    m.fit(df3)
    future = m.make_future_dataframe(periods=10)
    forecast = m.predict(future)
    fig = plot_plotly(m, forecast)  # This returns a plotly Figure
    fig.update_layout(
        title_text='<b>Covid-19 Total deaths cases Forecast<b>',
        title_x=0.5,
        paper_bgcolor='LightCoral',
        plot_bgcolor="LightCoral",
    )
    fig.show()
    return render_template("indiastatistics.html")
示例#7
0
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 show_graph(self, model, forecast):
        '''
        model = Prophet object
        forecast = Dataframe. Result of the model.predict(future)

        '''
        fig = plot_plotly(model, forecast)
        py.iplot(fig)
def plotter_prophet(model, frcst):
    fig = plot_plotly(model,
                      frcst,
                      figsize=(900, 600),
                      xlabel='Time period',
                      ylabel='Price')
    fig.update_layout(hovermode='x')
    fig.show()
示例#10
0
 def prediction(self, period):
     self.model.fit(self.prophet_df)
     future = self.model.make_future_dataframe(periods=period)
     # Eliminate weekend from future dataframe
     future['day'] = future['ds'].dt.weekday
     future = future[future['day'] <= 4]
     forecast = self.model.predict(future)
     fig = plot_plotly(self.model, forecast)
     fig2 = self.model.plot_components(forecast)
     fig3 = self.model.plot(forecast)
     a = add_changepoints_to_plot(fig3.gca(), self.model, forecast)
     return (fig, fig2, fig3)
示例#11
0
def prophet_prediction(row, zip_code, retirement_date='2029'):
    # if os.path.exists('pickles/{}_forecast.pkl'.format(zip_code)):
    # with open("pickles/{}_model.pkl".format(zip_code), 'rb') as f:
    #     unpickler = pickle.Unpickler(f)
    #     m = unpickler.load()
    m = Prophet(seasonality_mode='multiplicative')
    row = row[(row['ds'] > '2009')]
    m.fit(row)
    forecast = pd.read_pickle('pickles/{}_forecast.pkl'.format(zip_code))
    print(forecast.dtypes)
    forecast = forecast[(forecast['ds'] > '2009')
                        & (forecast['ds'] < str(retirement_date))]
    return plot_plotly(m, forecast)
示例#12
0
def model_from_coin(coin, base, growth, changepoints, changepoint_range,
                    seasonality_mode, seasonality_prior_scale,
                    holidays_prior_scale, changepoint_prior_scale,
                    interval_width):

    df = pd.DataFrame()
    df["ds"] = base["DATE_INFO"]
    df["y"] = base["CLOSE"]

    if growth == 'logistic':
        df["cap"] = float(max(base["CLOSE"]))

    m = Prophet(growth=growth,
                changepoints=changepoints,
                changepoint_range=changepoint_range,
                yearly_seasonality=False,
                weekly_seasonality=False,
                daily_seasonality=False,
                seasonality_mode=seasonality_mode,
                seasonality_prior_scale=seasonality_prior_scale,
                holidays_prior_scale=holidays_prior_scale,
                changepoint_prior_scale=changepoint_prior_scale,
                interval_width=interval_width).add_country_holidays(
                    country_name='US').add_seasonality(
                        name='bimonthly', period=365.25 / 6,
                        fourier_order=5).add_seasonality(name='yearly',
                                                         period=365.25,
                                                         fourier_order=3)

    m.fit(df)

    future = m.make_future_dataframe(periods=int(365 / 2))

    if growth == 'logistic':
        future["cap"] = float(max(base["CLOSE"]))

    forecast = m.predict(future)
    logging.info("Going to detect_anomalies")
    forecasted = detect_anomalies(forecast, df)
    logging.info("Saving graph for {}".format(coin))
    fig = plot_plotly(m, forecast)  # This returns a plotly Figure
    #plio.write_html(fig, '/appdata/graph_{}.html'.format(coin), include_plotlyjs=True)
    plot_anomalies(forecasted).save('/appdata/graph_{}.html'.format(coin))
    logging.info("Graph for {} saved".format(coin))
    now = datetime.datetime.now()

    resultdf = forecast[forecast['ds'] == pd.Timestamp(
        now.year, now.month, now.day)][[
            'ds', 'yhat', 'yhat_lower', 'yhat_upper'
        ]]
    return resultdf
示例#13
0
def predict(df, days):

    prophet = Prophet()
    prophet.fit(df)

    future = prophet.make_future_dataframe(periods=days)
    forecast = prophet.predict(future)
    df_forecast = forecast[["ds", "yhat", "yhat_lower",
                            "yhat_upper"]].set_index("ds")
    df_forecast = df_forecast.round(0)
    # fig_forecast = prophet.plot(forecast)
    fig_forecast = plot_plotly(prophet, forecast)

    return df_forecast
示例#14
0
文件: main.py 项目: donovanx/covid-lu
    def main_gui(self):
        st.image('cl.jpg')
        st.title('COVID-19 LUXEMBOURG')
        st.subheader('Last 5 days')
        st.table(self.data.tail())
        self.plot_data('Cases', 'Total Cases')
        self.plot_data('Deaths', 'Total Deaths')
        self.plot_data('Recovered', 'Total Recoveries')


        st.subheader('Future Cases (Predictions)')
        fig = plot_plotly(self.model, self.prediction)
        fig.update_layout(width = 700, height = 500)
        st.plotly_chart(fig)
        st.text('Source: https://github.com/CSSEGISandData/COVID-19')
示例#15
0
 def predict():
     temp = p_df.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(
         title='{} CBD Oil Intrest Prediction'.format(country),
         xaxis={'title': 'Date'},
         yaxis={'title': 'Intrest Prediction'})
     return fig, forecast, periods
def fit_predict_prophet(df1, city):
    """Subset for city column and rename Passengers columns"""
    df1 = df1[df1['city'] == city]
    df1 = df1.rename(columns={'PASSENGERS': 'y'})
    
    size = int(len(df1) * 0.7)
    train, test = df1[['ds','y']][0:size], df1[['ds','y']][size:len(df1)]
#     train_exog, test_exog = df1[0:size], df1[size:len(df1)]
    
    """Reset Index for both training and testing set"""
    train.reset_index(inplace=True)
    test.reset_index(inplace=True)
    
    start=len(train)
    end=len(train)+len(test)-1
    
#     endog = train_exog['y']
#     exog = train_exog[['temperature_mean']]
    
    """Prophet Modeling and Fit"""
    Model = pr(daily_seasonality = False, yearly_seasonality = True, weekly_seasonality = False,
                seasonality_mode = 'multiplicative', 
                interval_width = 0.90,
                changepoint_range = 0.8)
    Model.fit(train)
    
    """Forecast and Plot Model"""
    forecast = Model.predict(pd.DataFrame(df1.reset_index()['ds'][start-1:end]))
    forecast.head()
    Model.plot(forecast, uncertainty=True)
    
    """Plot Fbprophet Using plotly"""
    from fbprophet.plot import plot_plotly
    import plotly.offline as py
    py.init_notebook_mode()
    
    """This returns a plotly Figure"""
    fig = plot_plotly(Model, forecast)  
    
    """Calculate Root Mean Squared"""
    rms = sqrt(mean_squared_error(test['y'], forecast.loc[:, 'yhat']))
    print(rms)

    return fig
示例#17
0
def create_forecasts(value):
    #dataframe for fbprophet prediction/visualization
    fb_df = df[df['Geographic_Area'] == 'Total'][['Date', value]]
    fb_df.columns = ['ds', 'y']

    #removing any non-numerical characters
    fb_df['y'] = fb_df['y'].apply(lambda x: int(re.sub('[^0-9]', '', str(x))))

    #removing weekends
    fb_df_weekdays = fb_df[fb_df['ds'].dt.dayofweek < 5]

    #fitting the fbprophet model
    prophet = Prophet()
    prophet.fit(fb_df_weekdays)

    #making dataframe of future dates, 30 days into future
    future = prophet.make_future_dataframe(periods=30)
    future_weekdays = future[future['ds'].dt.dayofweek < 5]

    #generating forecast for future dates
    forecast = prophet.predict(future_weekdays)

    #dictionary of title options based on radio items feature to be used in app callbacks for fb prophet section
    title_options = {
        'Daily Cases': 'New Cases Per Day',
        'Total\xa0 Confirmed Cases': 'Total Confirmed Cases',
        'Recovered by Region': 'Recovered Patients',
        'Still infectious by Region': 'Active Cases',
        'Number of Deaths': 'Number of Deaths'
    }
    #plotting forecast
    fig1 = plot_plotly(prophet, forecast)

    fig1.update_layout(paper_bgcolor=colors['background'],
                       plot_bgcolor=colors['background'],
                       font={'color': colors['text']},
                       xaxis={'title': 'Date'},
                       yaxis={'title': title_options[value]},
                       width=1000)

    fig1.update_traces(marker={'color': 'LightSkyBlue'})

    return fig1
def plot_fbprophet_forecasting(df, dates, days_in_future, feature):
    k = df[df['Country/Region'] == 'India'].loc[:, '1/22/20':]
    india_values = k.values.tolist()[0]
    data = pd.DataFrame(columns=['ds', 'y'])
    data['ds'] = dates
    data['y'] = india_values
    pd.set_option('float_format', '{:f}'.format)
    model_prophet = fbprophet.Prophet()
    model_prophet.fit(data)
    future = model_prophet.make_future_dataframe(periods=days_in_future)
    prop_forecast = model_prophet.predict(future)
    forecast = prop_forecast[['ds', 'yhat', 'yhat_lower',
                              'yhat_upper']].tail(days_in_future)
    print(forecast)

    fig = plot_plotly(model_prophet, prop_forecast)
    fig = model_prophet.plot(prop_forecast,
                             xlabel='Date',
                             ylabel='{}'.format(feature))
    fig.show()
示例#19
0
def make_forecast(selection):
    """Takes a name from the selection and makes a forecast plot."""

    if selection == CASES:

        cumulative_series_name = "cumulative_cases"
        title = "Daily Cases"
        x_label = "Cases"

    if selection == DEATHS:

        cumulative_series_name = "cumulative_deaths"
        title = "Daily Deaths"
        x_label = "Deaths"

    if selection == RECOVERIES:

        cumulative_series_name = "cumulative_recoveries"
        title = "Daily Recoveries"
        x_label = "Recoveries"

    prophet_df = (
        df[cumulative_series_name]
        .diff()
        .dropna()
        .to_frame()
        .reset_index()
        .rename(columns={"date": "ds", cumulative_series_name: "y"})
    )

    model = Prophet()
    model.fit(prophet_df)
    future = model.make_future_dataframe(periods=90)
    forecast = model.predict(future)

    fig = plot_plotly(model, forecast)
    fig.update_layout(
        title=title, yaxis_title=x_label, xaxis_title="Date",
    )

    return fig
示例#20
0
def make_forecast(selection):
    """Takes a name from the selection and makes a forecast plot."""

    if selection == PRODUCT_A:

        cumulative_series_name = "cumulative_cases"
        title = "Forecast Product A"
        x_label = "Prices"

    if selection == PRODUCT_B:

        cumulative_series_name = "cumulative_deaths"
        title = "Forecast Product B"
        x_label = "Prices"

    if selection == PRODUCT_C:

        cumulative_series_name = "cumulative_recoveries"
        title = "Forecast Product C"
        x_label = "Prices"

    prophet_df = (df[cumulative_series_name].diff().dropna().to_frame().
                  reset_index().rename(columns={
                      "date": "ds",
                      cumulative_series_name: "y"
                  }))

    model = Prophet()
    model.fit(prophet_df)
    future = model.make_future_dataframe(periods=90)
    forecast = model.predict(future)

    fig = plot_plotly(model, forecast)
    fig.update_layout(
        title=title,
        yaxis_title=x_label,
        xaxis_title="Date",
    )

    return fig
def predict_n_days(required_data, start_date, end_date, company_symbol):
    number_of_days = input(
        'How many days in the future you want to predict? : ')
    required_data[['ds', 'y']] = required_data[['Date', 'Close']]
    df = required_data[['ds', 'y']]
    m = Prophet(weekly_seasonality=False,
                yearly_seasonality=True,
                daily_seasonality=True,
                n_changepoints=15)
    m.fit(df)
    future = m.make_future_dataframe(periods=int(number_of_days))
    forecast = m.predict(future)
    fig = plot_plotly(
        m,
        forecast,
        xlabel=
        f'Trained model from {start_date} to {end_date} and predicted {number_of_days} days in the future',
        ylabel=f'Closing price of {company_symbol} ',
        figsize=(1800, 800))
    fig.update_layout(showlegend=True)
    plot(fig,
         filename=f'{company_symbol}_predict_{number_of_days}_days_graph.html')
def karcured():
    df = pd.read_csv("onlykarnatakajune3.csv",
                     parse_dates=['Date'],
                     dayfirst=True)
    df = df[['Date', 'State/UnionTerritory', 'Cured', 'Deaths', 'Confirmed']]
    df.columns = ['date', 'state', 'cured', 'deaths', 'confirmed']
    #df.isna().sum()
    today = df[df.date == '2020-07-24']
    df2 = df.groupby(['date'])['confirmed', 'deaths',
                               'cured', ].sum().reset_index()
    #making columns for daily new cases
    df2['new_confirmed'] = df2.confirmed.diff()
    df2['new_deaths'] = df2.deaths.diff()
    df2['new_cured'] = df2.cured.diff()
    #taking dates from 15th March
    df2 = df2.iloc[122:]
    #Statewise new confirmed
    df['new_confirmed'] = df.groupby(['state'])['confirmed'].diff()
    df['new_deaths'] = df.groupby(['state'])['deaths'].diff()
    df['new_cured'] = df.groupby(['state'])['cured'].diff()
    df3 = df2[['date', 'cured']]

    #Renaming column names according to fb prophet
    df3.columns = ['ds', 'y']
    m = Prophet()
    m.fit(df3)
    future = m.make_future_dataframe(periods=10)
    forecast = m.predict(future)
    #forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(31)
    fig = plot_plotly(m, forecast)  # This returns a plotly Figure
    fig.update_layout(
        title_text='<b>Covid-19 Total Recovery cases Forecast in karnataka<b>',
        title_x=0.5,
        paper_bgcolor='LightGreen',
        plot_bgcolor="LightGreen",
    )
    fig.show()
    return render_template("karnataka.html")
示例#23
0
def iterate():

    folder_path = "../convert_data/idle_res_us_timestamp"
    for filename in os.listdir(folder_path):
        if filename.endswith(".csv"):

            df = pd.read_csv(folder_path + "/" + filename,
                             names=[
                                 "ds", "bandwidth_up", "bandwidth_down",
                                 "connections", "ports", "ips"
                             ])

            df['ds'] = df['ds'].apply(
                lambda x: time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(x)))

            df.head()

            m = Prophet(changepoint_prior_scale=0.01, interval_width=0.95)

            for col in df.columns:
                if col != "ds":
                    subdf = df[['ds', col]].dropna()
                    subdf = subdf.rename(columns={'ds': 'ds', col: 'y'})
                    m.fit(subdf)
                    break

            future = m.make_future_dataframe(periods=1)
            future.tail()

            forecast = m.predict(future)
            forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()

            m.plot_components(forecast).savefig(
                filename.split('.')[0] + '.png')  #
            fig = plot_plotly(m, forecast)  # This returns a plotly Figure
            file_name_html = filename.split('.')[0] + ".html"
            py.plot(fig, filename=file_name_html)
示例#24
0
    dataset[dataset.Country == 'China'].groupby(
        'Date')['Confirmed'].sum().reset_index()).rename(columns={
            'Date': 'ds',
            'Confirmed': 'y'
        })
confirmed_training_dataset.head()

prophet = Prophet(yearly_seasonality=False,
                  weekly_seasonality=False,
                  daily_seasonality=True,
                  seasonality_mode='additive')
prophet.fit(confirmed_training_dataset)
future = prophet.make_future_dataframe(periods=7)
confirmed_forecast = prophet.predict(future)

fig = plot_plotly(prophet, confirmed_forecast)
annotations = []
annotations.append(
    dict(xref='paper',
         yref='paper',
         x=0.0,
         y=1.05,
         xanchor='left',
         yanchor='bottom',
         text='确诊人数预测',
         font=dict(family='Arial', size=30, color='rgb(37,37,37)'),
         showarrow=False))
fig.update_layout(annotations=annotations)

prophet = Prophet(yearly_seasonality=False,
                  weekly_seasonality=False,
示例#25
0
df3 = df2[['date', 'confirmed']]
#Renaming column names according to fb prophet
df3.columns = ['ds', 'y']

#model
m = Prophet()

#fitting the model
m.fit(df3)
#forecast
future = m.make_future_dataframe(periods=20)

forecast = m.predict(future)

from fbprophet.plot import plot_plotly
fig4 = plot_plotly(m, forecast)  # This returns a plotly Figure
fig4.update_layout(
    autosize=False,
    width=750,
    height=800,
    title_text='<b>Covid-19 Total cases Forecast<b>',
    title_x=0.5,
    paper_bgcolor='snow',
    plot_bgcolor="snow",
)

maha = df[df.state == 'Maharashtra']
maha = maha[['date', 'confirmed']]
maha.columns = ['ds', 'y']
p = Prophet()
p.fit(maha)
            <div style="font-family: 'Suez One';font-size:70px; background-color:white; color:black"><center>Covid-19 Global Predictor</center></div>
            ''',unsafe_allow_html=True
        )
st.header(" ")
st.header("Region-wise predictions")
option1 = st.selectbox("Country",countries)
option2 = st.number_input("Forecast period in days",min_value=1,max_value=30)
option3 = st.selectbox("Select the forecasted variable",list(type_of_analysis.keys()))
if( len(option1) != 0):
    m=Prophet(seasonality_mode='additive',yearly_seasonality=True,weekly_seasonality=True,daily_seasonality=True)
    #,growth='logistic'
    data=df[df['location']==option1][['date',type_of_analysis[option3]]].rename(columns={"date":"ds",type_of_analysis[option3]:"y"})
    #data['floor']=0
    #data['cap']=data['y'].max()+data['y'].mean()
    m.fit(data)
    future=m.make_future_dataframe(periods=option2)
    #future['floor']=0
    #future['cap']=data['y'].max()+data['y'].mean()
    forecast = m.predict(future)
    fig=plot_plotly(m, forecast)
    fig.update_layout(
    title="Forecasting",
    xaxis_title="Date",
    yaxis_title=option3)
    st.plotly_chart(fig,config = {'displayModeBar': False})
    cross_validation_results = cross_validation(m,initial='100 days',horizon="50 days")
    #horizon='5 days'
    #, initial='210 days', period='15 days',
    performance_metrics_results = performance_metrics(cross_validation_results)
    st.write(performance_metrics_results)
    
示例#27
0
year = [1977, 1989, 1996, 1997, 2006, 2011, 2018]
speed = [62136, 173736, 27000, 122000, 58536, 209000, 343180]
plt.plot(year, speed, color='red')
plt.xlabel('Year Launched')
plt.ylabel('Fastest Speed Recorded (km/h)')
plt.title('Fastest Spacecrafts Launched in the Last 50 Years')

#create a dataframe for manipulation
data = [['1977-09-05', 62136], ['1989-10-18', 173736], ['2011-08-05', 209000], ['2018-08-12', 343180]]
df = pd.DataFrame(data, columns = ['ds', 'y']) 

#use fbprophet to predict groth
m = Prophet()
m.fit(df)
future = m.make_future_dataframe(periods=365*243)
future.tail(n=10)

forecast = m.predict(future)
forecast.tail(n=3)

py.init_notebook_mode()
fig = plot_plotly(m, forecast)  # This returns a plotly Figure
py.iplot(fig)

m.plot_components(forecast)

y = travelTime(50034460)
timeConver(y)


示例#28
0
data2 = (data2['Price'].dropna().to_frame().reset_index().rename(columns={
    "index": "ds",
    'Price': "y"
}))

windows = st.sidebar.slider('prediction window',
                            min_value=80,
                            max_value=250,
                            value=90,
                            step=1)

model = Prophet()
model.fit(data2)
future = model.make_future_dataframe(periods=windows)
forecast = model.predict(future)

fig = plot_plotly(model, forecast)
fig.update_layout(
    title='title',
    yaxis_title=asset,
    xaxis_title="Date",
)

st.write("# Forecast Prices")
st.plotly_chart(fig)

##########################################
model.plot_components(forecast)
#plt.title("Global Products")
plt.legend()
st.pyplot()
    m.fit(df_train)
    future = m.make_future_dataframe(periods=periode)
    forecast = m.predict(future)
    return forecast


#Visualisasi Ramalan

#selectbox untuk tampilkan plot
st.subheader("Tampilkan Visualisasi Awal")
check_1 = st.checkbox('tampilkan canddle stick')
check_2 = st.checkbox('tampilkan grafik garis')

if check_1:
    plot_data_awal_canddlestick(df)
if check_2:
    plot_data_awal_linechart(df)

st.subheader("Ramalan")
check_3 = st.checkbox('Lakukan Training')

if check_3:
    hasil_training = forecast_stock(df)
    st.write(hasil_training.tail())

st.subheader("Tampilkan Visualisasi Ramalan")
check_4 = st.checkbox("Visualisasi 1")

if check_4:
    st.plotly_chart(plot_plotly(m, hasil_training))
示例#30
0
df_treino = df_valores[['Date', 'Close']]

#renomear colunas
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)