mystycrym/Algorithmic_trading_bot
2
1# Import libraries2import streamlit as st3import yfinance as yf4from statsmodels.tsa.arima.model import ARIMA5import pandas as pd6import matplotlib.pyplot as plt7 8# Title and description9st.title("Algorithmic Trading Bot with ARIMA")10st.write(11 "This app simulates an algorithmic trading bot using the ARIMA model for price prediction. "12 "The bot predicts future stock prices and simulates trades based on the predicted trends."13)14 15# Sidebar for user inputs16st.sidebar.title("Settings")17ticker = st.sidebar.text_input("Stock Ticker (e.g., AAPL, TSLA, ^GSPC):", value="^GSPC")18start_date = st.sidebar.date_input("Start Date", value=pd.to_datetime("2015-01-01"))19end_date = st.sidebar.date_input("End Date", value=pd.to_datetime("2023-12-31"))20n_days = st.sidebar.slider("Prediction Horizon (days)", min_value=1, max_value=30, value=7)21initial_balance = st.sidebar.number_input("Initial Balance (USD):", value=10000.0)22arima_order = st.sidebar.text_input("ARIMA Order (p, d, q):", value="5,1,0")23 24# Parse ARIMA order25try:26 p, d, q = map(int, arima_order.split(","))27except ValueError:28 st.error("Invalid ARIMA order. Please enter in the format 'p,d,q'.")29 30# Fetch historical data31st.write("### Historical Data")32try:33 data = yf.download(ticker, start=start_date, end=end_date)34 data = data["Close"]35 st.line_chart(data)36except Exception as e:37 st.error(f"Error fetching data: {e}")38 39# Trading Bot Simulation40if st.button("Run Trading Bot"):41 st.write("### Trading Bot Simulation")42 43 if len(data) < 30:44 st.error("Not enough data to train the model. Please select a longer date range.")45 else:46 try:47 # Train ARIMA model48 model = ARIMA(data, order=(p, d, q))49 fitted_model = model.fit()50 51 # Predict future prices52 future_index = pd.date_range(start=data.index[-1], periods=n_days + 1, freq="B")[1:]53 forecast = fitted_model.forecast(steps=n_days)54 st.write("### Debug: Forecasted Prices")55 st.write(pd.DataFrame({"Date": future_index, "Predicted Price": forecast}))56 57 # Simulate trading58 balance = initial_balance59 position = 0 # Number of shares held60 trades = []61 62 for i in range(1, len(forecast)):63 if forecast[i] > forecast[i - 1]: # Buy signal64 if position == 0:65 position = balance / forecast[i]66 balance = 067 trades.append((future_index[i], "BUY", forecast[i]))68 elif forecast[i] < forecast[i - 1]: # Sell signal69 if position > 0:70 balance = position * forecast[i]71 position = 072 trades.append((future_index[i], "SELL", forecast[i]))73 74 # Final balance75 final_balance = balance + (position * forecast[-1] if position > 0 else 0)76 profit = final_balance - initial_balance77 78 # Show results79 st.write(f"### Final Balance: ${final_balance:,.2f}")80 st.write(f"### Total Profit: ${profit:,.2f}")81 trades_df = pd.DataFrame(trades, columns=["Date", "Action", "Price"])82 st.write("### Trade History")83 st.write(trades_df)84 85 # Plot results86 plt.figure(figsize=(10, 6))87 plt.plot(data, label="Historical Data (USD/share)")88 plt.plot(future_index, forecast, label="Predicted Data (USD/share)", linestyle="--")89 for trade in trades:90 plt.scatter(trade[0], trade[2], label=trade[1], color="green" if trade[1] == "BUY" else "red")91 plt.legend()92 plt.title("Algorithmic Trading Bot Simulation")93 plt.xlabel("Date")94 plt.ylabel("Price (USD/share)")95 st.pyplot(plt)96 97 except Exception as e:98 st.error(f"Error in trading bot simulation: {e}")99 