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 = ""
    
SECRET_KEY = ""

api = tradeapi.REST(KEY, SECRET_KEY, base_url='https://paper-api.alpaca.markets', api_version='v2') 

account = api.get_account()

api.list_positions()



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

    now = pd.Timestamp.now(tz='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")

        timestamp.append(ts)

        volume.append(bar.v)

        close.append(bar.c)

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

    m = Prophet()

    m.fit(df)
    
    future = m.make_future_dataframe(periods=future_periods)

    forecast = m.predict(future)
    
    fig = m.plot(forecast)
    
    fig = m.plot_components(forecast)
    
    plt.show()
    
    pass

if __name__ == '__main__':
    main()
%d bloggers like this: