Forecast stocks with Python and FbProphet.

Forecast stocks with Python and FbProphet.

Forecasting stocks with Python is actually really easy to do with the fbProphet model developed by Facebook. The following code will download the daily stock data which is passed into prophet to get a 10 day forecast.

To run this stock forecasting tool you will want to install Python on your computer. Once that is done you’ll need to install the fbprophet Python module.

After setting up your environment you can save this Python code into a file called “forecast.py” and run it with the following command. Note: In order to forecast as stock other than MSFT you’ll need to pickup a free API key here.

python ./forecast.py MSFT

The Python Code For Forecasting Stocks

import requests
import csv
import pandas as pd
import sys
from fbprophet import Prophet
from fbprophet.plot import plot_plotly
import plotly.offline as py
import matplotlib.pyplot as plt


api_key = 'demo'

ticker = sys.argv[1]

#How many periods to forecast. In this example we are forecasting days.
future_periods = 10

ticker = sys.argv[1]   #can only be MSFT when using 'demo' api_key. Get a free key at https://www.alphavantage.co/ to get more symbols and features.


#A function for downloading daily stock data.
def download():
    data = []
    
    url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' + ticker + '&apikey=' + api_key + '&datatype=csv'
    
    rawdata = requests.get(url,timeout=15)
    
    stockdata = csv.reader(rawdata.text.splitlines(), delimiter=',')
    
    next(stockdata, None)
    
    for row in stockdata:
        #Make sure we only get recent data. 
        if "2019" in row[0] or "2018" in row[0]:
           
            item = [row[0],float(row[4])]
           
            data.append(item)
    
    return data[::-1]

rowdata = download()

#Define a dataframe for Prophet.

df = pd.DataFrame(index=range(0,len(rowdata)),columns=['ds', 'y'])

#Create data frames.

for i in range(0,len(rowdata)):
    timestamp = rowdata[i][0]
    df['ds'][i] = rowdata[i][0]
    df['y'][i] = rowdata[i][1]


ts = df["ds"]


m = Prophet()

m.fit(df)

future = m.make_future_dataframe(periods=future_periods)

forecast = m.predict(future)

fig2 = m.plot_components(forecast)

plt.show()

Leave a Reply