BTCprediction / app.py
alihamzach's picture
Update app.py
740ca79 verified
import ccxt
import ccxt.async_support as ccxt
import pandas as pd
from datetime import datetime, timedelta
from prophet import Prophet
import matplotlib.pyplot as plt
import streamlit as st
# Initialize the exchange
binance = ccxt.bitget()
symbol = "BTC/USDT"
def fetch_btc_usdt_data(start_date, end_date):
since = int(datetime.strptime(start_date, '%Y-%m-%d').timestamp() * 1000)
end = int(datetime.strptime(end_date, '%Y-%m-%d').timestamp() * 1000)
timeframe = '1d' # Daily data
data = []
while since < end:
ohlcv = binance.fetch_ohlcv(symbol, timeframe, since, limit=1000)
if not ohlcv:
break
since = ohlcv[-1][0] + 1
data.extend(ohlcv)
# Convert data to DataFrame
columns = ['timestamps', 'open', 'high', 'low', 'close', 'volume']
df = pd.DataFrame(data, columns=columns)
df['timestamps'] = pd.to_datetime(df['timestamps'], unit='ms')
df.set_index('timestamps', inplace=True)
# Return the DataFrame
return df
def train_and_forecast(df):
# Prepare the data for Prophet
df_prophet = df[['close']].reset_index()
df_prophet.rename(columns={'timestamps': 'ds', 'close': 'y'}, inplace=True)
# Train the Prophet model
model = Prophet(daily_seasonality=True)
model.fit(df_prophet)
# Make a future dataframe for predictions (e.g., next 30 days)
future = model.make_future_dataframe(periods=30, freq='D')
# Get the forecast
forecast = model.predict(future)
return forecast, model
def plot_forecast(forecast, model):
# Plot the forecast
fig, ax = plt.subplots(figsize=(10, 6))
model.plot(forecast, ax=ax)
# Plot the components
fig2, ax2 = plt.subplots(figsize=(10, 6))
model.plot_components(forecast)
return fig, fig2
# Streamlit UI
st.title("BTC/USDT Price Forecasting")
st.markdown("""
This app uses Facebook's Prophet model to forecast the future prices of BTC/USDT based on historical data from Bitget.
You can select the start and end dates to get a prediction for the next 30 days.
""")
# Date input
start_date = st.date_input('Start Date', datetime.today() - timedelta(days=365))
end_date = st.date_input('End Date', datetime.today())
if start_date and end_date:
# Fetch the data
df = fetch_btc_usdt_data(start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))
# Train and forecast
forecast, model = train_and_forecast(df)
# Plot the forecast and components
st.subheader("Forecast Plot")
fig1, fig2 = plot_forecast(forecast, model)
st.pyplot(fig1) # Forecast plot
st.pyplot(fig2) # Components plot