Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import yfinance as yf
|
| 3 |
+
from statsmodels.tsa.arima.model import ARIMA
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
|
| 7 |
+
# Title and description
|
| 8 |
+
st.title("Algorithmic Trading Bot with ARIMA")
|
| 9 |
+
st.write("This app simulates an algorithmic trading bot using the ARIMA model for price prediction.")
|
| 10 |
+
|
| 11 |
+
# Sidebar for user inputs
|
| 12 |
+
st.sidebar.title("Settings")
|
| 13 |
+
ticker = st.sidebar.text_input("Stock Ticker (e.g., AAPL, TSLA, ^GSPC):", value="^GSPC")
|
| 14 |
+
start_date = st.sidebar.date_input("Start Date", value=pd.to_datetime("2015-01-01"))
|
| 15 |
+
end_date = st.sidebar.date_input("End Date", value=pd.to_datetime("2023-12-31"))
|
| 16 |
+
n_days = st.sidebar.slider("Prediction Horizon (days)", min_value=1, max_value=30, value=7)
|
| 17 |
+
initial_balance = st.sidebar.number_input("Initial Balance (USD):", value=10000.0)
|
| 18 |
+
arima_order = st.sidebar.text_input("ARIMA Order (p, d, q):", value="5,1,0")
|
| 19 |
+
|
| 20 |
+
# Parse ARIMA order
|
| 21 |
+
try:
|
| 22 |
+
p, d, q = map(int, arima_order.split(","))
|
| 23 |
+
except ValueError:
|
| 24 |
+
st.error("Invalid ARIMA order. Please enter in the format 'p,d,q'.")
|
| 25 |
+
|
| 26 |
+
# Fetch historical data
|
| 27 |
+
st.write("### Historical Data")
|
| 28 |
+
try:
|
| 29 |
+
data = yf.download(ticker, start=start_date, end=end_date)
|
| 30 |
+
data = data["Close"]
|
| 31 |
+
st.line_chart(data)
|
| 32 |
+
except Exception as e:
|
| 33 |
+
st.error(f"Error fetching data: {e}")
|
| 34 |
+
|
| 35 |
+
# Trading Bot Simulation
|
| 36 |
+
if st.button("Run Trading Bot"):
|
| 37 |
+
st.write("### Trading Bot Simulation")
|
| 38 |
+
|
| 39 |
+
if len(data) < 30:
|
| 40 |
+
st.error("Not enough data to train the model. Please select a longer date range.")
|
| 41 |
+
else:
|
| 42 |
+
try:
|
| 43 |
+
# Train ARIMA model
|
| 44 |
+
model = ARIMA(data, order=(p, d, q))
|
| 45 |
+
fitted_model = model.fit()
|
| 46 |
+
|
| 47 |
+
# Predict future prices
|
| 48 |
+
future_index = pd.date_range(start=data.index[-1], periods=n_days + 1, freq="B")[1:]
|
| 49 |
+
forecast = fitted_model.forecast(steps=n_days)
|
| 50 |
+
forecast_df = pd.DataFrame({"Date": future_index, "Predicted Price": forecast}).set_index("Date")
|
| 51 |
+
|
| 52 |
+
# Simulate trading
|
| 53 |
+
balance = initial_balance
|
| 54 |
+
position = 0 # Number of shares held
|
| 55 |
+
trades = []
|
| 56 |
+
|
| 57 |
+
for i in range(1, len(forecast)):
|
| 58 |
+
if forecast[i] > forecast[i - 1]: # Buy signal
|
| 59 |
+
if position == 0:
|
| 60 |
+
position = balance / forecast[i]
|
| 61 |
+
balance = 0
|
| 62 |
+
trades.append((future_index[i], "BUY", forecast[i]))
|
| 63 |
+
elif forecast[i] < forecast[i - 1]: # Sell signal
|
| 64 |
+
if position > 0:
|
| 65 |
+
balance = position * forecast[i]
|
| 66 |
+
position = 0
|
| 67 |
+
trades.append((future_index[i], "SELL", forecast[i]))
|
| 68 |
+
|
| 69 |
+
# Final balance
|
| 70 |
+
final_balance = balance + (position * forecast[-1] if position > 0 else 0)
|
| 71 |
+
profit = final_balance - initial_balance
|
| 72 |
+
|
| 73 |
+
# Show results
|
| 74 |
+
st.write(f"### Final Balance: ${final_balance:,.2f}")
|
| 75 |
+
st.write(f"### Total Profit: ${profit:,.2f}")
|
| 76 |
+
trades_df = pd.DataFrame(trades, columns=["Date", "Action", "Price"])
|
| 77 |
+
st.write("### Trade History")
|
| 78 |
+
st.write(trades_df)
|
| 79 |
+
|
| 80 |
+
# Plot results
|
| 81 |
+
plt.figure(figsize=(10, 6))
|
| 82 |
+
plt.plot(data, label="Historical Data (USD/share)")
|
| 83 |
+
plt.plot(forecast_df, label="Predicted Data (USD/share)", linestyle="--")
|
| 84 |
+
for trade in trades:
|
| 85 |
+
plt.scatter(trade[0], trade[2], label=trade[1], color="green" if trade[1] == "BUY" else "red")
|
| 86 |
+
plt.legend()
|
| 87 |
+
plt.title("Algorithmic Trading Bot Simulation")
|
| 88 |
+
plt.xlabel("Date")
|
| 89 |
+
plt.ylabel("Price (USD/share)")
|
| 90 |
+
st.pyplot(plt)
|
| 91 |
+
|
| 92 |
+
except Exception as e:
|
| 93 |
+
st.error(f"Error in trading bot simulation: {e}")
|