Coder Social home page Coder Social logo

plumti / out-of-sample-stock-price-prediction Goto Github PK

View Code? Open in Web Editor NEW
4.0 2.0 0.0 505 KB

This is a small example of using Facebook's open-source algorithm for generating time-series models, with a dataset from yahoo finance.

Jupyter Notebook 100.00%
mathplotlib pandas price-prediction price-prediction-model prophet-facebook python stock-price-prediction yfinance

out-of-sample-stock-price-prediction's Introduction

Out-of-Sample Stock Price Prediction

Alt Text

This is a short example of how to predict stock prices out of sample using machine learning, using Facebook Prophet.

Disclaimer: This tutorial is for educational purposes only and should not be interpreted as trading advice. The provided code, timestamps, and datasets are used for visualization and experimentation purposes and may not represent a realistic trading model.

By following the steps below, you'll be able to understand the code and get started with your price prediction project.

Installation

To begin, you'll need to install the Prophet library. You can find installation instructions for Prophet in the official documentation here.

Once you have Prophet installed (assuming you have an IDE), you're ready to get started!

Quick Start

Prophet provides a quick start guide that will help you familiarize yourself with its Python API. I recommend reading through the quick start guide and trying out the provided code examples. You can find the guide here.

Understanding the Code

Once you have done the quick start, have a look at the code and the sketch. In this example, Yahoo Finance is used as a dataset for price prediction. You can easily install the yfinance library, which provides a convenient way to access Yahoo Finance data, using pip:

#This is before you run the code
# Install yfinance for Yahoo Finance data
pip install yfinance 
# Install prophet to forecasting time series data
python -m pip install prophet
# For working with the datasets
pip install pandas
# Import matplotlib for plotting
import matplotlib.pyplot as plt
--------------------------------------------
#Code from py_example.py
import pandas as pd
from prophet import Prophet
import yfinance as yf
from datetime import datetime, timedelta
import matplotlib.pyplot as plt  # Import matplotlib for plotting

# Define the date and time for which you want to make predictions (current date and time)
now = datetime.now()

# Calculate the end time for predictions (100 minutes from now)
end_time = now + timedelta(minutes=100)

# Create a list of timestamps for the next 100 minutes at 1-minute intervals
timestamps = pd.date_range(start=now, end=end_time, freq='1T')

# Create a DataFrame with the timestamps
future = pd.DataFrame({'ds': timestamps})

# Download historical data for Bitcoin (adjust as needed)
data = yf.download('BTC-USD', period='1d', interval='1m')  # 1 day of 1-minute data for Bitcoin

# Prepare data for Prophet
data = data.reset_index()  # Reset the index to access the 'ds' and 'y' columns
data = data[['Datetime', 'Close']]  # Keep only 'Datetime' and 'Close' columns
data.rename(columns={'Datetime': 'ds', 'Close': 'y'}, inplace=True)  # Rename columns to 'ds' and 'y'
data['ds'] = data['ds'].dt.tz_localize(None)

# Create and fit the Prophet model
model = Prophet()
model.fit(data)

# Make predictions
forecast = model.predict(future)

# Visualize the forecast with custom settings
fig = model.plot(forecast, xlabel='Date', ylabel='Price', figsize=(12, 6))
plt.title('Bitcoin Price Forecast', fontsize=16)  # Update the title
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend(['Actual Price', 'Trend', 'Forecast', 'Uncertainty'], loc='upper left', fontsize=12)
plt.tight_layout()
plt.show()

# Access the forecasted values
forecasted_values = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]
print(forecasted_values)

Here is another more recent example with the same time cycle and frequency:

Click here

Here is another more recent example with different time cycles and frequency (records data for 5 days, every 2 minutes) :

Click here

Not accurate enough?

If you think these predictions aren't precise enough, try adjust the timestamp and dataset settings. Alternatively consider using another machine learning library - I recommend scikit-learn

Sources:

https://scikit-learn.org/stable/index.html https://facebook.github.io/prophet/ https://matplotlib.org/ https://algotrading101.com/learn/yfinance-guide/

out-of-sample-stock-price-prediction's People

Contributors

plumti avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.