File size: 2,832 Bytes
89bad28
 
 
 
 
 
c72f1c6
89bad28
 
 
 
 
c72f1c6
 
 
89bad28
 
 
 
 
 
 
 
 
 
c72f1c6
89bad28
 
 
 
 
 
 
c72f1c6
89bad28
 
 
 
 
 
 
c72f1c6
89bad28
 
 
 
 
 
 
 
 
 
 
c72f1c6
89bad28
c72f1c6
 
 
 
 
 
 
89bad28
 
 
 
 
 
 
 
c72f1c6
 
 
 
89bad28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf

# Function to load historical data
@st.cache_data
def load_data(ticker):
    # Fetch data from Yahoo Finance
    return yf.download(ticker, start="2000-01-01", end="2023-01-01")

# User inputs for strategy parameters
st.title("Algorithmic Trading Strategy Backtesting")

ticker = st.text_input("Enter the ticker symbol", "AAPL")
data = load_data(ticker)

# Moving Average Windows
short_window = st.number_input("Short moving average window", 1, 50, 20)
long_window = st.number_input("Long moving average window", 1, 200, 50)

# Initial Capital
initial_capital = st.number_input("Initial Capital", 1000, 1000000, 100000)

# Data Preprocessing
# Calculate moving averages
data['Short_MA'] = data['Close'].rolling(window=short_window).mean()
data['Long_MA'] = data['Close'].rolling(window=long_window).mean()

# Drop NaN values
data.dropna(inplace=True)

# Generate Trading Signals
data['Signal'] = 0
data['Signal'][short_window:] = np.where(data['Short_MA'][short_window:] > data['Long_MA'][short_window:], 1, 0)
data['Position'] = data['Signal'].diff()

# Show signals in data
st.write(data.tail())

# Backtesting Engine
# Simulate portfolio
data['Portfolio Value'] = initial_capital
data['Portfolio Value'][short_window:] = initial_capital * (1 + data['Signal'][short_window:].shift(1) * data['Close'].pct_change()[short_window:]).cumprod()

# Performance metrics
cagr = (data['Portfolio Value'].iloc[-1] / initial_capital) ** (1 / ((data.index[-1] - data.index[short_window]).days / 365.25)) - 1
sharpe_ratio = data['Portfolio Value'].pct_change().mean() / data['Portfolio Value'].pct_change().std() * np.sqrt(252)

st.write(f"CAGR: {cagr:.2%}")
st.write(f"Sharpe Ratio: {sharpe_ratio:.2f}")

# Data Visualization
# Plot strategy performance
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(data.index, data['Portfolio Value'], label='Portfolio Value')
ax.set_title(f"Backtested Performance of {ticker} Strategy")
ax.set_xlabel("Date")
ax.set_ylabel("Portfolio Value")
ax.legend()
st.pyplot(fig)

# Highlight buy and sell signals
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(data.index, data['Close'], label='Close Price', alpha=0.5)
ax.plot(data.index, data['Short_MA'], label=f'Short MA ({short_window})', alpha=0.75)
ax.plot(data.index, data['Long_MA'], label=f'Long MA ({long_window})', alpha=0.75)
ax.plot(data[data['Position'] == 1].index, data['Short_MA'][data['Position'] == 1], '^', markersize=10, color='g', lw=0, label='Buy Signal')
ax.plot(data[data['Position'] == -1].index, data['Short_MA'][data['Position'] == -1], 'v', markersize=10, color='r', lw=0, label='Sell Signal')
ax.set_title(f"{ticker} Price and Trading Signals")
ax.set_xlabel("Date")
ax.set_ylabel("Price")
ax.legend()
st.pyplot(fig)