Last active
July 17, 2023 20:46
-
-
Save sharavsambuu/bc65fa176d89b285e90762f924af5584 to your computer and use it in GitHub Desktop.
Streamlit template for Walk Forward stuffs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import streamlit as st | |
import pandas as pd | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from datetime import timedelta | |
def generate_stock_equity(start_date, end_date): | |
num_days = (end_date - start_date).days + 1 | |
changes = np.random.randint(low=-150, high=150, size=num_days) | |
date_range = pd.date_range(start=start_date, end=end_date, freq='D') | |
df = pd.DataFrame({'Date': date_range, 'Change': changes}) | |
df['Equity'] = df['Change'].cumsum() | |
df.set_index('Date', inplace=True) | |
df['max_equity'] = df['Equity'].cummax() | |
df['is_max' ] = df['Equity'] == df['max_equity'] | |
return df | |
def perform_backtest(start_date, end_date, asset): | |
stock_equity = generate_stock_equity(start_date, end_date) | |
higher_high_df = stock_equity[stock_equity['is_max']==True].copy() | |
higher_high_df['s'] = 100 | |
plt.figure(figsize=(18, 8)) | |
plt.plot(stock_equity.index, stock_equity['Equity'], color='blue') | |
plt.scatter(higher_high_df.index, higher_high_df['Equity'], color='green', s=higher_high_df['s']) | |
plt.xlabel('Date') | |
plt.ylabel('Equity') | |
plt.title(f'Equity for {asset}') | |
plt.xticks(rotation=45) | |
plt.grid(True) | |
st.pyplot(plt) | |
st.write('<style>div.block-container{padding-top:0.5rem;}</style>', unsafe_allow_html=True) | |
st.header('Walk-Forward Backtesting') | |
col1, col2, col3, col4 = st.columns(4) | |
with col1: | |
asset = st.text_input('Asset', value="btcusdt") | |
with col2: | |
timeframe = st.number_input('Timeframe', min_value=1, step=30, value=30) | |
with col3: | |
start_date = st.date_input('Start Date', min_value=None, max_value=None, key=None) | |
with col4: | |
backtesting_period = st.number_input('Period in months', min_value=1, step=1, value=6) | |
end_date = (start_date + timedelta(days=30 * backtesting_period)) if start_date else None | |
st.text(f'End Date: {end_date.strftime("%Y-%m-%d") if end_date else ""}') | |
if st.button('Perform Backtest'): | |
if not start_date: | |
st.error('Error: Start date is mandatory.') | |
elif start_date >= end_date: | |
st.error('Error: Invalid date range. Start date should be earlier than end date.') | |
elif not asset: | |
st.error('Error: Asset is mandatory.') | |
else: | |
perform_backtest(start_date, end_date, asset) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment