build a python backtesting engine for finance
To upload files, please first save the app
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class StrategyData(Base):
__tablename__ = 'strategy_data'
id = Column(Integer, primary_key=True)
stock = Column(String)
date = Column(Date)
price = Column(Float)
signal = Column(Integer)
engine = create_engine('sqlite:///backtest.sqlite')
Base.metadata.create_all(bind=engine)
st.title('Finance Backtesting Engine')
# Upload stock data
uploaded_file = st.file_uploader('Upload your CSV file', type='csv')
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.write(df)
# Simple moving average strategy
df["SMA"] = df["Close"].rolling(window=20).mean()
df["Signal"] = 0
df["Signal"][20:] = np.where(df["Close"][20:] > df["SMA"][20:], 1, 0)
df["Position"] = df["Signal"].diff()
st.write(df)
# Save strategy data to database
with Session(engine) as session:
for index, row in df.iterrows():
strategy_data = StrategyData(stock=row['Stock'], date=row['Date'], price=row['Close'], signal=row['Signal'])
session.add(strategy_data)
session.commit()
# Plot results
plt.figure(figsize=(10,5))
plt.plot(df['Close'], label='Close Price')
plt.plot(df['SMA'], label='SMA 20', alpha=0.7)
plt.plot(df[df['Position'] == 1].index, df['SMA'][df['Position'] == 1], '^', markersize=10, color='g', lw=0, label='Buy Signal')
plt.plot(df[df['Position'] == -1].index, df['SMA'][df['Position'] == -1], 'v', markersize=10, color='r', lw=0, label='Sell Signal')
plt.title('Strategy Backtesting')
plt.legend()
st.pyplot()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?