Forecast stock prices with Python and FbProphet.

ByJames Burnett

Forecasting is a sub-discipline of prediction that uses data based on time to produce an output. Using Python and the FBProphet python module we can train a module using time series data (data that is associated with a date and time) to forecast what would happen to the data over the course of similar time periods.

For example, if you want to Forecast a stock price you could get all the important past dates related to that stock to build your model. You could input specific dates of interest like corporate earnings, dividend payout dates and holidays and FbProphet could then correlate price changes on or around those dates. Based on what happened around those dates in the past could then be used to forecast data in the future based on the date.

The model in theory could forecast the price of a stock on our around corporate earning reports or even during the Christmas holidays.

The code below will download stock data and generate a forecast by using only the dates of the stock price. No holidays or special dates have been inputted so the model will only forecast based on what the price did on a previous day of a previous month and/or year.

The Code

You will need to install Pandas (pip install pandas), the Alpaca trading api module (pip install alpaca_trade_api) and Fbprophet (pip install fbprophet) to run the code. I highly recommend that you run this code in a Linux environment (Debian if you’re cool) as several custom libraries will need to be installed.

import alpaca_trade_api as tradeapi
import pandas as pd
from fbprophet import Prophet
from fbprophet.plot import plot_plotly
import plotly.offline as py
import matplotlib.pyplot as plt
import mykeys
import sys

KEY = ""

api = tradeapi.REST(KEY, SECRET_KEY, base_url='', api_version='v2') 

account = api.get_account()


def main():
    ticker = sys.argv[1]

    now ='US/Eastern')

    barset = api.get_barset( [ticker], '15Min',  limit = 1000)

    timestamp = []

    close = []

    volume = []

    future_periods = 6

    for bar in barset[ticker]:
        td = pd.Timestamp(bar.t)

        ts = td.strftime("%Y-%m-%d %H:%M:%S")




        print(ticker, ts,bar.c)
    df = pd.DataFrame( { "ds" : timestamp,  "y": close, "volume": volume})

    m = Prophet()
    future = m.make_future_dataframe(periods=future_periods)

    forecast = m.predict(future)
    fig = m.plot(forecast)
    fig = m.plot_components(forecast)

if __name__ == '__main__':
%d bloggers like this: